From 804f2d82918ce837af72c9077a1f35ec61cad588 Mon Sep 17 00:00:00 2001 From: Derik Badman Date: Fri, 28 Jun 2024 14:02:34 -0400 Subject: [PATCH] chore(release): 4.5.3 --- CHANGELOG.md | 2 + dist/index.js | 2 +- dist/index.js.map | 2 +- dist/service_worker.js | 2 +- dist/service_worker.js.map | 2 +- package-lock.json | 716 +++++++++++++++++++++++++++++-------- package.json | 2 +- 7 files changed, 569 insertions(+), 159 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c85090..74900ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines. +## [4.5.3](https://github.com/derikb/character-sheet-app/compare/v4.5.2...v4.5.3) (2024-06-28) + ## [4.5.2](https://github.com/derikb/character-sheet-app/compare/v4.5.1...v4.5.2) (2024-06-02) ## [4.5.1](https://github.com/derikb/character-sheet-app/compare/v4.5.0...v4.5.1) (2024-03-02) diff --git a/dist/index.js b/dist/index.js index 519e9f2..2e27992 100644 --- a/dist/index.js +++ b/dist/index.js @@ -455,7 +455,7 @@ dl.field-horizontal dt { -`;var nr=class extends Yn{constructor({emitter:e}){super({emitter:e,templateNode:Nf.content.cloneNode(!0)})}connectedCallback(){super.connectedCallback();let e=document.querySelector("footer-nav");e&&e.setLinks([{label:"Attributes",tab:"pane-stats",href:"#page-attributes"},{label:"Notes",tab:"pane-notes",href:"#page-notes"}])}disconnectedCallback(){super.disconnectedCallback()}_validateCharacter(e){if(!(e instanceof Ft))throw new Error("Invalid character type for this view.")}};window.customElements.get("sheet-view-vagabonds")||window.customElements.define("sheet-view-vagabonds",nr);var Lf=nr;var Of="4.5.2";var St=null,a_=Of,s_=function(){return new Date().toUTCString()},Kc=function(){let n=`${Math.random().toString(36)}00000000000000000`.slice(2,9);for(;ut(n)!==null;)n=`${Math.random().toString(36)}00000000000000000`.slice(2,9);return n},Mf=function(){return["Character5e","CharacterVagabonds"]},Hn=function(n,e){switch(n){case void 0:case"":case"Character5e":return new zt(e);case"CharacterVagabonds":return new Ft(e);default:return new et(e)}},i_=function(n,e="Character5e"){return Hn(e,{key:n})},ut=function(n){if(!n)return null;let e=fn.get(n);return!e||!e.key?null:Hn(e.className,e)},ar=async function(n){if(!n)return null;let e=await ss.get(n);return!e||!e.key?null:Hn(e.className,e)},is=function(n){return n.updated=s_(),n.version=a_,fn.set(n.key,n)},Qc=async function(n){return await ss.set(n.key,n.toJSON())},sr=function(n){fn.remove(n)},Vf=async function(n){return ss.remove(n)},At=function(){let n=[];return fn.getAll().forEach(e=>{n.push(Hn(e.className,e))}),n},zf=async function(){let n=new Map;return as()?((await ss.getAll()).forEach(t=>{let a=Hn(t.className,t);n.set(a.key,a)}),n):[]},Ff=function(n){if(typeof n!="object"||!n.key)throw new Error("Data appears to be invalid. Try removing any text that isn't part of the backup (i.e. email introduction).");let e=Hn(n.className,n),t=ut(n.key);if(t&&t.charname!==""&&t.charname!==e.charname)if(!e.key_prev)e.key_prev=e.key,e.key=Kc();else{let a=e.key_prev;e.key_prev=e.key,e.key=a}return is(e),e},jf=function(n){if(!n)throw Error("LocalStorage prefix is empty.");fn.setPrefix(n)},Uf=function(n,e,t=!1){let a=ut(n);if(!a){if(!t)return null;a=i_(n,e)}return St=a,St},qf=function(){return St},$n=function(){return St?St.key:""},Wf=function(){if(!St)throw new Error("No character is set.");if(St.charname==="")throw new Error("Your character must have name to save!");is(St)},Bf=function(n,e){let t=null;switch(n.className){case void 0:case"Character5e":t=new Pf({emitter:e});break;case"CharacterVagabonds":t=new Lf({emitter:e});break;default:t=new Yn({emitter:e});break}return t};var Jc=class{constructor(e){this.emitter=e,this.shortcuts={},document.addEventListener("keydown",this.checkShortCuts.bind(this))}addShortCut(e,t){this.shortcuts[e]=t}getKeyCode(e,t,a){let s="";return t&&(s+="Ctrl+"),a&&(s+="Shift+"),s+=e,s}checkShortCuts(e){let t=!1,a=!1;e.ctrlKey&&(t=!0),e.shiftKey&&(a=!0);let s=e.key,i=this.getKeyCode(s,t,a),o=this.shortcuts[i]||null;o&&(e.preventDefault(),e.stopPropagation(),this.emitter.trigger(o))}},Gf=Jc;var r_={emitter:null,appname:"",dialog_unsaved:document.querySelector(".alert-unsaved"),dialog_undo:document.querySelector(".alert-delete"),triggerNewCharacter:function(n=""){let e=Kc();this.loadCharacter(e,n).then(()=>{window.location.hash=`#${e}`}).catch(t=>{console.log(t)})},changeCharacter:function(){let n=window.location.hash.substring(1),e=$n();e&&n===e||this.loadCharacter(n)},loadCharacter:async function(n,e=""){this.hideUnsavedDialog();let t=Uf(n,e,!0);t.emitter=this.emitter;let a=Bf(t,this.emitter);document.querySelector("main").innerHTML="",document.querySelector("main").appendChild(a),a.character=t,this.emitter.trigger("loaddialog:close"),this.emitter.trigger("newdialog:close")},saveCharacter:function(){if(document.activeElement){let n=new Event("blur");document.activeElement.dispatchEvent(n)}try{Wf()}catch(n){this.emitter.trigger("error:display",n.message);return}this.hideUnsavedDialog()},downloadBackup:function(n){let e=[],t=[];Array.from(n.querySelectorAll("input[type=checkbox]:checked")).forEach(o=>{let c=ut(o.value);e.push(c),t.push(c.charname)});let s=n.querySelector("input[name=format]:checked").value,i=new Date;if(s==="email"){let o=`Below is the backup data for your character(s) ${t.join(", ")}. +`;var nr=class extends Yn{constructor({emitter:e}){super({emitter:e,templateNode:Nf.content.cloneNode(!0)})}connectedCallback(){super.connectedCallback();let e=document.querySelector("footer-nav");e&&e.setLinks([{label:"Attributes",tab:"pane-stats",href:"#page-attributes"},{label:"Notes",tab:"pane-notes",href:"#page-notes"}])}disconnectedCallback(){super.disconnectedCallback()}_validateCharacter(e){if(!(e instanceof Ft))throw new Error("Invalid character type for this view.")}};window.customElements.get("sheet-view-vagabonds")||window.customElements.define("sheet-view-vagabonds",nr);var Lf=nr;var Of="4.5.3";var St=null,a_=Of,s_=function(){return new Date().toUTCString()},Kc=function(){let n=`${Math.random().toString(36)}00000000000000000`.slice(2,9);for(;ut(n)!==null;)n=`${Math.random().toString(36)}00000000000000000`.slice(2,9);return n},Mf=function(){return["Character5e","CharacterVagabonds"]},Hn=function(n,e){switch(n){case void 0:case"":case"Character5e":return new zt(e);case"CharacterVagabonds":return new Ft(e);default:return new et(e)}},i_=function(n,e="Character5e"){return Hn(e,{key:n})},ut=function(n){if(!n)return null;let e=fn.get(n);return!e||!e.key?null:Hn(e.className,e)},ar=async function(n){if(!n)return null;let e=await ss.get(n);return!e||!e.key?null:Hn(e.className,e)},is=function(n){return n.updated=s_(),n.version=a_,fn.set(n.key,n)},Qc=async function(n){return await ss.set(n.key,n.toJSON())},sr=function(n){fn.remove(n)},Vf=async function(n){return ss.remove(n)},At=function(){let n=[];return fn.getAll().forEach(e=>{n.push(Hn(e.className,e))}),n},zf=async function(){let n=new Map;return as()?((await ss.getAll()).forEach(t=>{let a=Hn(t.className,t);n.set(a.key,a)}),n):[]},Ff=function(n){if(typeof n!="object"||!n.key)throw new Error("Data appears to be invalid. Try removing any text that isn't part of the backup (i.e. email introduction).");let e=Hn(n.className,n),t=ut(n.key);if(t&&t.charname!==""&&t.charname!==e.charname)if(!e.key_prev)e.key_prev=e.key,e.key=Kc();else{let a=e.key_prev;e.key_prev=e.key,e.key=a}return is(e),e},jf=function(n){if(!n)throw Error("LocalStorage prefix is empty.");fn.setPrefix(n)},Uf=function(n,e,t=!1){let a=ut(n);if(!a){if(!t)return null;a=i_(n,e)}return St=a,St},qf=function(){return St},$n=function(){return St?St.key:""},Wf=function(){if(!St)throw new Error("No character is set.");if(St.charname==="")throw new Error("Your character must have name to save!");is(St)},Bf=function(n,e){let t=null;switch(n.className){case void 0:case"Character5e":t=new Pf({emitter:e});break;case"CharacterVagabonds":t=new Lf({emitter:e});break;default:t=new Yn({emitter:e});break}return t};var Jc=class{constructor(e){this.emitter=e,this.shortcuts={},document.addEventListener("keydown",this.checkShortCuts.bind(this))}addShortCut(e,t){this.shortcuts[e]=t}getKeyCode(e,t,a){let s="";return t&&(s+="Ctrl+"),a&&(s+="Shift+"),s+=e,s}checkShortCuts(e){let t=!1,a=!1;e.ctrlKey&&(t=!0),e.shiftKey&&(a=!0);let s=e.key,i=this.getKeyCode(s,t,a),o=this.shortcuts[i]||null;o&&(e.preventDefault(),e.stopPropagation(),this.emitter.trigger(o))}},Gf=Jc;var r_={emitter:null,appname:"",dialog_unsaved:document.querySelector(".alert-unsaved"),dialog_undo:document.querySelector(".alert-delete"),triggerNewCharacter:function(n=""){let e=Kc();this.loadCharacter(e,n).then(()=>{window.location.hash=`#${e}`}).catch(t=>{console.log(t)})},changeCharacter:function(){let n=window.location.hash.substring(1),e=$n();e&&n===e||this.loadCharacter(n)},loadCharacter:async function(n,e=""){this.hideUnsavedDialog();let t=Uf(n,e,!0);t.emitter=this.emitter;let a=Bf(t,this.emitter);document.querySelector("main").innerHTML="",document.querySelector("main").appendChild(a),a.character=t,this.emitter.trigger("loaddialog:close"),this.emitter.trigger("newdialog:close")},saveCharacter:function(){if(document.activeElement){let n=new Event("blur");document.activeElement.dispatchEvent(n)}try{Wf()}catch(n){this.emitter.trigger("error:display",n.message);return}this.hideUnsavedDialog()},downloadBackup:function(n){let e=[],t=[];Array.from(n.querySelectorAll("input[type=checkbox]:checked")).forEach(o=>{let c=ut(o.value);e.push(c),t.push(c.charname)});let s=n.querySelector("input[name=format]:checked").value,i=new Date;if(s==="email"){let o=`Below is the backup data for your character(s) ${t.join(", ")}. To use this data, go to: ${window.location.href} and click the "Restore Backup" button. Then paste the text below into the box. diff --git a/dist/index.js.map b/dist/index.js.map index d239c77..9cadea1 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/services/EventEmitter.js", "../src/models/CharacterNote.js", "../src/models/Character.js", "../src/models/CharacterConstants5e.js", "../src/models/Weapon.js", "../src/models/Character5e.js", "../src/models/CharacterVagabonds.js", "../src/services/Storage.js", "../node_modules/@firebase/util/src/constants.ts", "../node_modules/@firebase/util/src/assert.ts", "../node_modules/@firebase/util/src/crypt.ts", "../node_modules/@firebase/util/src/deepCopy.ts", "../node_modules/@firebase/util/src/global.ts", "../node_modules/@firebase/util/src/defaults.ts", "../node_modules/@firebase/util/src/deferred.ts", "../node_modules/@firebase/util/src/emulator.ts", "../node_modules/@firebase/util/src/environment.ts", "../node_modules/@firebase/util/src/errors.ts", "../node_modules/@firebase/util/src/json.ts", "../node_modules/@firebase/util/src/jwt.ts", "../node_modules/@firebase/util/src/obj.ts", "../node_modules/@firebase/util/src/promise.ts", "../node_modules/@firebase/util/src/query.ts", "../node_modules/@firebase/util/src/sha1.ts", "../node_modules/@firebase/util/src/subscribe.ts", "../node_modules/@firebase/util/src/validation.ts", "../node_modules/@firebase/util/src/utf8.ts", "../node_modules/@firebase/util/src/uuid.ts", "../node_modules/@firebase/util/src/exponential_backoff.ts", "../node_modules/@firebase/util/src/formatters.ts", "../node_modules/@firebase/util/src/compat.ts", "../node_modules/@firebase/component/src/component.ts", "../node_modules/@firebase/component/src/constants.ts", "../node_modules/@firebase/component/src/provider.ts", "../node_modules/@firebase/component/src/component_container.ts", "../node_modules/@firebase/logger/src/logger.ts", "../node_modules/idb/build/wrap-idb-value.js", "../node_modules/idb/build/index.js", "../node_modules/@firebase/app/src/platformLoggerService.ts", "../node_modules/@firebase/app/src/logger.ts", "../node_modules/@firebase/app/src/constants.ts", "../node_modules/@firebase/app/src/internal.ts", "../node_modules/@firebase/app/src/errors.ts", "../node_modules/@firebase/app/src/firebaseApp.ts", "../node_modules/@firebase/app/src/firebaseServerApp.ts", "../node_modules/@firebase/app/src/api.ts", "../node_modules/@firebase/app/src/indexeddb.ts", "../node_modules/@firebase/app/src/heartbeatService.ts", "../node_modules/@firebase/app/src/registerCoreComponents.ts", "../node_modules/@firebase/app/src/index.ts", "../node_modules/node_modules/closure-net/firebase/bloom_blob_es2018.js", "../node_modules/node_modules/closure-net/firebase/webchannel_blob_es2018.js", "../node_modules/@firebase/firestore/src/auth/user.ts", "../node_modules/@firebase/firestore/src/core/version.ts", "../node_modules/@firebase/firestore/src/util/log.ts", "../node_modules/@firebase/firestore/src/platform/browser/format_json.ts", "../node_modules/@firebase/firestore/src/util/assert.ts", "../node_modules/@firebase/firestore/src/util/error.ts", "../node_modules/@firebase/firestore/src/util/promise.ts", "../node_modules/@firebase/firestore/src/api/credentials.ts", "../node_modules/@firebase/firestore/src/platform/browser/random_bytes.ts", "../node_modules/@firebase/firestore/src/util/misc.ts", "../node_modules/@firebase/firestore/src/lite-api/timestamp.ts", "../node_modules/@firebase/firestore/src/core/snapshot_version.ts", "../node_modules/@firebase/firestore/src/model/path.ts", "../node_modules/@firebase/firestore/src/model/document_key.ts", "../node_modules/@firebase/firestore/src/model/field_index.ts", "../node_modules/@firebase/firestore/src/local/persistence_transaction.ts", "../node_modules/@firebase/firestore/src/local/local_store.ts", "../node_modules/@firebase/firestore/src/local/persistence_promise.ts", "../node_modules/@firebase/firestore/src/local/simple_db.ts", "../node_modules/@firebase/firestore/src/local/index_backfiller.ts", "../node_modules/@firebase/firestore/src/core/listen_sequence.ts", "../node_modules/@firebase/firestore/src/util/types.ts", "../node_modules/@firebase/firestore/src/local/encoded_resource_path.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_sentinels.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_schema_legacy.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_transaction.ts", "../node_modules/@firebase/firestore/src/util/obj.ts", "../node_modules/@firebase/firestore/src/util/sorted_map.ts", "../node_modules/@firebase/firestore/src/util/sorted_set.ts", "../node_modules/@firebase/firestore/src/model/field_mask.ts", "../node_modules/@firebase/firestore/src/util/base64_decode_error.ts", "../node_modules/@firebase/firestore/src/platform/browser/base64.ts", "../node_modules/@firebase/firestore/src/util/byte_string.ts", "../node_modules/@firebase/firestore/src/model/normalize.ts", "../node_modules/@firebase/firestore/src/model/server_timestamps.ts", "../node_modules/@firebase/firestore/src/core/database_info.ts", "../node_modules/@firebase/firestore/src/model/values.ts", "../node_modules/@firebase/firestore/src/model/object_value.ts", "../node_modules/@firebase/firestore/src/model/document.ts", "../node_modules/@firebase/firestore/src/core/bound.ts", "../node_modules/@firebase/firestore/src/core/order_by.ts", "../node_modules/@firebase/firestore/src/core/filter.ts", "../node_modules/@firebase/firestore/src/core/target.ts", "../node_modules/@firebase/firestore/src/core/query.ts", "../node_modules/@firebase/firestore/src/util/obj_map.ts", "../node_modules/@firebase/firestore/src/model/collections.ts", "../node_modules/@firebase/firestore/src/remote/number_serializer.ts", "../node_modules/@firebase/firestore/src/model/transform_operation.ts", "../node_modules/@firebase/firestore/src/model/mutation.ts", "../node_modules/@firebase/firestore/src/model/mutation_batch.ts", "../node_modules/@firebase/firestore/src/model/overlay.ts", "../node_modules/@firebase/firestore/src/core/aggregate.ts", "../node_modules/@firebase/firestore/src/remote/existence_filter.ts", "../node_modules/@firebase/firestore/src/remote/rpc_error.ts", "../node_modules/@firebase/firestore/src/util/testing_hooks_spi.ts", "../node_modules/@firebase/firestore/src/platform/browser/text_serializer.ts", "../node_modules/@firebase/firestore/src/remote/bloom_filter.ts", "../node_modules/@firebase/firestore/src/remote/remote_event.ts", "../node_modules/@firebase/firestore/src/remote/watch_change.ts", "../node_modules/@firebase/firestore/src/remote/serializer.ts", "../node_modules/@firebase/firestore/src/local/target_data.ts", "../node_modules/@firebase/firestore/src/local/local_serializer.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_bundle_cache.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_document_overlay_cache.ts", "../node_modules/@firebase/firestore/src/index/firestore_index_value_writer.ts", "../node_modules/@firebase/firestore/src/index/ordered_code_writer.ts", "../node_modules/@firebase/firestore/src/index/index_byte_encoder.ts", "../node_modules/@firebase/firestore/src/index/index_entry.ts", "../node_modules/@firebase/firestore/src/model/target_index_matcher.ts", "../node_modules/@firebase/firestore/src/util/logic_utils.ts", "../node_modules/@firebase/firestore/src/local/memory_index_manager.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_index_manager.ts", "../node_modules/@firebase/firestore/src/local/lru_garbage_collector.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_mutation_batch_impl.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_mutation_queue.ts", "../node_modules/@firebase/firestore/src/core/target_id_generator.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_target_cache.ts", "../node_modules/@firebase/firestore/src/local/lru_garbage_collector_impl.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_lru_delegate_impl.ts", "../node_modules/@firebase/firestore/src/local/remote_document_change_buffer.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_remote_document_cache.ts", "../node_modules/@firebase/firestore/src/local/overlayed_document.ts", "../node_modules/@firebase/firestore/src/local/local_documents_view.ts", "../node_modules/@firebase/firestore/src/local/memory_bundle_cache.ts", "../node_modules/@firebase/firestore/src/local/memory_document_overlay_cache.ts", "../node_modules/@firebase/firestore/src/local/reference_set.ts", "../node_modules/@firebase/firestore/src/local/memory_mutation_queue.ts", "../node_modules/@firebase/firestore/src/local/memory_remote_document_cache.ts", "../node_modules/@firebase/firestore/src/local/memory_target_cache.ts", "../node_modules/@firebase/firestore/src/local/memory_persistence.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_schema_converter.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_persistence.ts", "../node_modules/@firebase/firestore/src/local/indexeddb_schema.ts", "../node_modules/@firebase/firestore/src/local/local_view_changes.ts", "../node_modules/@firebase/firestore/src/local/query_context.ts", "../node_modules/@firebase/firestore/src/local/query_engine.ts", "../node_modules/@firebase/firestore/src/local/local_store_impl.ts", "../node_modules/@firebase/firestore/src/local/shared_client_state_schema.ts", "../node_modules/@firebase/firestore/src/local/shared_client_state.ts", "../node_modules/@firebase/firestore/src/remote/connectivity_monitor_noop.ts", "../node_modules/@firebase/firestore/src/platform/browser/connectivity_monitor.ts", "../node_modules/@firebase/firestore/src/util/debug_uid.ts", "../node_modules/@firebase/firestore/src/remote/rest_connection.ts", "../node_modules/@firebase/firestore/src/remote/stream_bridge.ts", "../node_modules/@firebase/firestore/src/platform/browser/webchannel_connection.ts", "../node_modules/@firebase/firestore/src/platform/browser/dom.ts", "../node_modules/@firebase/firestore/src/platform/browser/serializer.ts", "../node_modules/@firebase/firestore/src/remote/backoff.ts", "../node_modules/@firebase/firestore/src/remote/persistent_stream.ts", "../node_modules/@firebase/firestore/src/remote/datastore.ts", "../node_modules/@firebase/firestore/src/remote/online_state_tracker.ts", "../node_modules/@firebase/firestore/src/remote/remote_store.ts", "../node_modules/@firebase/firestore/src/util/async_queue.ts", "../node_modules/@firebase/firestore/src/model/document_set.ts", "../node_modules/@firebase/firestore/src/core/view_snapshot.ts", "../node_modules/@firebase/firestore/src/core/event_manager.ts", "../node_modules/@firebase/firestore/src/util/bundle_reader.ts", "../node_modules/@firebase/firestore/src/core/bundle_impl.ts", "../node_modules/@firebase/firestore/src/core/view.ts", "../node_modules/@firebase/firestore/src/core/sync_engine_impl.ts", "../node_modules/@firebase/firestore/src/core/component_provider.ts", "../node_modules/@firebase/firestore/src/platform/browser/connection.ts", "../node_modules/@firebase/firestore/src/util/byte_stream.ts", "../node_modules/@firebase/firestore/src/util/async_observer.ts", "../node_modules/@firebase/firestore/src/util/bundle_reader_impl.ts", "../node_modules/@firebase/firestore/src/core/transaction.ts", "../node_modules/@firebase/firestore/src/core/transaction_runner.ts", "../node_modules/@firebase/firestore/src/core/firestore_client.ts", "../node_modules/@firebase/firestore/src/platform/browser/byte_stream_reader.ts", "../node_modules/@firebase/firestore/src/util/array.ts", "../node_modules/@firebase/firestore/src/api/long_polling_options.ts", "../node_modules/@firebase/firestore/src/lite-api/components.ts", "../node_modules/@firebase/firestore/src/util/input_validation.ts", "../node_modules/@firebase/firestore/src/lite-api/settings.ts", "../node_modules/@firebase/firestore/src/lite-api/database.ts", "../node_modules/@firebase/firestore/src/lite-api/reference.ts", "../node_modules/@firebase/firestore/src/util/async_queue_impl.ts", "../node_modules/@firebase/firestore/src/api/observer.ts", "../node_modules/@firebase/firestore/src/api/bundle.ts", "../node_modules/@firebase/firestore/src/api/database.ts", "../node_modules/@firebase/firestore/src/lite-api/aggregate_types.ts", "../node_modules/@firebase/firestore/src/lite-api/bytes.ts", "../node_modules/@firebase/firestore/src/lite-api/field_path.ts", "../node_modules/@firebase/firestore/src/lite-api/field_value.ts", "../node_modules/@firebase/firestore/src/lite-api/geo_point.ts", "../node_modules/@firebase/firestore/src/lite-api/user_data_reader.ts", "../node_modules/@firebase/firestore/src/lite-api/snapshot.ts", "../node_modules/@firebase/firestore/src/lite-api/query.ts", "../node_modules/@firebase/firestore/src/lite-api/user_data_writer.ts", "../node_modules/@firebase/firestore/src/lite-api/reference_impl.ts", "../node_modules/@firebase/firestore/src/lite-api/aggregate.ts", "../node_modules/@firebase/firestore/src/api/snapshot.ts", "../node_modules/@firebase/firestore/src/api/reference_impl.ts", "../node_modules/@firebase/firestore/src/api/aggregate.ts", "../node_modules/@firebase/firestore/src/api/cache_config.ts", "../node_modules/@firebase/firestore/src/core/transaction_options.ts", "../node_modules/@firebase/firestore/src/lite-api/write_batch.ts", "../node_modules/@firebase/firestore/src/api/transaction.ts", "../node_modules/@firebase/firestore/src/lite-api/transaction.ts", "../node_modules/@firebase/firestore/src/lite-api/field_value_impl.ts", "../node_modules/@firebase/firestore/src/api/write_batch.ts", "../node_modules/@firebase/firestore/src/api/index_configuration.ts", "../node_modules/@firebase/firestore/src/api/persistent_cache_index_manager.ts", "../node_modules/@firebase/firestore/src/remote/internal_serializer.ts", "../node_modules/@firebase/firestore/src/util/testing_hooks.ts", "../node_modules/@firebase/firestore/src/register.ts", "../node_modules/@firebase/firestore/src/index.ts", "../node_modules/firebase/app/index.ts", "../src/config/firebase.js", "../src/services/firebaseService.js", "../node_modules/tslib/tslib.es6.mjs", "../node_modules/@firebase/auth/src/model/enum_maps.ts", "../node_modules/@firebase/auth/src/core/errors.ts", "../node_modules/@firebase/auth/src/core/util/log.ts", "../node_modules/@firebase/auth/src/core/util/assert.ts", "../node_modules/@firebase/auth/src/core/util/location.ts", "../node_modules/@firebase/auth/src/core/util/navigator.ts", "../node_modules/@firebase/auth/src/core/util/delay.ts", "../node_modules/@firebase/auth/src/core/util/emulator.ts", "../node_modules/@firebase/auth/src/core/util/fetch_provider.ts", "../node_modules/@firebase/auth/src/api/errors.ts", "../node_modules/@firebase/auth/src/api/index.ts", "../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha.ts", "../node_modules/@firebase/auth/src/api/authentication/recaptcha.ts", "../node_modules/@firebase/auth/src/api/account_management/account.ts", "../node_modules/@firebase/auth/src/core/util/time.ts", "../node_modules/@firebase/auth/src/core/user/id_token_result.ts", "../node_modules/@firebase/auth/src/core/user/invalidation.ts", "../node_modules/@firebase/auth/src/core/user/proactive_refresh.ts", "../node_modules/@firebase/auth/src/core/user/user_metadata.ts", "../node_modules/@firebase/auth/src/core/user/reload.ts", "../node_modules/@firebase/auth/src/api/authentication/token.ts", "../node_modules/@firebase/auth/src/core/user/token_manager.ts", "../node_modules/@firebase/auth/src/core/user/user_impl.ts", "../node_modules/@firebase/auth/src/core/util/instantiator.ts", "../node_modules/@firebase/auth/src/core/persistence/in_memory.ts", "../node_modules/@firebase/auth/src/core/persistence/persistence_user_manager.ts", "../node_modules/@firebase/auth/src/core/util/browser.ts", "../node_modules/@firebase/auth/src/core/util/version.ts", "../node_modules/@firebase/auth/src/core/auth/middleware.ts", "../node_modules/@firebase/auth/src/api/password_policy/get_password_policy.ts", "../node_modules/@firebase/auth/src/core/auth/password_policy_impl.ts", "../node_modules/@firebase/auth/src/core/auth/auth_impl.ts", "../node_modules/@firebase/auth/src/platform_browser/load_js.ts", "../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts", "../node_modules/@firebase/auth/src/core/auth/initialize.ts", "../node_modules/@firebase/auth/src/core/auth/emulator.ts", "../node_modules/@firebase/auth/src/core/credentials/auth_credential.ts", "../node_modules/@firebase/auth/src/api/account_management/email_and_password.ts", "../node_modules/@firebase/auth/src/api/authentication/email_and_password.ts", "../node_modules/@firebase/auth/src/api/authentication/email_link.ts", "../node_modules/@firebase/auth/src/core/credentials/email.ts", "../node_modules/@firebase/auth/src/api/authentication/idp.ts", "../node_modules/@firebase/auth/src/core/credentials/oauth.ts", "../node_modules/@firebase/auth/src/api/authentication/sms.ts", "../node_modules/@firebase/auth/src/core/credentials/phone.ts", "../node_modules/@firebase/auth/src/core/action_code_url.ts", "../node_modules/@firebase/auth/src/core/providers/email.ts", "../node_modules/@firebase/auth/src/core/providers/federated.ts", "../node_modules/@firebase/auth/src/core/providers/oauth.ts", "../node_modules/@firebase/auth/src/core/providers/facebook.ts", "../node_modules/@firebase/auth/src/core/providers/google.ts", "../node_modules/@firebase/auth/src/core/providers/github.ts", "../node_modules/@firebase/auth/src/core/credentials/saml.ts", "../node_modules/@firebase/auth/src/core/providers/saml.ts", "../node_modules/@firebase/auth/src/core/providers/twitter.ts", "../node_modules/@firebase/auth/src/api/authentication/sign_up.ts", "../node_modules/@firebase/auth/src/core/user/user_credential_impl.ts", "../node_modules/@firebase/auth/src/core/strategies/anonymous.ts", "../node_modules/@firebase/auth/src/mfa/mfa_error.ts", "../node_modules/@firebase/auth/src/core/util/providers.ts", "../node_modules/@firebase/auth/src/core/user/link_unlink.ts", "../node_modules/@firebase/auth/src/core/user/reauthenticate.ts", "../node_modules/@firebase/auth/src/core/strategies/credential.ts", "../node_modules/@firebase/auth/src/api/authentication/custom_token.ts", "../node_modules/@firebase/auth/src/core/strategies/custom_token.ts", "../node_modules/@firebase/auth/src/mfa/mfa_info.ts", "../node_modules/@firebase/auth/src/core/strategies/action_code_settings.ts", "../node_modules/@firebase/auth/src/core/strategies/email_and_password.ts", "../node_modules/@firebase/auth/src/core/strategies/email_link.ts", "../node_modules/@firebase/auth/src/api/authentication/create_auth_uri.ts", "../node_modules/@firebase/auth/src/core/strategies/email.ts", "../node_modules/@firebase/auth/src/api/account_management/profile.ts", "../node_modules/@firebase/auth/src/core/user/account_info.ts", "../node_modules/@firebase/auth/src/core/user/additional_user_info.ts", "../node_modules/@firebase/auth/src/core/index.ts", "../node_modules/@firebase/auth/src/mfa/mfa_session.ts", "../node_modules/@firebase/auth/src/mfa/mfa_resolver.ts", "../node_modules/@firebase/auth/src/api/account_management/mfa.ts", "../node_modules/@firebase/auth/src/mfa/mfa_user.ts", "../node_modules/@firebase/auth/src/core/persistence/index.ts", "../node_modules/@firebase/auth/src/platform_browser/persistence/browser.ts", "../node_modules/@firebase/auth/src/platform_browser/persistence/local_storage.ts", "../node_modules/@firebase/auth/src/platform_browser/persistence/session_storage.ts", "../node_modules/@firebase/auth/src/platform_browser/messagechannel/promise.ts", "../node_modules/@firebase/auth/src/platform_browser/messagechannel/receiver.ts", "../node_modules/@firebase/auth/src/core/util/event_id.ts", "../node_modules/@firebase/auth/src/platform_browser/messagechannel/sender.ts", "../node_modules/@firebase/auth/src/platform_browser/auth_window.ts", "../node_modules/@firebase/auth/src/platform_browser/util/worker.ts", "../node_modules/@firebase/auth/src/platform_browser/persistence/indexed_db.ts", "../node_modules/@firebase/auth/src/api/authentication/mfa.ts", "../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_mock.ts", "../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_loader.ts", "../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_verifier.ts", "../node_modules/@firebase/auth/src/platform_browser/strategies/phone.ts", "../node_modules/@firebase/auth/src/platform_browser/providers/phone.ts", "../node_modules/@firebase/auth/src/core/util/resolver.ts", "../node_modules/@firebase/auth/src/core/strategies/idp.ts", "../node_modules/@firebase/auth/src/core/strategies/abstract_popup_redirect_operation.ts", "../node_modules/@firebase/auth/src/platform_browser/strategies/popup.ts", "../node_modules/@firebase/auth/src/core/strategies/redirect.ts", "../node_modules/@firebase/auth/src/platform_browser/strategies/redirect.ts", "../node_modules/@firebase/auth/src/core/auth/auth_event_manager.ts", "../node_modules/@firebase/auth/src/api/project_config/get_project_config.ts", "../node_modules/@firebase/auth/src/core/util/validate_origin.ts", "../node_modules/@firebase/auth/src/platform_browser/iframe/gapi.ts", "../node_modules/@firebase/auth/src/platform_browser/iframe/iframe.ts", "../node_modules/@firebase/auth/src/platform_browser/util/popup.ts", "../node_modules/@firebase/auth/src/core/util/handler.ts", "../node_modules/@firebase/auth/src/platform_browser/popup_redirect.ts", "../node_modules/@firebase/auth/src/mfa/mfa_assertion.ts", "../node_modules/@firebase/auth/src/platform_browser/mfa/assertions/phone.ts", "../node_modules/@firebase/auth/src/mfa/assertions/totp.ts", "../node_modules/@firebase/auth/src/core/auth/firebase_internal.ts", "../node_modules/@firebase/auth/src/core/auth/register.ts", "../node_modules/@firebase/auth/src/platform_browser/index.ts", "../src/services/AuthService.js", "../src/services/Database.js", "../src/views/Tabs.js", "../src/views/SheetView.js", "../src/views/Character5eSheet.js", "../src/views/CharacterVagabondsSheet.js", "../package.json", "../src/services/CharacterService.js", "../src/views/ShortCutKeys.js", "../src/views/Manager.js", "../src/components/ConfirmButton.js", "../src/services/syncService.js", "../src/components/SyncInfo.js", "../src/views/ActionMenu.js", "../src/components/NoteListItem.js", "../src/utils/setCursorAtContentEnd.js", "../src/components/NoteList.js", "../src/components/SimpleList.js", "../src/components/TableEditable.js", "../src/components/SkillListing.js", "../src/components/AttributeListing.js", "../node_modules/rpg-table-randomizer/src/randomizer.js", "../node_modules/rpg-table-randomizer/src/dice_roller.js", "../src/utils/dragger.js", "../src/components/Die.js", "../src/components/DiceRoller.js", "../src/components/EditableField.js", "../src/components/FooterNav.js", "../src/components/Modal.js", "../src/5e-SRD-Spells.json", "../src/components/SpellItem.js", "../src/components/AddSpellButton.js", "../src/index.js"], - "sourcesContent": ["/**\n * @prop {Object} events Store the events here.\n * @prop {Boolean} debug So you can more easily in dev see when events are triggered.\n */\nexport default class EventEmitter {\n constructor () {\n this.events = {};\n this.debug = false;\n }\n /**\n * Get index of listener in the event array.\n * -1 means it isn't there\n * @param {String} event Event to check.\n * @param {Function} listener Listener to check.\n * @return {Number}\n */\n listenerIndex (event, listener) {\n return this.events[event].findIndex((item) => {\n return item.listener === listener;\n });\n }\n /**\n * Listen to an event\n * @param {String} event Name of the event to listen for.\n * @param {Function|Array} listener Callback to trigger for event OR an array of [classname, methodName]\n * @param {Object} boundObj Object to bind the callback to.\n * @return {undefined}\n */\n on (event, listener, boundObj = null) {\n if (typeof listener !== 'function') {\n return;\n }\n this.events[event] = this.events[event] || [];\n if (this.events[event].length > 0) {\n const index = this.listenerIndex(event, listener);\n // Replace the listener if it already exists.\n if (index > -1) {\n this.events[event].splice(index, 1);\n }\n }\n this.events[event].push({ listener, boundObj });\n }\n /**\n * Stop listening to an event.\n * Remove event if it was the last listener.\n * @param {String} event Name of the event.\n * @param {Function} listener Callback to remove.\n * @return {undefined}\n */\n off (event, listener) {\n if (Array.isArray(this.events[event])) {\n const index = this.listenerIndex(event, listener);\n if (index === -1) {\n return;\n }\n this.events[event].splice(index, 1);\n if (this.events[event].length === 0) {\n delete this.events[event];\n }\n }\n }\n /**\n * Listen for an event but only trigger it once, then it is removed.\n * @param {String} event Name of the event to listen for.\n * @param {Function} listener Callback to trigger for event.\n * @param {Object} boundObj Object to bind the callback to.\n */\n once (event, listener, boundObj) {\n this.on(event, function wrap () {\n this.off(event, wrap);\n const binder = typeof boundObj === 'undefined' ? this : boundObj;\n listener.apply(binder, arguments);\n });\n }\n /**\n * Trigger an event. This will cause any listeners for that event to be called.\n * Any arguments after the event will be passed on to the callback(s).\n * @param {String} event Event to trigger.\n */\n trigger (event) {\n if (this.debug && console) {\n console.log(`EventEmitter triggered: ${event}`);\n }\n const args = [].slice.call(arguments, 1);\n\n if (Array.isArray(this.events[event])) {\n this.events[event].forEach((listenObj) => {\n const binder = listenObj.boundObj === null ? this : listenObj.boundObj;\n listenObj.listener.apply(binder, args);\n });\n }\n };\n};\n", "/** Note object */\nexport default class CharacterNote {\n constructor ({\n header = '',\n text = ''\n }) {\n this.header = header;\n this.text = text;\n }\n toJSON () {\n const obj = {};\n const props = Object.getOwnPropertyNames(this);\n props.forEach((prop) => {\n obj[prop] = this[prop];\n });\n return obj;\n }\n};\n", "import CharacterNote from './CharacterNote.js';\n\n/**\n * Generic Character Modal.\n * Extend for different rules/games/properties.\n * This is only props/methods that apply to all.\n * Another not set here, should only be used in the appropriate SheetView.\n *\n * @prop {String} key Unique (in one instance of the app) id for the character. 7 Random letters/numbers.\n * @prop {String} charname Name.\n * @prop {String} updated UTC date string.\n * @prop {String} key_prev If character was imported into app with identical key. This is that key and the character is given a new one on import.\n * @prop {String} version Version number (semver format) of app.\n */\nexport default class Character {\n constructor ({\n key = '',\n charname = '',\n updated = '',\n key_prev = '',\n version = ''\n }) {\n this.key = key;\n this.charname = charname;\n this.updated = updated;\n this.key_prev = key_prev;\n this.version = version;\n }\n /**\n * Localized last updated string.\n */\n get updatedTime () {\n const date = new Date(this.updated);\n return date.toLocaleString();\n }\n /**\n * Class name (for JSON (de)serialization). Override in children.\n */\n get className () {\n return 'Character';\n }\n /**\n * Ruleset name. Override in children.\n */\n get ruleset () {\n return 'Generic';\n }\n /**\n * A quick summary header for use in lists.\n */\n get summaryHeader () {\n return `${this.charname} (${this.ruleset})`;\n }\n /**\n * Convert notes arrays from Array[] or Object[] to CharacterNotes[]\n * @param {Array} noteArray\n * @returns\n */\n _convertNotes (noteArray) {\n const value = [];\n noteArray.forEach((item) => {\n // Remove null and non-objects\n if (item && typeof item !== 'object') {\n return;\n }\n if (item instanceof CharacterNote) {\n value.push(item);\n return;\n }\n // @version < 3.0.0 backwards compat\n if (Array.isArray(item)) {\n // convert\n value.push(new CharacterNote({\n header: item[0] || '',\n text: item[1] || ''\n }));\n return;\n }\n value.push(new CharacterNote(item));\n });\n return value;\n }\n /**\n * Converting _ props for saving.\n * @returns {Object}\n */\n toJSON () {\n const obj = {\n className: this.className\n };\n const props = Object.getOwnPropertyNames(this);\n props.forEach((prop) => {\n if (prop === 'emitter') {\n return;\n }\n let value = this[prop];\n if (Array.isArray(value)) {\n value = value.map((el) => {\n if (typeof el.toJSON === 'function') {\n return el.toJSON();\n }\n return el;\n });\n }\n if (prop.substring(0, 1) === '_') {\n obj[prop.substring(1)] = value;\n } else {\n obj[prop] = value;\n }\n });\n return obj;\n }\n}\n", "/**\n * Matching attribute full names to the character properties.\n */\nexport const attributes = Object.freeze({\n STRENGTH: 'str',\n DEXTERITY: 'dex',\n CONSTITUTION: 'con',\n INTELLIGENCE: 'intel',\n WISDOM: 'wis',\n CHARISMA: 'cha'\n});\n\n/**\n * Matching skills to attributes.\n */\nexport const skillAttributes = Object.freeze({\n acrobatics: attributes.DEXTERITY,\n animal_handling: attributes.WISDOM,\n arcana: attributes.INTELLIGENCE,\n athletics: attributes.STRENGTH,\n deception: attributes.CHARISMA,\n history: attributes.INTELLIGENCE,\n insight: attributes.WISDOM,\n intimidation: attributes.CHARISMA,\n investigation: attributes.INTELLIGENCE,\n medicine: attributes.WISDOM,\n nature: attributes.INTELLIGENCE,\n perception: attributes.WISDOM,\n performance: attributes.CHARISMA,\n persuasion: attributes.CHARISMA,\n religion: attributes.INTELLIGENCE,\n sleight_of_hand: attributes.DEXTERITY,\n stealth: attributes.DEXTERITY,\n survival: attributes.WISDOM\n});\n\nexport const skillLevels = Object.freeze({\n UNSKILLED: 0,\n PROFICIENT: 1,\n EXPERT: 2\n});\n", "/** Weapon object */\nexport default class Weapon {\n constructor ({\n name = '',\n attack = '',\n damage = '',\n notes = ''\n }) {\n this.name = name;\n this.attack = attack;\n this.damage = damage;\n this.notes = notes;\n }\n toJSON () {\n const obj = {};\n const props = Object.getOwnPropertyNames(this);\n props.forEach((prop) => {\n obj[prop] = this[prop];\n });\n return obj;\n }\n};\n", "/**\n * Model for 5e character data\n */\n\nimport { skillAttributes, skillLevels } from './CharacterConstants5e.js';\nimport Weapon from './Weapon.js';\nimport Character from './Character.js';\n\nexport default class Character5e extends Character {\n /**\n * Property notes...\n * @prop {String} key Unique (in one instance of the app) id for the character. 7 Random letters/numbers.\n * @prop {String} charname Name.\n * @prop {Object} class_points Class point like ki, sorcerer points, etc.\n * @prop {Number} class_points.cur\n * @prop {Number} class_points.max\n * @prop {Weapon[]} weapons Weapon data (name, att, dam, notes).\n * @prop {String[]} features Special features and abilities.\n * @prop {String[]} equipment Stuff the character carries.\n * @prop {CharacterNote[]} notes_adv Adventure notes\n * @prop {CharacterNote[]} notes_cam Campaign notes\n * @prop {CharacterNote[]} npcs NPC notes\n * @prop {CharacterNote[]} factions NPC notes\n * @prop {CharacterNote[]} partymembers Other party members.\n * @prop {Object} skills Skill and its level. 0/1/2 (See skillLevels).\n */\n constructor ({\n key = '',\n charname = '',\n charclass = '',\n race = '',\n background = '',\n alignment = '',\n level = 1,\n experience = 0,\n inspiration = '',\n armor_class = '',\n speed = 30,\n hp_cur = '',\n hp_max = '',\n hd_cur = '',\n hd_max = '',\n deathSave = {\n success: 0,\n fail: 0\n },\n class_points = {\n cur: 0,\n max: 0\n },\n str = 10,\n dex = 10,\n con = 10,\n intel = 10,\n wis = 10,\n cha = 10,\n saves = {\n str: 0,\n dex: 0,\n con: 0,\n intel: 0,\n wis: 0,\n cha: 0\n },\n skills = {\n acrobatics: 0,\n animal_handling: 0,\n arcana: 0,\n athletics: 0,\n deception: 0,\n history: 0,\n insight: 0,\n intimidation: 0,\n investigation: 0,\n medicine: 0,\n nature: 0,\n perception: 0,\n performance: 0,\n persuasion: 0,\n religion: 0,\n sleight_of_hand: 0,\n stealth: 0,\n survival: 0\n },\n weapons = [],\n proficiencies_other = '',\n languages = '',\n traits = '',\n ideals = '',\n bonds = '',\n flaws = '',\n appearance = '',\n equipment = [],\n cp = '',\n sp = '',\n gp = '',\n pp = '',\n features = [],\n notes = '',\n notes_adv = [],\n notes_cam = [],\n npcs = [],\n factions = [],\n partymembers = [],\n spell_ability = '',\n spell_save = '',\n spell_attack = '',\n spell_slots = {\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0,\n 7: 0,\n 8: 0,\n 9: 0\n },\n spell_slots_cur = {\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0,\n 7: 0,\n 8: 0,\n 9: 0\n },\n spells = {\n 0: [],\n 1: [],\n 2: [],\n 3: [],\n 4: [],\n 5: [],\n 6: [],\n 7: [],\n 8: [],\n 9: []\n },\n updated = '',\n key_prev = '',\n version = ''\n }) {\n super({\n key,\n charname,\n updated,\n key_prev,\n version\n });\n this.charclass = charclass;\n this.race = race;\n this.background = background;\n this.alignment = alignment;\n // use underscore so we can use getter/setters on level itself.\n this._level = level;\n this.experience = experience;\n this.inspiration = inspiration;\n this.armor_class = armor_class;\n this.speed = speed;\n this.hp_cur = hp_cur;\n this.hp_max = hp_max;\n this.hd_cur = hd_cur;\n this.hd_max = hd_max;\n this.deathSave = deathSave;\n this.class_points = class_points;\n this.str = str;\n this.dex = dex;\n this.con = con;\n this.intel = intel;\n this.wis = wis;\n this.cha = cha;\n this.saves = saves;\n this.skills = skills;\n // @version < 2.2.0 Backwards compatibile convert sleight_of_Hand to sleight_of_hand\n if (typeof this.skills.sleight_of_Hand !== 'undefined') {\n const sleight = this.skills.sleight_of_Hand;\n delete this.skills.sleight_of_Hand;\n this.skills.sleight_of_hand = sleight;\n }\n\n this.weapons = [];\n weapons.forEach((item) => {\n // Remove null and non-objects\n if (item && typeof item !== 'object') {\n return;\n }\n // @version < 3.0.0 backwards compat\n if (Array.isArray(item)) {\n // convert\n this.weapons.push(new Weapon({\n name: item[0] || '',\n attack: item[1] || '',\n damage: item[2] || '',\n notes: item[3] || ''\n }));\n return;\n }\n if (item instanceof Weapon) {\n this.weapons.push(item);\n return;\n }\n this.weapons.push(new Weapon(item));\n });\n\n this.proficiencies_other = proficiencies_other;\n this.languages = languages;\n this.traits = traits;\n this.ideals = ideals;\n this.bonds = bonds;\n this.flaws = flaws;\n this.appearance = appearance;\n this.equipment = equipment;\n this.cp = cp;\n this.sp = sp;\n this.gp = gp;\n this.pp = pp;\n this.features = features;\n this.notes = notes;\n this.notes_adv = this._convertNotes(notes_adv);\n this.notes_cam = this._convertNotes(notes_cam);\n this.npcs = this._convertNotes(npcs);\n this.factions = this._convertNotes(factions);\n this.partymembers = this._convertNotes(partymembers);\n this.spell_ability = spell_ability;\n this.spell_save = spell_save;\n this.spell_attack = spell_attack;\n this.spell_slots = spell_slots;\n this.spell_slots_cur = spell_slots_cur;\n this.spells = spells;\n\n this.emitter = null;\n }\n get className () {\n return 'Character5e';\n }\n get ruleset () {\n return '5e';\n }\n /**\n * Level getter.\n * @returns {Number}\n */\n get level () {\n return this._level;\n }\n /**\n * Set level and trigger proficiency update if necessary.\n * @param {Number}\n */\n set level (newVal) {\n const cur = this.level;\n if (newVal === cur) {\n return;\n }\n const prof = this.proficiency;\n this._level = newVal;\n const newProf = this.proficiency;\n if (prof === newProf) {\n return;\n }\n if (this.emitter) {\n this.emitter.trigger('character:proficiency:update');\n }\n }\n /**\n * Proficiency modifier as string.\n * @returns {String}\n */\n get proficiency () {\n const bonus = Math.ceil(this.level / 4) + 1;\n return `+${bonus}`;\n }\n /**\n * Set an attribute score.\n * @param {String} attribute\n * @param {Number} value\n */\n setAttribute (attribute, value) {\n if (!this[attribute]) {\n return;\n }\n const curVal = this[attribute];\n if (curVal === value) {\n return;\n }\n this[attribute] = value;\n if (this.emitter) {\n this.emitter.trigger('character:attribute:update', attribute);\n // Update any relevant skill mods.\n for (const skill in skillAttributes) {\n if (skillAttributes[skill] === attribute) {\n this.emitter.trigger('character:skill:update', skill, this.getSkillMod(skill));\n }\n }\n }\n }\n /**\n * Get modifier for an attribute.\n * @param {String} attribute Attribute short code\n * @returns {String}\n */\n attributeMod (attribute) {\n const score = this[attribute];\n if (Number.isNaN(score)) {\n return '0';\n }\n const raw = Math.floor((score - 10) / 2);\n return (raw > 0) ? `+${raw}` : raw.toString();\n }\n /**\n * Are they proficient in a skill.\n * @param {String} skill\n * @returns {Boolean}\n */\n isProficient (skill) {\n return this.skills[skill] > skillLevels.UNSKILLED;\n }\n /**\n * Are they expert in a skill.\n * @param {String} skill\n * @returns {Boolean}\n */\n isExpert (skill) {\n return this.skills[skill] === skillLevels.EXPERT;\n }\n /**\n * Get the modifier for a skill.\n * @param {String} skill\n * @returns {String}\n */\n getSkillMod (skill) {\n let raw = 0;\n const skillLevel = this.skills[skill];\n if (typeof skillLevel === 'undefined') {\n return 0;\n }\n const attribute = skillAttributes[skill];\n if (attribute) {\n raw += parseInt(this.attributeMod(attribute), 10);\n }\n const prof = parseInt(this.proficiency, 10);\n if (this.isProficient(skill)) {\n raw += prof;\n }\n if (this.isExpert(skill)) {\n raw += prof;\n }\n return (raw > 0) ? `+${raw}` : raw.toString();\n }\n /**\n * Get skill proficiency\n * @param {String} skill\n * @returns {Number}\n */\n getSkill (skill) {\n const value = this.skills[skill];\n if (typeof value === 'undefined') {\n return null;\n }\n return value;\n }\n /**\n * Set a skill proficiency.\n * @param {String} skill\n * @param {Number} newValue\n */\n setSkill (skill, newValue) {\n const curValue = this.getSkill(skill);\n if (curValue === null || curValue === newValue) {\n return;\n }\n this.skills[skill] = newValue;\n if (this.emitter) {\n this.emitter.trigger('character:skill:update', skill, this.getSkillMod(skill));\n }\n }\n /**\n * Is the attribute save proficient.\n * @param {String} attr\n * @returns {Number}\n */\n isSaveProficient (attr) {\n return (this.saves[attr] || 0);\n }\n /**\n * Get the save modifier for an attribute.\n * @param {String} attr\n * @returns {String}\n */\n saveMod (attr) {\n let profMod = 0;\n if (this.isSaveProficient(attr)) {\n profMod = parseInt(this.proficiency, 10);\n }\n const raw = 0 + profMod + parseInt(this.attributeMod(attr), 10);\n return (raw > 0) ? `+${raw}` : raw.toString();\n }\n /**\n * Set/unset a save proficiency.\n * @param {String} attr\n * @param {Number} checked\n */\n setSaveProficiency (attr, checked) {\n const cur = this.saves[attr];\n if (typeof cur === 'undefined') {\n return;\n }\n if (cur === checked) {\n return;\n }\n this.saves[attr] = (checked ? 1 : 0);\n if (this.emitter) {\n this.emitter.trigger('character:save:update', attr);\n }\n }\n\n /**\n * Returns the spells. Include the level to get by level\n * @param {Number} level\n * @returns {Array}\n */\n getSpells (level = undefined) {\n if (level in this.spells) {\n return this.spells[level];\n }\n\n return this.spells;\n }\n /**\n * Set the spells\n * @param {Object} spell\n * @param {Number} level\n */\n setSpells (spell, level) {\n const spells = this.spells[level];\n\n if (typeof spells === 'undefined') {\n return;\n }\n\n // Temporary\n if (typeof spell === 'object') {\n spell = spell.name;\n }\n\n const newSpellsList = [...spells, spell];\n const newSpellSlotsLength = this.spell_slots[level] + 1;\n\n this.spell_slots[level] = newSpellSlotsLength;\n this.spells[level] = newSpellsList;\n\n if (this.emitter) {\n this.emitter.trigger('character:update:spells');\n this.emitter.trigger('dialog:save:show');\n }\n }\n};\n", "/**\n * Model for Vagabonds of Dyfed character\n */\nimport Character from './Character.js';\n\nexport default class CharacterVagabonds extends Character {\n /**\n * @prop {String} key Unique (in one instance of the app) id for the character. 7 Random letters/numbers.\n * @prop {String} charname Name.\n * @prop {Number} level\n * @prop {String} conflict_approach\n * @prop {String} goal\n * @prop {String} gimmick\n * @prop {String} background\n * @prop {String} foreground\n * @prop {String} weakness\n * @prop {String} core_flaw\n * @prop {String[]} techniques\n * @prop {String[]} traits\n * @prop {Number} hp_cur\n * @prop {Number} hp_max\n * @prop {Number} armor\n * @prop {String} initiative\n * @prop {String[]} lineage\n * @prop {Number} experience\n * @prop {String} appearance\n * @prop {String} personality\n * @prop {String[]} inventory\n * @prop {Number} coins\n * @prop {String[]} injuries\n * @prop {String} notes\n * @prop {CharacterNote[]} notes_adv Adventure notes\n * @prop {CharacterNote[]} notes_cam Campaign notes\n * @prop {CharacterNote[]} npcs NPC notes\n * @prop {CharacterNote[]} factions NPC notes\n * @prop {CharacterNote[]} partymembers Other party members.\n * @prop {String} key_prev If character was imported into app with identical key. This is that key and the character is given a new one on import.\n */\n constructor ({\n key = '',\n charname = '',\n level = 1,\n conflict_approach = '',\n goal = '',\n gimmick = '',\n background = '',\n foreground = '',\n weakness = '',\n core_flaw = '',\n techniques = [],\n traits = [],\n hp_cur = 0,\n hp_max = 0,\n armor = 0,\n initiative = '0',\n lineage = [],\n experience = 0,\n appearance = '',\n personality = '',\n inventory = [],\n coins = 0,\n injuries = [],\n notes = '',\n notes_adv = [],\n notes_cam = [],\n npcs = [],\n factions = [],\n partymembers = [],\n updated = '',\n key_prev = '',\n version = ''\n }) {\n super({\n key,\n charname,\n updated,\n key_prev,\n version\n });\n this.level = level;\n this.conflict_approach = conflict_approach;\n this.goal = goal;\n this.gimmick = gimmick;\n this.background = background;\n this.foreground = foreground;\n this.weakness = weakness;\n this.core_flaw = core_flaw;\n this.techniques = techniques;\n this.traits = traits;\n this.hp_cur = hp_cur;\n this.hp_max = hp_max;\n this.armor = armor;\n this.initiative = initiative;\n this.lineage = lineage;\n this.experience = experience;\n this.appearance = appearance;\n this.personality = personality;\n this.inventory = inventory;\n this.coins = coins;\n this.injuries = injuries;\n this.notes = notes;\n this.notes_adv = this._convertNotes(notes_adv);\n this.notes_cam = this._convertNotes(notes_cam);\n this.npcs = this._convertNotes(npcs);\n this.factions = this._convertNotes(factions);\n this.partymembers = this._convertNotes(partymembers);\n\n this.emitter = null;\n }\n /**\n * Class name (for JSON (de)serialization). Override in children.\n */\n get className () {\n return 'CharacterVagabonds';\n }\n /**\n * Ruleset name. Override in children.\n */\n get ruleset () {\n return 'Vagabonds';\n }\n};\n", "/**\n * LocalStorage interface\n */\nconst Storage = {\n /**\n * A prefix to attack to the random keys to differentiate them from any other storage for the current location/domain\n */\n prefix: '',\n /**\n * Set the prefix\n * @param {String} prefix string to prefix the randomly generated key\n */\n setPrefix: function (prefix) {\n this.prefix = prefix;\n },\n /**\n * Returns blank or the value for the key\n * @param {String} key\n * @return {Object|Null} object or null\n */\n get: function (key) {\n try {\n const txt = localStorage.getItem(`${this.prefix}${key}`);\n return (txt !== null) ? JSON.parse(txt) : null;\n } catch (e) {\n return null;\n }\n },\n /**\n * Store a value for the key\n * Warning: browsers vary for the amount of data you can store (usually ~5mb)\n * @param {String} key\n * @param {Object} object\n * @return {Boolean} returns false on error\n */\n set: function (key, object) {\n try {\n localStorage.setItem(`${this.prefix}${key}`, JSON.stringify(object));\n } catch (e) {\n // Should only happen when over quota\n console.log(e.message);\n return false;\n }\n return true;\n },\n /**\n * Remove a key\n * @param {String} key\n * @return void\n */\n remove: function (key) {\n localStorage.removeItem(`${this.prefix}${key}`);\n },\n /**\n * Get an array of all keys with the key prefix\n * @return {Array}\n */\n getAllKeys: function () {\n const keys = [];\n if (localStorage.length > 0) {\n const key_regex = new RegExp(`^(${this.prefix})+`, 'i');\n for (let i = 0; i < localStorage.length; i++) {\n let key = localStorage.key(i);\n key = key.replace(key_regex, '');\n keys.push(key);\n }\n }\n return keys;\n },\n /**\n * Get all objects from the store.\n * @returns Object[]\n */\n getAll: function () {\n const keys = this.getAllKeys();\n const objects = [];\n keys.forEach((key) => {\n const char_obj = Storage.get(key);\n if (!char_obj || !char_obj.key) {\n return;\n }\n objects.push(char_obj);\n });\n return objects;\n }\n};\n\nexport default Storage;\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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_()\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';\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 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 promiseified 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 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';\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", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 * 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 */\nexport function isBrowser(): boolean {\n return typeof self === 'object' && self.self === self;\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/**\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 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 sychronously 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 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 * Copied from https://stackoverflow.com/a/2117523\n * Generates a new uuid.\n * @public\n */\nexport const uuidv4 = function (): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = (Math.random() * 16) | 0,\n v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\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/**\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 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 mulitple 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 mulitple 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/can not 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", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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", "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", "/**\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 {\n ComponentContainer,\n ComponentType,\n Provider,\n Name\n} from '@firebase/component';\nimport { PlatformLoggerService, VersionService } from './types';\n\nexport class PlatformLoggerServiceImpl implements PlatformLoggerService {\n constructor(private readonly container: ComponentContainer) {}\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString(): string {\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() as VersionService;\n return `${service.library}/${service.version}`;\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: Provider): boolean {\n const component = provider.getComponent();\n return component?.type === ComponentType.VERSION;\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 { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app');\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 { name as appName } from '../package.json';\nimport { name as appCompatName } from '../../app-compat/package.json';\nimport { name as analyticsCompatName } from '../../../packages/analytics-compat/package.json';\nimport { name as analyticsName } from '../../../packages/analytics/package.json';\nimport { name as appCheckCompatName } from '../../../packages/app-check-compat/package.json';\nimport { name as appCheckName } from '../../../packages/app-check/package.json';\nimport { name as authName } from '../../../packages/auth/package.json';\nimport { name as authCompatName } from '../../../packages/auth-compat/package.json';\nimport { name as databaseName } from '../../../packages/database/package.json';\nimport { name as databaseCompatName } from '../../../packages/database-compat/package.json';\nimport { name as functionsName } from '../../../packages/functions/package.json';\nimport { name as functionsCompatName } from '../../../packages/functions-compat/package.json';\nimport { name as installationsName } from '../../../packages/installations/package.json';\nimport { name as installationsCompatName } from '../../../packages/installations-compat/package.json';\nimport { name as messagingName } from '../../../packages/messaging/package.json';\nimport { name as messagingCompatName } from '../../../packages/messaging-compat/package.json';\nimport { name as performanceName } from '../../../packages/performance/package.json';\nimport { name as performanceCompatName } from '../../../packages/performance-compat/package.json';\nimport { name as remoteConfigName } from '../../../packages/remote-config/package.json';\nimport { name as remoteConfigCompatName } from '../../../packages/remote-config-compat/package.json';\nimport { name as storageName } from '../../../packages/storage/package.json';\nimport { name as storageCompatName } from '../../../packages/storage-compat/package.json';\nimport { name as firestoreName } from '../../../packages/firestore/package.json';\nimport { name as vertexName } from '../../../packages/vertexai/package.json';\nimport { name as firestoreCompatName } from '../../../packages/firestore-compat/package.json';\nimport { name as packageName } from '../../../packages/firebase/package.json';\n\n/**\n * The default app name\n *\n * @internal\n */\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\nexport const PLATFORM_LOG_STRING = {\n [appName]: 'fire-core',\n [appCompatName]: 'fire-core-compat',\n [analyticsName]: 'fire-analytics',\n [analyticsCompatName]: 'fire-analytics-compat',\n [appCheckName]: 'fire-app-check',\n [appCheckCompatName]: 'fire-app-check-compat',\n [authName]: 'fire-auth',\n [authCompatName]: 'fire-auth-compat',\n [databaseName]: 'fire-rtdb',\n [databaseCompatName]: 'fire-rtdb-compat',\n [functionsName]: 'fire-fn',\n [functionsCompatName]: 'fire-fn-compat',\n [installationsName]: 'fire-iid',\n [installationsCompatName]: 'fire-iid-compat',\n [messagingName]: 'fire-fcm',\n [messagingCompatName]: 'fire-fcm-compat',\n [performanceName]: 'fire-perf',\n [performanceCompatName]: 'fire-perf-compat',\n [remoteConfigName]: 'fire-rc',\n [remoteConfigCompatName]: 'fire-rc-compat',\n [storageName]: 'fire-gcs',\n [storageCompatName]: 'fire-gcs-compat',\n [firestoreName]: 'fire-fst',\n [firestoreCompatName]: 'fire-fst-compat',\n [vertexName]: 'fire-vertex',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [packageName]: 'fire-js-all'\n} as const;\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 {\n FirebaseApp,\n FirebaseOptions,\n FirebaseServerApp\n} from './public-types';\nimport { Component, Provider, Name } from '@firebase/component';\nimport { logger } from './logger';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { FirebaseServerAppImpl } from './firebaseServerApp';\n\n/**\n * @internal\n */\nexport const _apps = new Map();\n\n/**\n * @internal\n */\nexport const _serverApps = new Map();\n\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _components = new Map>();\n\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nexport function _addComponent(\n app: FirebaseApp,\n component: Component\n): void {\n try {\n (app as FirebaseAppImpl).container.addComponent(component);\n } catch (e) {\n logger.debug(\n `Component ${component.name} failed to register with FirebaseApp ${app.name}`,\n e\n );\n }\n}\n\n/**\n *\n * @internal\n */\nexport function _addOrOverwriteComponent(\n app: FirebaseApp,\n component: Component\n): void {\n (app as FirebaseAppImpl).container.addOrOverwriteComponent(component);\n}\n\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nexport function _registerComponent(\n component: Component\n): boolean {\n const componentName = component.name;\n if (_components.has(componentName)) {\n logger.debug(\n `There were multiple attempts to register component ${componentName}.`\n );\n\n return false;\n }\n\n _components.set(componentName, component);\n\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app as FirebaseAppImpl, component);\n }\n\n for (const serverApp of _serverApps.values()) {\n _addComponent(serverApp as FirebaseServerAppImpl, component);\n }\n\n return true;\n}\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 */\nexport function _getProvider(\n app: FirebaseApp,\n name: T\n): Provider {\n const heartbeatController = (app as FirebaseAppImpl).container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return (app as FirebaseAppImpl).container.getProvider(name);\n}\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 */\nexport function _removeServiceInstance(\n app: FirebaseApp,\n name: T,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n): void {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n\n/**\n *\n * @param obj - an object of type FirebaseApp or FirebaseOptions.\n *\n * @returns true if the provide object is of type FirebaseApp.\n *\n * @internal\n */\nexport function _isFirebaseApp(\n obj: FirebaseApp | FirebaseOptions\n): obj is FirebaseApp {\n return (obj as FirebaseApp).options !== undefined;\n}\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 */\nexport function _isFirebaseServerApp(\n obj: FirebaseApp | FirebaseServerApp\n): obj is FirebaseServerApp {\n return (obj as FirebaseServerApp).settings !== undefined;\n}\n\n/**\n * Test only\n *\n * @internal\n */\nexport function _clearComponents(): void {\n _components.clear();\n}\n\n/**\n * Exported in order to be used in app-compat package\n */\nexport { DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME };\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 { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\n BAD_APP_NAME = 'bad-app-name',\n DUPLICATE_APP = 'duplicate-app',\n APP_DELETED = 'app-deleted',\n SERVER_APP_DELETED = 'server-app-deleted',\n NO_OPTIONS = 'no-options',\n INVALID_APP_ARGUMENT = 'invalid-app-argument',\n INVALID_LOG_ARGUMENT = 'invalid-log-argument',\n IDB_OPEN = 'idb-open',\n IDB_GET = 'idb-get',\n IDB_WRITE = 'idb-set',\n IDB_DELETE = 'idb-delete',\n FINALIZATION_REGISTRY_NOT_SUPPORTED = 'finalization-registry-not-supported',\n INVALID_SERVER_APP_ENVIRONMENT = 'invalid-server-app-environment'\n}\n\nconst ERRORS: ErrorMap = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call initializeApp() first',\n [AppError.BAD_APP_NAME]: \"Illegal App name: '{$appName}'\",\n [AppError.DUPLICATE_APP]:\n \"Firebase App named '{$appName}' already exists with different options or config\",\n [AppError.APP_DELETED]: \"Firebase App named '{$appName}' already deleted\",\n [AppError.SERVER_APP_DELETED]: 'Firebase Server App has been deleted',\n [AppError.NO_OPTIONS]:\n 'Need to provide options, when not being deployed to hosting via source.',\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [AppError.INVALID_LOG_ARGUMENT]:\n 'First argument to `onLog` must be null or a function.',\n [AppError.IDB_OPEN]:\n 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_GET]:\n 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_WRITE]:\n 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_DELETE]:\n 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED]:\n 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\n [AppError.INVALID_SERVER_APP_ENVIRONMENT]:\n 'FirebaseServerApp is not for use in browser environments.'\n};\n\ninterface ErrorParams {\n [AppError.NO_APP]: { appName: string };\n [AppError.BAD_APP_NAME]: { appName: string };\n [AppError.DUPLICATE_APP]: { appName: string };\n [AppError.APP_DELETED]: { appName: string };\n [AppError.INVALID_APP_ARGUMENT]: { appName: string };\n [AppError.IDB_OPEN]: { originalErrorMessage?: string };\n [AppError.IDB_GET]: { originalErrorMessage?: string };\n [AppError.IDB_WRITE]: { originalErrorMessage?: string };\n [AppError.IDB_DELETE]: { originalErrorMessage?: string };\n [AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED]: { appName?: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory(\n 'app',\n 'Firebase',\n 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 */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport {\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { ERROR_FACTORY, AppError } from './errors';\n\nexport class FirebaseAppImpl implements FirebaseApp {\n protected readonly _options: FirebaseOptions;\n protected readonly _name: string;\n /**\n * Original config values passed in as a constructor parameter.\n * It is only used to compare with another config object to support idempotent initializeApp().\n *\n * Updating automaticDataCollectionEnabled on the App instance will not change its value in _config.\n */\n private readonly _config: Required;\n private _automaticDataCollectionEnabled: boolean;\n protected _isDeleted = false;\n private readonly _container: ComponentContainer;\n\n constructor(\n options: FirebaseOptions,\n config: Required,\n container: ComponentContainer\n ) {\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(\n new Component('app', () => this, ComponentType.PUBLIC)\n );\n }\n\n get automaticDataCollectionEnabled(): boolean {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val: boolean) {\n this.checkDestroyed();\n this._automaticDataCollectionEnabled = val;\n }\n\n get name(): string {\n this.checkDestroyed();\n return this._name;\n }\n\n get options(): FirebaseOptions {\n this.checkDestroyed();\n return this._options;\n }\n\n get config(): Required {\n this.checkDestroyed();\n return this._config;\n }\n\n get container(): ComponentContainer {\n return this._container;\n }\n\n get isDeleted(): boolean {\n return this._isDeleted;\n }\n\n set isDeleted(val: boolean) {\n this._isDeleted = val;\n }\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 protected checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.APP_DELETED, { appName: this._name });\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\nimport {\n FirebaseAppSettings,\n FirebaseServerApp,\n FirebaseServerAppSettings,\n FirebaseOptions\n} from './public-types';\nimport { deleteApp, registerVersion } from './api';\nimport { ComponentContainer } from '@firebase/component';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport { name as packageName, version } from '../package.json';\n\nexport class FirebaseServerAppImpl\n extends FirebaseAppImpl\n implements FirebaseServerApp\n{\n private readonly _serverConfig: FirebaseServerAppSettings;\n private _finalizationRegistry: FinalizationRegistry;\n private _refCount: number;\n\n constructor(\n options: FirebaseOptions | FirebaseAppImpl,\n serverConfig: FirebaseServerAppSettings,\n name: string,\n container: ComponentContainer\n ) {\n // Build configuration parameters for the FirebaseAppImpl base class.\n const automaticDataCollectionEnabled =\n serverConfig.automaticDataCollectionEnabled !== undefined\n ? serverConfig.automaticDataCollectionEnabled\n : false;\n\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\n const config: Required = {\n name,\n automaticDataCollectionEnabled\n };\n\n if ((options as FirebaseOptions).apiKey !== undefined) {\n // Construct the parent FirebaseAppImp object.\n super(options as FirebaseOptions, config, container);\n } else {\n const appImpl: FirebaseAppImpl = options as FirebaseAppImpl;\n super(appImpl.options, config, container);\n }\n\n // Now construct the data for the FirebaseServerAppImpl.\n this._serverConfig = {\n automaticDataCollectionEnabled,\n ...serverConfig\n };\n\n this._finalizationRegistry = new FinalizationRegistry(() => {\n this.automaticCleanup();\n });\n\n this._refCount = 0;\n this.incRefCount(this._serverConfig.releaseOnDeref);\n\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegisry\n // will never trigger.\n this._serverConfig.releaseOnDeref = undefined;\n serverConfig.releaseOnDeref = undefined;\n\n registerVersion(packageName, version, 'serverapp');\n }\n\n toJSON(): undefined {\n return undefined;\n }\n\n get refCount(): number {\n return this._refCount;\n }\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: object | undefined): void {\n if (this.isDeleted) {\n return;\n }\n this._refCount++;\n if (obj !== undefined) {\n this._finalizationRegistry.register(obj, this);\n }\n }\n\n // Decrement the reference count.\n decRefCount(): number {\n if (this.isDeleted) {\n return 0;\n }\n return --this._refCount;\n }\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 private automaticCleanup(): void {\n void deleteApp(this);\n }\n\n get settings(): FirebaseServerAppSettings {\n this.checkDestroyed();\n return this._serverConfig;\n }\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 protected checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.SERVER_APP_DELETED);\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\nimport {\n FirebaseApp,\n FirebaseServerApp,\n FirebaseOptions,\n FirebaseAppSettings,\n FirebaseServerAppSettings\n} from './public-types';\nimport { DEFAULT_ENTRY_NAME, PLATFORM_LOG_STRING } from './constants';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport {\n ComponentContainer,\n Component,\n Name,\n ComponentType\n} from '@firebase/component';\nimport { version } from '../../firebase/package.json';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { FirebaseServerAppImpl } from './firebaseServerApp';\nimport {\n _apps,\n _components,\n _isFirebaseApp,\n _registerComponent,\n _serverApps\n} from './internal';\nimport { logger } from './logger';\nimport {\n LogLevelString,\n setLogLevel as setLogLevelImpl,\n LogCallback,\n LogOptions,\n setUserLogHandler\n} from '@firebase/logger';\nimport { deepEqual, getDefaultAppConfig, isBrowser } from '@firebase/util';\n\nexport { FirebaseError } from '@firebase/util';\n\n/**\n * The current SDK version.\n *\n * @public\n */\nexport const SDK_VERSION = version;\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseApp} instance.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize default app\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * });\n * ```\n *\n * @example\n * ```javascript\n *\n * // Initialize another app\n * const otherApp = initializeApp({\n * databaseURL: \"https://.firebaseio.com\",\n * storageBucket: \".appspot.com\"\n * }, \"otherApp\");\n * ```\n *\n * @param options - Options to configure the app's services.\n * @param name - Optional name of the app to initialize. If no name\n * is provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The initialized app.\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n name?: string\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @param options - Options to configure the app's services.\n * @param config - FirebaseApp Configuration\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n config?: FirebaseAppSettings\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @public\n */\nexport function initializeApp(): FirebaseApp;\nexport function initializeApp(\n _options?: FirebaseOptions,\n rawConfig = {}\n): FirebaseApp {\n let options = _options;\n\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n\n const config: Required = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: false,\n ...rawConfig\n };\n const name = config.name;\n\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(AppError.BAD_APP_NAME, {\n appName: String(name)\n });\n }\n\n options ||= getDefaultAppConfig();\n\n if (!options) {\n throw ERROR_FACTORY.create(AppError.NO_OPTIONS);\n }\n\n const existingApp = _apps.get(name) as FirebaseAppImpl;\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (\n deepEqual(options, existingApp.options) &&\n deepEqual(config, existingApp.config)\n ) {\n return existingApp;\n } else {\n throw ERROR_FACTORY.create(AppError.DUPLICATE_APP, { appName: name });\n }\n }\n\n const container = new ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseAppImpl(options, config, container);\n\n _apps.set(name, newApp);\n\n return newApp;\n}\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseServerApp} instance.\n *\n * The `FirebaseServerApp` is similar to `FirebaseApp`, but is intended for execution in\n * server side rendering environments only. Initialization will fail if invoked from a\n * browser environment.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize an instance of `FirebaseServerApp`.\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeServerApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * },\n * {\n * authIdToken: \"Your Auth ID Token\"\n * });\n * ```\n *\n * @param options - `Firebase.AppOptions` to configure the app's services, or a\n * a `FirebaseApp` instance which contains the `AppOptions` within.\n * @param config - `FirebaseServerApp` configuration.\n *\n * @returns The initialized `FirebaseServerApp`.\n *\n * @public\n */\nexport function initializeServerApp(\n options: FirebaseOptions | FirebaseApp,\n config: FirebaseServerAppSettings\n): FirebaseServerApp;\n\nexport function initializeServerApp(\n _options: FirebaseOptions | FirebaseApp,\n _serverAppConfig: FirebaseServerAppSettings\n): FirebaseServerApp {\n if (isBrowser()) {\n // FirebaseServerApp isn't designed to be run in browsers.\n throw ERROR_FACTORY.create(AppError.INVALID_SERVER_APP_ENVIRONMENT);\n }\n\n if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {\n _serverAppConfig.automaticDataCollectionEnabled = false;\n }\n\n let appOptions: FirebaseOptions;\n if (_isFirebaseApp(_options)) {\n appOptions = _options.options;\n } else {\n appOptions = _options;\n }\n\n // Build an app name based on a hash of the configuration options.\n const nameObj = {\n ..._serverAppConfig,\n ...appOptions\n };\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\n const hashCode = (s: string): number => {\n return [...s].reduce(\n (hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0,\n 0\n );\n };\n\n if (_serverAppConfig.releaseOnDeref !== undefined) {\n if (typeof FinalizationRegistry === 'undefined') {\n throw ERROR_FACTORY.create(\n AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED,\n {}\n );\n }\n }\n\n const nameString = '' + hashCode(JSON.stringify(nameObj));\n const existingApp = _serverApps.get(nameString) as FirebaseServerApp;\n if (existingApp) {\n (existingApp as FirebaseServerAppImpl).incRefCount(\n _serverAppConfig.releaseOnDeref\n );\n return existingApp;\n }\n\n const container = new ComponentContainer(nameString);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseServerAppImpl(\n appOptions,\n _serverAppConfig,\n nameString,\n container\n );\n\n _serverApps.set(nameString, newApp);\n\n return newApp;\n}\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 */\nexport function getApp(name: string = DEFAULT_ENTRY_NAME): FirebaseApp {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n\n return app;\n}\n\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nexport function getApps(): FirebaseApp[] {\n return Array.from(_apps.values());\n}\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 */\nexport async function deleteApp(app: FirebaseApp): Promise {\n let cleanupProviders = false;\n const name = app.name;\n if (_apps.has(name)) {\n cleanupProviders = true;\n _apps.delete(name);\n } else if (_serverApps.has(name)) {\n const firebaseServerApp = app as FirebaseServerAppImpl;\n if (firebaseServerApp.decRefCount() <= 0) {\n _serverApps.delete(name);\n cleanupProviders = true;\n }\n }\n\n if (cleanupProviders) {\n await Promise.all(\n (app as FirebaseAppImpl).container\n .getProviders()\n .map(provider => provider.delete())\n );\n (app as FirebaseAppImpl).isDeleted = true;\n }\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 */\nexport function registerVersion(\n libraryKeyOrName: string,\n version: string,\n variant?: string\n): void {\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(\n `library name \"${library}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(\n `version name \"${version}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n logger.warn(warning.join(' '));\n return;\n }\n _registerComponent(\n new Component(\n `${library}-version` as Name,\n () => ({ library, version }),\n ComponentType.VERSION\n )\n );\n}\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 */\nexport function onLog(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(AppError.INVALID_LOG_ARGUMENT);\n }\n setUserLogHandler(logCallback, options);\n}\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 */\nexport function setLogLevel(logLevel: LogLevelString): void {\n setLogLevelImpl(logLevel);\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 { FirebaseError } from '@firebase/util';\nimport { DBSchema, openDB, IDBPDatabase } from 'idb';\nimport { AppError, ERROR_FACTORY } from './errors';\nimport { FirebaseApp } from './public-types';\nimport { HeartbeatsInIndexedDB } from './types';\nimport { logger } from './logger';\n\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\n\ninterface AppDB extends DBSchema {\n 'firebase-heartbeat-store': {\n key: string;\n value: HeartbeatsInIndexedDB;\n };\n}\n\nlet dbPromise: Promise> | null = null;\nfunction getDbPromise(): Promise> {\n if (!dbPromise) {\n dbPromise = 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 } 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(AppError.IDB_OPEN, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\n\nexport async function readHeartbeatsFromIndexedDB(\n app: FirebaseApp\n): Promise {\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 } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_GET, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nexport async function writeHeartbeatsToIndexedDB(\n app: FirebaseApp,\n heartbeatObject: HeartbeatsInIndexedDB\n): Promise {\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 } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_WRITE, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.name}!${app.options.appId}`;\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 { ComponentContainer } from '@firebase/component';\nimport {\n base64urlEncodeWithoutPadding,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport {\n readHeartbeatsFromIndexedDB,\n writeHeartbeatsToIndexedDB\n} from './indexeddb';\nimport { FirebaseApp } from './public-types';\nimport {\n HeartbeatsByUserAgent,\n HeartbeatService,\n HeartbeatsInIndexedDB,\n HeartbeatStorage,\n SingleDateHeartbeat\n} from './types';\n\nconst MAX_HEADER_BYTES = 1024;\n// 30 days\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\n\nexport class HeartbeatServiceImpl implements HeartbeatService {\n /**\n * The persistence layer for heartbeats\n * Leave public for easier testing.\n */\n _storage: HeartbeatStorageImpl;\n\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 _heartbeatsCache: HeartbeatsInIndexedDB | null = null;\n\n /**\n * the initialization promise for populating heartbeatCache.\n * If getHeartbeatsHeader() is called before the promise resolves\n * (hearbeatsCache == null), it should wait for this promise\n * Leave public for easier testing.\n */\n _heartbeatsCachePromise: Promise;\n constructor(private readonly container: ComponentContainer) {\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 /**\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(): Promise {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n\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 (\n this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(\n singleDateHeartbeat => singleDateHeartbeat.date === date\n )\n ) {\n return;\n } else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n }\n // Remove entries older than 30 days.\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(\n singleDateHeartbeat => {\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\n const now = Date.now();\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\n }\n );\n return this._storage.overwrite(this._heartbeatsCache);\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(): Promise {\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 (\n this._heartbeatsCache?.heartbeats == null ||\n this._heartbeatsCache.heartbeats.length === 0\n ) {\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(\n this._heartbeatsCache.heartbeats\n );\n const headerString = base64urlEncodeWithoutPadding(\n JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })\n );\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 } 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}\n\nfunction getUTCDateString(): string {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\n\nexport function extractHeartbeatsForHeader(\n heartbeatsCache: SingleDateHeartbeat[],\n maxSize = MAX_HEADER_BYTES\n): {\n heartbeatsToSend: HeartbeatsByUserAgent[];\n unsentEntries: SingleDateHeartbeat[];\n} {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend: HeartbeatsByUserAgent[] = [];\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(\n hb => hb.agent === singleDateHeartbeat.agent\n );\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 } 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}\n\nexport class HeartbeatStorageImpl implements HeartbeatStorage {\n private _canUseIndexedDBPromise: Promise;\n constructor(public app: FirebaseApp) {\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck(): Promise {\n if (!isIndexedDBAvailable()) {\n return false;\n } else {\n return validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read(): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n } else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n if (idbHeartbeatObject?.heartbeats) {\n return idbHeartbeatObject;\n } else {\n return { heartbeats: [] };\n }\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject: HeartbeatsInIndexedDB): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject: HeartbeatsInIndexedDB): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\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 */\nexport function countBytes(heartbeatsCache: HeartbeatsByUserAgent[]): number {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })\n ).length;\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 { Component, ComponentType } from '@firebase/component';\nimport { PlatformLoggerServiceImpl } from './platformLoggerService';\nimport { name, version } from '../package.json';\nimport { _registerComponent } from './internal';\nimport { registerVersion } from './api';\nimport { HeartbeatServiceImpl } from './heartbeatService';\n\nexport function registerCoreComponents(variant?: string): void {\n _registerComponent(\n new Component(\n 'platform-logger',\n container => new PlatformLoggerServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n _registerComponent(\n new Component(\n 'heartbeat',\n container => new HeartbeatServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n\n // Register `app` package.\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n", "/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\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\nimport { registerCoreComponents } from './registerCoreComponents';\n\nexport * from './api';\nexport * from './internal';\nexport * from './public-types';\n\nregisterCoreComponents('__RUNTIME_ENV__');\n", "/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n(function() {'use strict';var h;/** @license\n\n Copyright The Closure Library Authors.\n SPDX-License-Identifier: Apache-2.0\n*/\nfunction k(f,a){function c(){}c.prototype=a.prototype;f.D=a.prototype;f.prototype=new c;f.prototype.constructor=f;f.C=function(d,e,g){for(var b=Array(arguments.length-2),r=2;re;++e)d[e]=a.charCodeAt(c++)|a.charCodeAt(c++)<<8|a.charCodeAt(c++)<<16|a.charCodeAt(c++)<<24;else for(e=0;16>e;++e)d[e]=a[c++]|a[c++]<<8|a[c++]<<16|a[c++]<<24;a=f.g[0];c=f.g[1];e=f.g[2];var g=f.g[3];var b=a+(g^c&(e^g))+d[0]+3614090360&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[1]+3905402710&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[2]+606105819&4294967295;e=g+(b<<17&4294967295|b>>>15);\nb=c+(a^e&(g^a))+d[3]+3250441966&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[4]+4118548399&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[5]+1200080426&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[6]+2821735955&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[7]+4249261313&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[8]+1770035416&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[9]+2336552879&4294967295;g=a+(b<<12&4294967295|\nb>>>20);b=e+(c^g&(a^c))+d[10]+4294925233&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[11]+2304563134&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[12]+1804603682&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[13]+4254626195&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[14]+2792965006&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[15]+1236535329&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(e^g&(c^e))+d[1]+4129170786&4294967295;a=c+(b<<\n5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[6]+3225465664&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[11]+643717713&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[0]+3921069994&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[5]+3593408605&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[10]+38016083&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[15]+3634488961&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[4]+3889429448&4294967295;c=\ne+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[9]+568446438&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[14]+3275163606&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[3]+4107603335&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[8]+1163531501&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[13]+2850285829&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[2]+4243563512&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[7]+1735328473&4294967295;\ne=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[12]+2368359562&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(c^e^g)+d[5]+4294588738&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[8]+2272392833&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[11]+1839030562&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[14]+4259657740&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[1]+2763975236&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[4]+1272893353&4294967295;g=a+(b<<11&4294967295|\nb>>>21);b=e+(g^a^c)+d[7]+4139469664&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[10]+3200236656&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[13]+681279174&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[0]+3936430074&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[3]+3572445317&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[6]+76029189&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[9]+3654602809&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[12]+\n3873151461&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[15]+530742520&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[2]+3299628645&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(e^(c|~g))+d[0]+4096336452&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[7]+1126891415&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[14]+2878612391&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[5]+4237533241&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[12]+1700485571&\n4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[3]+2399980690&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[10]+4293915773&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[1]+2240044497&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[8]+1873313359&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[15]+4264355552&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[6]+2734768916&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[13]+1309151649&\n4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[4]+4149444226&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[11]+3174756917&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[2]+718787259&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[9]+3951481745&4294967295;f.g[0]=f.g[0]+a&4294967295;f.g[1]=f.g[1]+(e+(b<<21&4294967295|b>>>11))&4294967295;f.g[2]=f.g[2]+e&4294967295;f.g[3]=f.g[3]+g&4294967295}\nm.prototype.u=function(f,a){void 0===a&&(a=f.length);for(var c=a-this.blockSize,d=this.B,e=this.h,g=0;gthis.h?this.blockSize:2*this.blockSize)-this.h);f[0]=128;for(var a=1;aa;++a)for(var d=0;32>d;d+=8)f[c++]=this.g[a]>>>d&255;return f};function p(f,a){var c=q;return Object.prototype.hasOwnProperty.call(c,f)?c[f]:c[f]=a(f)};function t(f,a){this.h=a;for(var c=[],d=!0,e=f.length-1;0<=e;e--){var g=f[e]|0;d&&g==a||(c[e]=g,d=!1)}this.g=c}var q={};function u(f){return-128<=f&&128>f?p(f,function(a){return new t([a|0],0>a?-1:0)}):new t([f|0],0>f?-1:0)}function v(f){if(isNaN(f)||!isFinite(f))return w;if(0>f)return x(v(-f));for(var a=[],c=1,d=0;f>=c;d++)a[d]=f/c|0,c*=4294967296;return new t(a,0)}\nfunction y(f,a){if(0==f.length)throw Error(\"number format error: empty string\");a=a||10;if(2>a||36g?(g=v(Math.pow(a,g)),d=d.j(g).add(v(b))):(d=d.j(c),d=d.add(v(b)))}return d}var w=u(0),z=u(1),A=u(16777216);h=t.prototype;\nh.m=function(){if(B(this))return-x(this).m();for(var f=0,a=1,c=0;cf||36>>0).toString(f);c=e;if(C(c))return g+d;for(;6>g.length;)g=\"0\"+g;d=g+d}};\nh.i=function(f){return 0>f?0:f>>16)+(this.i(e)>>>16)+(f.i(e)>>>16);d=b>>>16;g&=65535;b&=65535;c[e]=b<<16|g}return new t(c,c[c.length-1]&-2147483648?-1:0)};function F(f,a){return f.add(x(a))}\nh.j=function(f){if(C(this)||C(f))return w;if(B(this))return B(f)?x(this).j(x(f)):x(x(this).j(f));if(B(f))return x(this.j(x(f)));if(0>this.l(A)&&0>f.l(A))return v(this.m()*f.m());for(var a=this.g.length+f.g.length,c=[],d=0;d<2*a;d++)c[d]=0;for(d=0;d>>16,b=this.i(d)&65535,r=f.i(e)>>>16,E=f.i(e)&65535;c[2*d+2*e]+=b*E;G(c,2*d+2*e);c[2*d+2*e+1]+=g*E;G(c,2*d+2*e+1);c[2*d+2*e+1]+=b*r;G(c,2*d+2*e+1);c[2*d+2*e+2]+=g*r;G(c,2*d+2*e+2)}for(d=0;d<\na;d++)c[d]=c[2*d+1]<<16|c[2*d];for(d=a;d<2*a;d++)c[d]=0;return new t(c,0)};function G(f,a){for(;(f[a]&65535)!=f[a];)f[a+1]+=f[a]>>>16,f[a]&=65535,a++}function H(f,a){this.g=f;this.h=a}\nfunction D(f,a){if(C(a))throw Error(\"division by zero\");if(C(f))return new H(w,w);if(B(f))return a=D(x(f),a),new H(x(a.g),x(a.h));if(B(a))return a=D(f,x(a)),new H(x(a.g),a.h);if(30=d.l(f);)c=I(c),d=I(d);var e=J(c,1),g=J(d,1);d=J(d,2);for(c=J(c,2);!C(d);){var b=g.add(d);0>=b.l(f)&&(e=e.add(c),g=b);d=J(d,1);c=J(c,1)}a=F(f,e.j(a));return new H(e,a)}for(e=w;0<=f.l(a);){c=Math.max(1,Math.floor(f.m()/\na.m()));d=Math.ceil(Math.log(c)/Math.LN2);d=48>=d?1:Math.pow(2,d-48);g=v(c);for(b=g.j(a);B(b)||0>>31;return new t(c,f.h)}function J(f,a){var c=a>>5;a%=32;for(var d=f.g.length-c,e=[],g=0;g>>a|f.i(g+c+1)<<32-a:f.i(g+c);return new t(e,f.h)};m.prototype.digest=m.prototype.v;m.prototype.reset=m.prototype.s;m.prototype.update=m.prototype.u;module.exports.Md5=m;t.prototype.add=t.prototype.add;t.prototype.multiply=t.prototype.j;t.prototype.modulo=t.prototype.A;t.prototype.compare=t.prototype.l;t.prototype.toNumber=t.prototype.m;t.prototype.toString=t.prototype.toString;t.prototype.getBits=t.prototype.i;t.fromNumber=v;t.fromString=y;module.exports.Integer=t;}).apply( typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {});\n", "/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n(function() {'use strict';var h,aa=\"function\"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};function ba(a){a=[\"object\"==typeof globalThis&&globalThis,a,\"object\"==typeof window&&window,\"object\"==typeof self&&self,\"object\"==typeof global&&global];for(var b=0;b{throw a;},0)};function xa(){var a=za;let b=null;a.g&&(b=a.g,a.g=a.g.next,a.g||(a.h=null),b.next=null);return b}class Aa{constructor(){this.h=this.g=null}add(a,b){const c=Ba.get();c.set(a,b);this.h?this.h.next=c:this.g=c;this.h=c}}var Ba=new na(()=>new Ca,a=>a.reset());class Ca{constructor(){this.next=this.g=this.h=null}set(a,b){this.h=a;this.g=b;this.next=null}reset(){this.next=this.g=this.h=null}};let x,y=!1,za=new Aa,Ea=()=>{const a=k.Promise.resolve(void 0);x=()=>{a.then(Da)}};var Da=()=>{for(var a;a=xa();){try{a.h.call(a.g)}catch(c){wa(c)}var b=Ba;b.j(a);100>b.h&&(b.h++,a.next=b.g,b.g=a)}y=!1};function z(){this.s=this.s;this.C=this.C}z.prototype.s=!1;z.prototype.ma=function(){this.s||(this.s=!0,this.N())};z.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function A(a,b){this.type=a;this.g=this.target=b;this.defaultPrevented=!1}A.prototype.h=function(){this.defaultPrevented=!0};var Fa=function(){if(!k.addEventListener||!Object.defineProperty)return!1;var a=!1,b=Object.defineProperty({},\"passive\",{get:function(){a=!0}});try{const c=()=>{};k.addEventListener(\"test\",c,b);k.removeEventListener(\"test\",c,b)}catch(c){}return a}();function C(a,b){A.call(this,a?a.type:\"\");this.relatedTarget=this.g=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=0;this.key=\"\";this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.pointerId=0;this.pointerType=\"\";this.i=null;if(a){var c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.g=b;if(b=a.relatedTarget){if(pa){a:{try{oa(b.nodeName);var e=!0;break a}catch(f){}e=\n!1}e||(b=null)}}else\"mouseover\"==c?b=a.fromElement:\"mouseout\"==c&&(b=a.toElement);this.relatedTarget=b;d?(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.clientX=void 0!==a.clientX?a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.key=a.key||\"\";this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=\na.shiftKey;this.metaKey=a.metaKey;this.pointerId=a.pointerId||0;this.pointerType=\"string\"===typeof a.pointerType?a.pointerType:Ga[a.pointerType]||\"\";this.state=a.state;this.i=a;a.defaultPrevented&&C.aa.h.call(this)}}r(C,A);var Ga={2:\"touch\",3:\"pen\",4:\"mouse\"};C.prototype.h=function(){C.aa.h.call(this);var a=this.i;a.preventDefault?a.preventDefault():a.returnValue=!1};var D=\"closure_listenable_\"+(1E6*Math.random()|0);var Ha=0;function Ia(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.ha=e;this.key=++Ha;this.da=this.fa=!1}function Ja(a){a.da=!0;a.listener=null;a.proxy=null;a.src=null;a.ha=null};function Ka(a){this.src=a;this.g={};this.h=0}Ka.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.g[f];a||(a=this.g[f]=[],this.h++);var g=La(a,b,d,e);-1>>0);function Sa(a){if(\"function\"===typeof a)return a;a[$a]||(a[$a]=function(b){return a.handleEvent(b)});return a[$a]};function E(){z.call(this);this.i=new Ka(this);this.M=this;this.F=null}r(E,z);E.prototype[D]=!0;E.prototype.removeEventListener=function(a,b,c,d){Ya(this,a,b,c,d)};\nfunction F(a,b){var c,d=a.F;if(d)for(c=[];d;d=d.F)c.push(d);a=a.M;d=b.type||b;if(\"string\"===typeof b)b=new A(b,a);else if(b instanceof A)b.target=b.target||a;else{var e=b;b=new A(d,a);ua(b,e)}e=!0;if(c)for(var f=c.length-1;0<=f;f--){var g=b.g=c[f];e=ab(g,d,!0,b)&&e}g=b.g=a;e=ab(g,d,!0,b)&&e;e=ab(g,d,!1,b)&&e;if(c)for(f=0;f{a.g=null;a.i&&(a.i=!1,cb(a))},a.l);const b=a.h;a.h=null;a.m.apply(null,b)}class eb extends z{constructor(a,b){super();this.m=a;this.l=b;this.h=null;this.i=!1;this.g=null}j(a){this.h=arguments;this.g?this.i=!0:cb(this)}N(){super.N();this.g&&(k.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}};function G(a){z.call(this);this.h=a;this.g={}}r(G,z);var fb=[];function gb(a){qa(a.g,function(b,c){this.g.hasOwnProperty(c)&&Za(b)},a);a.g={}}G.prototype.N=function(){G.aa.N.call(this);gb(this)};G.prototype.handleEvent=function(){throw Error(\"EventHandler.handleEvent not implemented\");};var hb=k.JSON.stringify;var ib=k.JSON.parse;var jb=class{stringify(a){return k.JSON.stringify(a,void 0)}parse(a){return k.JSON.parse(a,void 0)}};function kb(){}kb.prototype.h=null;function lb(a){return a.h||(a.h=a.i())};function mb(){}var H={OPEN:\"a\",kb:\"b\",Ja:\"c\",wb:\"d\"};function nb(){A.call(this,\"d\")}r(nb,A);function ob(){A.call(this,\"c\")}r(ob,A);var I={},pb=null;function qb(){return pb=pb||new E}I.La=\"serverreachability\";function rb(a){A.call(this,I.La,a)}r(rb,A);function J(a){const b=qb();F(b,new rb(b,a))}I.STAT_EVENT=\"statevent\";function sb(a,b){A.call(this,I.STAT_EVENT,a);this.stat=b}r(sb,A);function K(a){const b=qb();F(b,new sb(b,a))}I.Ma=\"timingevent\";function tb(a,b){A.call(this,I.Ma,a);this.size=b}r(tb,A);\nfunction ub(a,b){if(\"function\"!==typeof a)throw Error(\"Fn must not be null and must be a function\");return k.setTimeout(function(){a()},b)};function vb(){this.g=!0}vb.prototype.xa=function(){this.g=!1};function wb(a,b,c,d,e,f){a.info(function(){if(a.g)if(f){var g=\"\";for(var m=f.split(\"&\"),q=0;qd.length)){var e=d[1];if(Array.isArray(e)&&!(1>e.length)){var f=e[0];if(\"noop\"!=f&&\"stop\"!=f&&\"close\"!=f)for(var g=1;gw)&&(3!=w||this.g&&(this.h.h||this.g.oa()||Nb(this.g)))){this.J||4!=w||7==b||(8==b||0>=O?J(3):J(2));Ob(this);var c=this.g.Z();this.X=c;b:if(Pb(this)){var d=Nb(this.g);a=\"\";var e=d.length,f=4==P(this.g);if(!this.h.i){if(\"undefined\"===typeof TextDecoder){Q(this);Qb(this);var g=\"\";break b}this.h.i=new k.TextDecoder}for(b=0;bb.length)return Gb;b=b.slice(d,d+c);a.C=d+c;return b}M.prototype.cancel=function(){this.J=!0;Q(this)};function Kb(a){a.S=Date.now()+a.I;Wb(a,a.I)}function Wb(a,b){if(null!=a.B)throw Error(\"WatchDog timer not null\");a.B=ub(p(a.ba,a),b)}function Ob(a){a.B&&(k.clearTimeout(a.B),a.B=null)}\nM.prototype.ba=function(){this.B=null;const a=Date.now();0<=a-this.S?(zb(this.i,this.A),2!=this.L&&(J(3),K(17)),Q(this),this.s=2,Qb(this)):Wb(this,this.S-a)};function Qb(a){0==a.j.G||a.J||Ub(a.j,a)}function Q(a){Ob(a);var b=a.M;b&&\"function\"==typeof b.ma&&b.ma();a.M=null;gb(a.U);a.g&&(b=a.g,a.g=null,b.abort(),b.ma())}\nfunction Rb(a,b){try{var c=a.j;if(0!=c.G&&(c.g==a||Xb(c.h,a)))if(!a.K&&Xb(c.h,a)&&3==c.G){try{var d=c.Da.g.parse(b)}catch(l){d=null}if(Array.isArray(d)&&3==d.length){var e=d;if(0==e[0])a:{if(!c.u){if(c.g)if(c.g.F+3E3e[2]&&c.F&&0==c.v&&!c.C&&(c.C=ub(p(c.Za,c),6E3));if(1>=ac(c.h)&&c.ca){try{c.ca()}catch(l){}c.ca=void 0}}else R(c,11)}else if((a.K||c.g==a)&&Yb(c),!t(b))for(e=c.Da.g.parse(b),b=0;b=a.j:!1}function ac(a){return a.h?1:a.g?a.g.size:0}function Xb(a,b){return a.h?a.h==b:a.g?a.g.has(b):!1}\nfunction bc(a,b){a.g?a.g.add(b):a.h=b}function dc(a,b){a.h&&a.h==b?a.h=null:a.g&&a.g.has(b)&&a.g.delete(b)}ic.prototype.cancel=function(){this.i=kc(this);if(this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const a of this.g.values())a.cancel();this.g.clear()}};function kc(a){if(null!=a.h)return a.i.concat(a.h.D);if(null!=a.g&&0!==a.g.size){let b=a.i;for(const c of a.g.values())b=b.concat(c.D);return b}return la(a.i)};function lc(a){if(a.V&&\"function\"==typeof a.V)return a.V();if(\"undefined\"!==typeof Map&&a instanceof Map||\"undefined\"!==typeof Set&&a instanceof Set)return Array.from(a.values());if(\"string\"===typeof a)return a.split(\"\");if(ha(a)){for(var b=[],c=a.length,d=0;db)throw Error(\"Bad port number \"+b);a.s=b}else a.s=null}function tc(a,b,c){b instanceof sc?(a.i=b,Ac(a.i,a.h)):(c||(b=vc(b,Bc)),a.i=new sc(b,a.h))}function S(a,b,c){a.i.set(b,c)}function Ib(a){S(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36));return a}\nfunction uc(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}function vc(a,b,c){return\"string\"===typeof a?(a=encodeURI(a).replace(b,Cc),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Cc(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var wc=/[#\\/\\?@]/g,yc=/[#\\?:]/g,xc=/[#\\?]/g,Bc=/[#\\?@]/g,zc=/#/g;function sc(a,b){this.h=this.g=null;this.i=a||null;this.j=!!b}\nfunction U(a){a.g||(a.g=new Map,a.h=0,a.i&&pc(a.i,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}h=sc.prototype;h.add=function(a,b){U(this);this.i=null;a=V(this,a);var c=this.g.get(a);c||this.g.set(a,c=[]);c.push(b);this.h+=1;return this};function Dc(a,b){U(a);b=V(a,b);a.g.has(b)&&(a.i=null,a.h-=a.g.get(b).length,a.g.delete(b))}function Ec(a,b){U(a);b=V(a,b);return a.g.has(b)}\nh.forEach=function(a,b){U(this);this.g.forEach(function(c,d){c.forEach(function(e){a.call(b,e,d,this)},this)},this)};h.na=function(){U(this);const a=Array.from(this.g.values()),b=Array.from(this.g.keys()),c=[];for(let d=0;d{d.abort();W(c,\"TestPingServer: timeout\",!1,b)},1E4);fetch(a,{signal:d.signal}).then(f=>{clearTimeout(e);f.ok?W(c,\"TestPingServer: ok\",!0,b):W(c,\"TestPingServer: server error\",!1,b)}).catch(()=>{clearTimeout(e);W(c,\"TestPingServer: error\",!1,b)})}function W(a,b,c,d,e){try{e&&(e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null),d(c)}catch(f){}};function Hc(){this.g=new jb}function Ic(a,b,c){const d=c||\"\";try{nc(a,function(e,f){let g=e;n(e)&&(g=hb(e));b.push(d+f+\"=\"+encodeURIComponent(g))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function Jc(a){this.l=a.Ub||null;this.j=a.eb||!1}r(Jc,kb);Jc.prototype.g=function(){return new Kc(this.l,this.j)};Jc.prototype.i=function(a){return function(){return a}}({});function Kc(a,b){E.call(this);this.D=a;this.o=b;this.m=void 0;this.status=this.readyState=0;this.responseType=this.responseText=this.response=this.statusText=\"\";this.onreadystatechange=null;this.u=new Headers;this.h=null;this.B=\"GET\";this.A=\"\";this.g=!1;this.v=this.j=this.l=null}r(Kc,E);h=Kc.prototype;\nh.open=function(a,b){if(0!=this.readyState)throw this.abort(),Error(\"Error reopening a connection\");this.B=a;this.A=b;this.readyState=1;Lc(this)};h.send=function(a){if(1!=this.readyState)throw this.abort(),Error(\"need to call open() first. \");this.g=!0;const b={headers:this.u,method:this.B,credentials:this.m,cache:void 0};a&&(b.body=a);(this.D||k).fetch(new Request(this.A,b)).then(this.Sa.bind(this),this.ga.bind(this))};\nh.abort=function(){this.response=this.responseText=\"\";this.u=new Headers;this.status=0;this.j&&this.j.cancel(\"Request was aborted.\").catch(()=>{});1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Mc(this));this.readyState=0};\nh.Sa=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,Lc(this)),this.g&&(this.readyState=3,Lc(this),this.g)))if(\"arraybuffer\"===this.responseType)a.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(\"undefined\"!==typeof k.ReadableStream&&\"body\"in a){this.j=a.body.getReader();if(this.o){if(this.responseType)throw Error('responseType must be empty for \"streamBinaryChunks\" mode responses.');this.response=\n[]}else this.response=this.responseText=\"\",this.v=new TextDecoder;Nc(this)}else a.text().then(this.Ra.bind(this),this.ga.bind(this))};function Nc(a){a.j.read().then(a.Pa.bind(a)).catch(a.ga.bind(a))}h.Pa=function(a){if(this.g){if(this.o&&a.value)this.response.push(a.value);else if(!this.o){var b=a.value?a.value:new Uint8Array(0);if(b=this.v.decode(b,{stream:!a.done}))this.response=this.responseText+=b}a.done?Mc(this):Lc(this);3==this.readyState&&Nc(this)}};\nh.Ra=function(a){this.g&&(this.response=this.responseText=a,Mc(this))};h.Qa=function(a){this.g&&(this.response=a,Mc(this))};h.ga=function(){this.g&&Mc(this)};function Mc(a){a.readyState=4;a.l=null;a.j=null;a.v=null;Lc(a)}h.setRequestHeader=function(a,b){this.u.append(a,b)};h.getResponseHeader=function(a){return this.h?this.h.get(a.toLowerCase())||\"\":\"\"};\nh.getAllResponseHeaders=function(){if(!this.h)return\"\";const a=[],b=this.h.entries();for(var c=b.next();!c.done;)c=c.value,a.push(c[0]+\": \"+c[1]),c=b.next();return a.join(\"\\r\\n\")};function Lc(a){a.onreadystatechange&&a.onreadystatechange.call(a)}Object.defineProperty(Kc.prototype,\"withCredentials\",{get:function(){return\"include\"===this.m},set:function(a){this.m=a?\"include\":\"same-origin\"}});function Oc(a){let b=\"\";qa(a,function(c,d){b+=d;b+=\":\";b+=c;b+=\"\\r\\n\"});return b}function Pc(a,b,c){a:{for(d in c){var d=!1;break a}d=!0}d||(c=Oc(c),\"string\"===typeof a?(encodeURIComponent(String(b)),null!=c&&encodeURIComponent(String(c))):S(a,b,c))};function X(a){E.call(this);this.headers=new Map;this.o=a||null;this.h=!1;this.v=this.g=null;this.D=\"\";this.m=0;this.l=\"\";this.j=this.B=this.u=this.A=!1;this.I=null;this.H=\"\";this.J=!1}r(X,E);var Qc=/^https?$/i,Rc=[\"POST\",\"PUT\"];h=X.prototype;h.Ha=function(a){this.J=a};\nh.ea=function(a,b,c,d){if(this.g)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.D+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.D=a;this.l=\"\";this.m=0;this.A=!1;this.h=!0;this.g=this.o?this.o.g():Cb.g();this.v=this.o?lb(this.o):lb(Cb);this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(b,String(a),!0),this.B=!1}catch(f){Sc(this,f);return}a=c||\"\";c=new Map(this.headers);if(d)if(Object.getPrototypeOf(d)===Object.prototype)for(var e in d)c.set(e,d[e]);else if(\"function\"===\ntypeof d.keys&&\"function\"===typeof d.get)for(const f of d.keys())c.set(f,d.get(f));else throw Error(\"Unknown input type for opt_headers: \"+String(d));d=Array.from(c.keys()).find(f=>\"content-type\"==f.toLowerCase());e=k.FormData&&a instanceof k.FormData;!(0<=Array.prototype.indexOf.call(Rc,b,void 0))||d||e||c.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");for(const [f,g]of c)this.g.setRequestHeader(f,g);this.H&&(this.g.responseType=this.H);\"withCredentials\"in this.g&&this.g.withCredentials!==\nthis.J&&(this.g.withCredentials=this.J);try{Tc(this),this.u=!0,this.g.send(a),this.u=!1}catch(f){Sc(this,f)}};function Sc(a,b){a.h=!1;a.g&&(a.j=!0,a.g.abort(),a.j=!1);a.l=b;a.m=5;Uc(a);Vc(a)}function Uc(a){a.A||(a.A=!0,F(a,\"complete\"),F(a,\"error\"))}h.abort=function(a){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=a||7,F(this,\"complete\"),F(this,\"abort\"),Vc(this))};h.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Vc(this,!0));X.aa.N.call(this)};\nh.Ea=function(){this.s||(this.B||this.u||this.j?Wc(this):this.bb())};h.bb=function(){Wc(this)};\nfunction Wc(a){if(a.h&&\"undefined\"!=typeof fa&&(!a.v[1]||4!=P(a)||2!=a.Z()))if(a.u&&4==P(a))bb(a.Ea,0,a);else if(F(a,\"readystatechange\"),4==P(a)){a.h=!1;try{const g=a.Z();a:switch(g){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var b=!0;break a;default:b=!1}var c;if(!(c=b)){var d;if(d=0===g){var e=String(a.D).match(oc)[1]||null;!e&&k.self&&k.self.location&&(e=k.self.location.protocol.slice(0,-1));d=!Qc.test(e?e.toLowerCase():\"\")}c=d}if(c)F(a,\"complete\"),F(a,\"success\");else{a.m=\n6;try{var f=2{}:null;a.g=null;a.v=null;b||F(a,\"ready\");try{c.onreadystatechange=d}catch(e){}}}function Tc(a){a.I&&(k.clearTimeout(a.I),a.I=null)}h.isActive=function(){return!!this.g};function P(a){return a.g?a.g.readyState:0}h.Z=function(){try{return 2=a.h.j-(a.s?1:0))return!1;if(a.s)return a.i=b.D.concat(a.i),!0;if(1==a.G||2==a.G||a.B>=(a.Va?0:a.Wa))return!1;a.s=ub(p(a.Ga,a,b),cd(a,a.B));a.B++;return!0}\nh.Ga=function(a){if(this.s)if(this.s=null,1==this.G){if(!a){this.U=Math.floor(1E5*Math.random());a=this.U++;const e=new M(this,this.j,a);let f=this.o;this.S&&(f?(f=sa(f),ua(f,this.S)):f=this.S);null!==this.m||this.O||(e.H=f,f=null);if(this.P)a:{var b=0;for(var c=0;cl)f=Math.max(0,e[q].g-100),m=!1;else try{Ic(v,g,\"req\"+l+\"_\")}catch(w){d&&d(v)}}if(m){d=g.join(\"&\");break a}}}a=a.i.splice(0,c);b.D=a;return d}function ec(a){if(!a.g&&!a.u){a.Y=1;var b=a.Fa;x||Ea();y||(x(),y=!0);za.add(b,a);a.v=0}}\nfunction $b(a){if(a.g||a.u||3<=a.v)return!1;a.Y++;a.u=ub(p(a.Fa,a),cd(a,a.v));a.v++;return!0}h.Fa=function(){this.u=null;fd(this);if(this.ba&&!(this.M||null==this.g||0>=this.R)){var a=2*this.R;this.j.info(\"BP detection timer enabled: \"+a);this.A=ub(p(this.ab,this),a)}};h.ab=function(){this.A&&(this.A=null,this.j.info(\"BP detection timeout reached.\"),this.j.info(\"Buffering proxy detected and switch to long-polling!\"),this.F=!1,this.M=!0,K(10),Zb(this),fd(this))};\nfunction Tb(a){null!=a.A&&(k.clearTimeout(a.A),a.A=null)}function fd(a){a.g=new M(a,a.j,\"rpc\",a.Y);null===a.m&&(a.g.H=a.o);a.g.O=0;var b=N(a.qa);S(b,\"RID\",\"rpc\");S(b,\"SID\",a.K);S(b,\"AID\",a.T);S(b,\"CI\",a.F?\"0\":\"1\");!a.F&&a.ja&&S(b,\"TO\",a.ja);S(b,\"TYPE\",\"xmlhttp\");$c(a,b);a.m&&a.o&&Pc(b,a.m,a.o);a.L&&(a.g.I=a.L);var c=a.g;a=a.ia;c.L=1;c.v=Ib(N(b));c.m=null;c.P=!0;Jb(c,a)}h.Za=function(){null!=this.C&&(this.C=null,Zb(this),$b(this),K(19))};function Yb(a){null!=a.C&&(k.clearTimeout(a.C),a.C=null)}\nfunction Ub(a,b){var c=null;if(a.g==b){Yb(a);Tb(a);a.g=null;var d=2}else if(Xb(a.h,b))c=b.D,dc(a.h,b),d=1;else return;if(0!=a.G)if(b.o)if(1==d){c=b.m?b.m.length:0;b=Date.now()-b.F;var e=a.B;d=qb();F(d,new tb(d,c,b,e));fc(a)}else ec(a);else if(e=b.s,3==e||0==e&&0\n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n * \n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\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/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure: string = 'Unexpected state'): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message =\n `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */\nexport function hardAssert(\n assertion: boolean,\n message?: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj 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 { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.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\nexport interface Resolver {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener!: () => void;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth) {\n this.auth.removeAuthTokenListener(this.tokenListener!);\n }\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener!: AppCheckTokenListener;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n\n constructor(\n private appCheckProvider: Provider\n ) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n this.appCheck.addTokenListener(this.tokenListener);\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck) {\n this.appCheck.removeTokenListener(this.tokenListener!);\n }\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n\n constructor(\n private appCheckProvider: Provider\n ) {\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\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 { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable {\n isEqual(other: T): boolean;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\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 */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n /** Returns a JSON-serializable representation of this `Timestamp`. */\n toJSON(): { seconds: number; nanoseconds: number } {\n return { seconds: this.seconds, nanoseconds: this.nanoseconds };\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n static comparator>(\n p1: BasePath,\n p2: BasePath\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const left = p1.get(i);\n const right = p2.get(i);\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n }\n if (p1.length < p2.length) {\n return -1;\n }\n if (p1.length > p2.length) {\n return 1;\n }\n return 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and traling slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { primitiveComparator } from '../util/misc';\n\nimport { Document } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldPath } from './path';\n\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_LARGEST_BATCH_ID = -1;\n\n/**\n * The initial sequence number for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_SEQUENCE_NUMBER = 0;\n\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nexport class FieldIndex {\n /** An ID for an index that has not yet been added to persistence. */\n static UNKNOWN_ID = -1;\n\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n readonly indexId: number,\n /** The collection ID this index applies to. */\n readonly collectionGroup: string,\n /** The field segments for this index. */\n readonly fields: IndexSegment[],\n /** Shows how up-to-date the index is for the current user. */\n readonly indexState: IndexState\n ) {}\n}\n\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nexport function fieldIndexGetArraySegment(\n fieldIndex: FieldIndex\n): IndexSegment | undefined {\n return fieldIndex.fields.find(s => s.kind === IndexKind.CONTAINS);\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */\nexport function fieldIndexGetDirectionalSegments(\n fieldIndex: FieldIndex\n): IndexSegment[] {\n return fieldIndex.fields.filter(s => s.kind !== IndexKind.CONTAINS);\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\nexport function fieldIndexGetKeyOrder(fieldIndex: FieldIndex): IndexKind {\n const directionalSegments = fieldIndexGetDirectionalSegments(fieldIndex);\n return directionalSegments.length === 0\n ? IndexKind.ASCENDING\n : directionalSegments[directionalSegments.length - 1].kind;\n}\n\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nexport function fieldIndexSemanticComparator(\n left: FieldIndex,\n right: FieldIndex\n): number {\n let cmp = primitiveComparator(left.collectionGroup, right.collectionGroup);\n if (cmp !== 0) {\n return cmp;\n }\n\n for (let i = 0; i < Math.min(left.fields.length, right.fields.length); ++i) {\n cmp = indexSegmentComparator(left.fields[i], right.fields[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return primitiveComparator(left.fields.length, right.fields.length);\n}\n\n/** Returns a debug representation of the field index */\nexport function fieldIndexToString(fieldIndex: FieldIndex): string {\n return `id=${fieldIndex.indexId}|cg=${\n fieldIndex.collectionGroup\n }|f=${fieldIndex.fields.map(f => `${f.fieldPath}:${f.kind}`).join(',')}`;\n}\n\n/** The type of the index, e.g. for which type of query it can be used. */\nexport const enum IndexKind {\n // Note: The order of these values cannot be changed as the enum values are\n // stored in IndexedDb.\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n ASCENDING,\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n DESCENDING,\n /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */\n CONTAINS\n}\n\n/** An index component consisting of field path and index type. */\nexport class IndexSegment {\n constructor(\n /** The field path of the component. */\n readonly fieldPath: FieldPath,\n /** The fields sorting order. */\n readonly kind: IndexKind\n ) {}\n}\n\nfunction indexSegmentComparator(\n left: IndexSegment,\n right: IndexSegment\n): number {\n const cmp = FieldPath.comparator(left.fieldPath, right.fieldPath);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.kind, right.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */\nexport class IndexState {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n readonly sequenceNumber: number,\n /** The the latest indexed read time, document and batch id. */\n readonly offset: IndexOffset\n ) {}\n\n /** The state of an index that has not yet been backfilled. */\n static empty(): IndexState {\n return new IndexState(INITIAL_SEQUENCE_NUMBER, IndexOffset.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */\nexport function newIndexOffsetSuccessorFromReadTime(\n readTime: SnapshotVersion,\n largestBatchId: number\n): IndexOffset {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const successorSeconds = readTime.toTimestamp().seconds;\n const successorNanos = readTime.toTimestamp().nanoseconds + 1;\n const successor = SnapshotVersion.fromTimestamp(\n successorNanos === 1e9\n ? new Timestamp(successorSeconds + 1, 0)\n : new Timestamp(successorSeconds, successorNanos)\n );\n return new IndexOffset(successor, DocumentKey.empty(), largestBatchId);\n}\n\n/** Creates a new offset based on the provided document. */\nexport function newIndexOffsetFromDocument(document: Document): IndexOffset {\n return new IndexOffset(\n document.readTime,\n document.key,\n INITIAL_LARGEST_BATCH_ID\n );\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */\nexport class IndexOffset {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n readonly readTime: SnapshotVersion,\n\n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n readonly documentKey: DocumentKey,\n\n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n readonly largestBatchId: number\n ) {}\n\n /** Returns an offset that sorts before all regular offsets. */\n static min(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.min(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n\n /** Returns an offset that sorts after all regular offsets. */\n static max(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.max(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n}\n\nexport function indexOffsetComparator(\n left: IndexOffset,\n right: IndexOffset\n): number {\n let cmp = left.readTime.compareTo(right.readTime);\n if (cmp !== 0) {\n return cmp;\n }\n cmp = DocumentKey.comparator(left.documentKey, right.documentKey);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.largestBatchId, right.largestBatchId);\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 { ListenSequenceNumber } from '../core/types';\nexport const PRIMARY_LEASE_LOST_ERROR_MSG =\n 'The current tab is not in the required state to perform this operation. ' +\n 'It might be necessary to refresh the browser tab.';\n\n/** The different modes supported by `Persistence.runTransaction()`. */\nexport type PersistenceTransactionMode =\n | 'readonly'\n | 'readwrite'\n | 'readwrite-primary';\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */\nexport abstract class PersistenceTransaction {\n private readonly onCommittedListeners: Array<() => void> = [];\n\n abstract readonly currentSequenceNumber: ListenSequenceNumber;\n\n addOnCommittedListener(listener: () => void): void {\n this.onCommittedListeners.push(listener);\n }\n\n raiseOnCommittedEvent(): void {\n this.onCommittedListeners.forEach(listener => listener());\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { IndexManager } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { PRIMARY_LEASE_LOST_ERROR_MSG } from './persistence_transaction';\n\nexport interface LocalStore {\n collectGarbage(garbageCollector: LruGarbageCollector): Promise;\n\n /** Manages the list of active field and collection indices. */\n indexManager: IndexManager;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments: LocalDocumentsView;\n}\n\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */\nexport async function ignoreIfPrimaryLeaseLoss(\n err: FirestoreError\n): Promise {\n if (\n err.code === Code.FAILED_PRECONDITION &&\n err.message === PRIMARY_LEASE_LOST_ERROR_MSG\n ) {\n logDebug('LocalStore', 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\n\nexport type FulfilledHandler =\n | ((result: T) => R | PersistencePromise)\n | null;\nexport type RejectedHandler =\n | ((reason: Error) => R | PersistencePromise)\n | null;\nexport type Resolver = (value?: T) => void;\nexport type Rejector = (error: Error) => void;\n\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */\nexport class PersistencePromise {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n private nextCallback: FulfilledHandler = null;\n private catchCallback: RejectedHandler = null;\n\n // When the operation resolves, we'll set result or error and mark isDone.\n private result: T | undefined = undefined;\n private error: Error | undefined = undefined;\n private isDone = false;\n\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n private callbackAttached = false;\n\n constructor(callback: (resolve: Resolver, reject: Rejector) => void) {\n callback(\n value => {\n this.isDone = true;\n this.result = value;\n if (this.nextCallback) {\n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(value!);\n }\n },\n error => {\n this.isDone = true;\n this.error = error;\n if (this.catchCallback) {\n this.catchCallback(error);\n }\n }\n );\n }\n\n catch(\n fn: (error: Error) => R | PersistencePromise\n ): PersistencePromise {\n return this.next(undefined, fn);\n }\n\n next(\n nextFn?: FulfilledHandler,\n catchFn?: RejectedHandler\n ): PersistencePromise {\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result!);\n } else {\n return this.wrapFailure(catchFn, this.error);\n }\n } else {\n return new PersistencePromise((resolve, reject) => {\n this.nextCallback = (value: T) => {\n this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n this.catchCallback = (error: Error) => {\n this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n }\n\n toPromise(): Promise {\n return new Promise((resolve, reject) => {\n this.next(resolve, reject);\n });\n }\n\n private wrapUserFunction(\n fn: () => R | PersistencePromise\n ): PersistencePromise {\n try {\n const result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n } else {\n return PersistencePromise.resolve(result);\n }\n } catch (e) {\n return PersistencePromise.reject(e as Error);\n }\n }\n\n private wrapSuccess(\n nextFn: FulfilledHandler | undefined,\n value: T\n ): PersistencePromise {\n if (nextFn) {\n return this.wrapUserFunction(() => nextFn(value));\n } else {\n // If there's no nextFn, then R must be the same as T\n return PersistencePromise.resolve(value as unknown as R);\n }\n }\n\n private wrapFailure(\n catchFn: RejectedHandler | undefined,\n error: Error\n ): PersistencePromise {\n if (catchFn) {\n return this.wrapUserFunction(() => catchFn(error));\n } else {\n return PersistencePromise.reject(error);\n }\n }\n\n static resolve(): PersistencePromise;\n static resolve(result: R): PersistencePromise;\n static resolve(result?: R): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n resolve(result);\n });\n }\n\n static reject(error: Error): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n reject(error);\n });\n }\n\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n all: { forEach: (cb: (el: PersistencePromise) => void) => void }\n ): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n let expectedCount = 0;\n let resolvedCount = 0;\n let done = false;\n\n all.forEach(element => {\n ++expectedCount;\n element.next(\n () => {\n ++resolvedCount;\n if (done && resolvedCount === expectedCount) {\n resolve();\n }\n },\n err => reject(err)\n );\n });\n\n done = true;\n if (resolvedCount === expectedCount) {\n resolve();\n }\n });\n }\n\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */\n static or(\n predicates: Array<() => PersistencePromise>\n ): PersistencePromise {\n let p: PersistencePromise =\n PersistencePromise.resolve(false);\n for (const predicate of predicates) {\n p = p.next(isTrue => {\n if (isTrue) {\n return PersistencePromise.resolve(isTrue);\n } else {\n return predicate();\n }\n });\n }\n return p;\n }\n\n /**\n * Given an iterable, call the given function on each element in the\n * collection and wait for all of the resulting concurrent PersistencePromises\n * to resolve.\n */\n static forEach(\n collection: { forEach: (cb: (r: R, s: S) => void) => void },\n f:\n | ((r: R, s: S) => PersistencePromise)\n | ((r: R) => PersistencePromise)\n ): PersistencePromise;\n static forEach(\n collection: { forEach: (cb: (r: R) => void) => void },\n f: (r: R) => PersistencePromise\n ): PersistencePromise;\n static forEach(\n collection: { forEach: (cb: (r: R, s?: S) => void) => void },\n f: (r: R, s?: S) => PersistencePromise\n ): PersistencePromise {\n const promises: Array> = [];\n collection.forEach((r, s) => {\n promises.push(f.call(this, r, s));\n });\n return this.waitFor(promises);\n }\n\n /**\n * Concurrently map all array elements through asynchronous function.\n */\n static mapArray(\n array: T[],\n f: (t: T) => PersistencePromise\n ): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n const expectedCount = array.length;\n const results: U[] = new Array(expectedCount);\n let resolvedCount = 0;\n for (let i = 0; i < expectedCount; i++) {\n const current = i;\n f(array[current]).next(\n result => {\n results[current] = result;\n ++resolvedCount;\n if (resolvedCount === expectedCount) {\n resolve(results);\n }\n },\n err => reject(err)\n );\n }\n });\n }\n\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */\n static doWhile(\n condition: () => boolean,\n action: () => PersistencePromise\n ): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n const process = (): void => {\n if (condition() === true) {\n action().next(() => {\n process();\n }, reject);\n } else {\n resolve();\n }\n };\n process();\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 { getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise {\n logDebug(LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for userse running version < 4.5.\n const androidVersion = getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndxedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise\n ): PersistencePromise {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback\n ): PersistencePromise {\n const results: Array> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\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 */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n private task: DelayedOperation | null;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly backfiller: IndexBackfiller\n ) {\n this.task = null;\n }\n\n start(): void {\n debugAssert(\n this.task === null,\n 'Cannot start an already started IndexBackfillerScheduler'\n );\n this.schedule(INITIAL_BACKFILL_DELAY_MS);\n }\n\n stop(): void {\n if (this.task) {\n this.task.cancel();\n this.task = null;\n }\n }\n\n get started(): boolean {\n return this.task !== null;\n }\n\n private schedule(delay: number): void {\n debugAssert(\n this.task === null,\n 'Cannot schedule IndexBackfiller while a task is pending'\n );\n logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n this.task = this.asyncQueue.enqueueAfterDelay(\n TimerId.IndexBackfill,\n delay,\n async () => {\n this.task = null;\n try {\n const documentsProcessed = await this.backfiller.backfill();\n logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during index backfill: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n }\n );\n }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n private readonly localStore: LocalStore,\n private readonly persistence: Persistence\n ) {}\n\n async backfill(\n maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n ): Promise {\n return this.persistence.runTransaction(\n 'Backfill Indexes',\n 'readwrite-primary',\n txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n );\n }\n\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n private writeIndexEntries(\n transation: PersistenceTransaction,\n maxDocumentsToProcess: number\n ): PersistencePromise {\n const processedCollectionGroups = new Set();\n let documentsRemaining = maxDocumentsToProcess;\n let continueLoop = true;\n return PersistencePromise.doWhile(\n () => continueLoop === true && documentsRemaining > 0,\n () => {\n return this.localStore.indexManager\n .getNextCollectionGroupToUpdate(transation)\n .next((collectionGroup: string | null) => {\n if (\n collectionGroup === null ||\n processedCollectionGroups.has(collectionGroup)\n ) {\n continueLoop = false;\n } else {\n logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`);\n return this.writeEntriesForCollectionGroup(\n transation,\n collectionGroup,\n documentsRemaining\n ).next(documentsProcessed => {\n documentsRemaining -= documentsProcessed;\n processedCollectionGroups.add(collectionGroup);\n });\n }\n });\n }\n ).next(() => maxDocumentsToProcess - documentsRemaining);\n }\n\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */\n private writeEntriesForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n documentsRemainingUnderCap: number\n ): PersistencePromise {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager\n .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n .next(existingOffset =>\n this.localStore.localDocuments\n .getNextDocuments(\n transaction,\n collectionGroup,\n existingOffset,\n documentsRemainingUnderCap\n )\n .next(nextBatch => {\n const docs: DocumentMap = nextBatch.changes;\n return this.localStore.indexManager\n .updateIndexEntries(transaction, docs)\n .next(() => this.getNewOffset(existingOffset, nextBatch))\n .next(newOffset => {\n logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n return this.localStore.indexManager.updateCollectionGroup(\n transaction,\n collectionGroup,\n newOffset\n );\n })\n .next(() => docs.size);\n })\n );\n }\n\n /** Returns the next offset based on the provided documents. */\n private getNewOffset(\n existingOffset: IndexOffset,\n lookupResult: LocalWriteResult\n ): IndexOffset {\n let maxOffset: IndexOffset = existingOffset;\n lookupResult.changes.forEach((key, document) => {\n const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n maxOffset = newOffset;\n }\n });\n return new IndexOffset(\n maxOffset.readTime,\n maxOffset.documentKey,\n Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n );\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): 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 { ResourcePath } from '../model/path';\nimport { fail, hardAssert } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encodeResourcePath(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decodeResourcePath(path: EncodedResourcePath): ResourcePath {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const length = path.length;\n hardAssert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n hardAssert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 'Non-empty path ' + path + ' had length 2'\n );\n return ResourcePath.emptyPath();\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\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 { BatchId, TargetId } from '../core/types';\nimport { ResourcePath } from '../model/path';\nimport { fail } from '../util/assert';\n\nimport {\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { DbDocumentMutation } from './indexeddb_schema';\nimport { DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy } from './indexeddb_schema_legacy';\n\n// This file contains static constants and helper functions for IndexedDB.\n// It is split from indexeddb_schema to allow for minification.\n\n/** A timestamp type that can be used in IndexedDb keys. */\nexport type DbTimestampKey = [/* seconds */ number, /* nanos */ number];\n\n// The key for the singleton object in the DbPrimaryClient is a single string.\nexport type DbPrimaryClientKey = typeof DbPrimaryClientKey;\n\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\nexport const DbPrimaryClientStore = 'owner';\n\n/**\n * The key string used for the single object that exists in the\n * DbPrimaryClient store.\n */\n\nexport const DbPrimaryClientKey = 'owner';\n\n/** Object keys in the 'mutationQueues' store are userId strings. */\nexport type DbMutationQueueKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationQueueStore = 'mutationQueues';\n\n/** Keys are automatically assigned via the userId property. */\nexport const DbMutationQueueKeyPath = 'userId';\n\n/** The 'mutations' store is keyed by batch ID. */\nexport type DbMutationBatchKey = BatchId;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationBatchStore = 'mutations';\n\n/** Keys are automatically assigned via the userId, batchId properties. */\nexport const DbMutationBatchKeyPath = 'batchId';\n\n/** The index name for lookup of mutations by user. */\n\nexport const DbMutationBatchUserMutationsIndex = 'userMutationsIndex';\n\n/** The user mutations index is keyed by [userId, batchId] pairs. */\nexport const DbMutationBatchUserMutationsKeyPath = ['userId', 'batchId'];\n\n/**\n * The key for a db document mutation, which is made up of a userID, path, and\n * batchId. Note that the path must be serialized into a form that indexedDB can\n * sort.\n */\nexport type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId];\n\n/**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\nexport function newDbDocumentMutationPrefixForUser(userId: string): [string] {\n return [userId];\n}\n\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nexport function newDbDocumentMutationPrefixForPath(\n userId: string,\n path: ResourcePath\n): [string, EncodedResourcePath] {\n return [userId, encodeResourcePath(path)];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\nexport function newDbDocumentMutationKey(\n userId: string,\n path: ResourcePath,\n batchId: BatchId\n): DbDocumentMutationKey {\n return [userId, encodeResourcePath(path), batchId];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */\nexport const DbDocumentMutationPlaceholder: DbDocumentMutation = {};\n\nexport const DbDocumentMutationStore = 'documentMutations';\n\nexport const DbRemoteDocumentStore = 'remoteDocumentsV14';\n\n/**\n * A key in the 'remoteDocumentsV14' object store is an array containing the\n * collection path, the collection group, the read time and the document id.\n */\nexport type DbRemoteDocumentKey = [\n /** path to collection */ string[],\n /** collection group */ string,\n /** read time */ DbTimestampKey,\n /** document ID */ string\n];\n\n/**\n * The primary key of the remote documents store, which allows for efficient\n * access by collection path and read time.\n */\nexport const DbRemoteDocumentKeyPath = [\n 'prefixPath',\n 'collectionGroup',\n 'readTime',\n 'documentId'\n];\n\n/** An index that provides access to documents by key. */\nexport const DbRemoteDocumentDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbRemoteDocumentDocumentKeyIndexPath = [\n 'prefixPath',\n 'collectionGroup',\n 'documentId'\n];\n\n/**\n * An index that provides access to documents by collection group and read\n * time.\n *\n * This index is used by the index backfiller.\n */\nexport const DbRemoteDocumentCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbRemoteDocumentCollectionGroupIndexPath = [\n 'collectionGroup',\n 'readTime',\n 'prefixPath',\n 'documentId'\n];\n\nexport const DbRemoteDocumentGlobalStore = 'remoteDocumentGlobal';\n\nexport const DbRemoteDocumentGlobalKey = 'remoteDocumentGlobalKey';\n\nexport type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobalKey;\n\n/**\n * A key in the 'targets' object store is a targetId of the query.\n */\nexport type DbTargetKey = TargetId;\n\nexport const DbTargetStore = 'targets';\n\n/** Keys are automatically assigned via the targetId property. */\nexport const DbTargetKeyPath = 'targetId';\n\n/** The name of the queryTargets index. */\nexport const DbTargetQueryTargetsIndexName = 'queryTargetsIndex';\n\n/**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\nexport const DbTargetQueryTargetsKeyPath = ['canonicalId', 'targetId'];\n\n/**\n * The key for a DbTargetDocument, containing a targetId and an encoded resource\n * path.\n */\nexport type DbTargetDocumentKey = [TargetId, EncodedResourcePath];\n\n/** Name of the IndexedDb object store. */\nexport const DbTargetDocumentStore = 'targetDocuments';\n\n/** Keys are automatically assigned via the targetId, path properties. */\nexport const DbTargetDocumentKeyPath = ['targetId', 'path'];\n\n/** The index name for the reverse index. */\nexport const DbTargetDocumentDocumentTargetsIndex = 'documentTargetsIndex';\n\n/** We also need to create the reverse index for these properties. */\nexport const DbTargetDocumentDocumentTargetsKeyPath = ['path', 'targetId'];\n\n/**\n * The type to represent the single allowed key for the DbTargetGlobal store.\n */\nexport type DbTargetGlobalKey = typeof DbTargetGlobalKey;\n/**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\nexport const DbTargetGlobalKey = 'targetGlobalKey';\n\nexport const DbTargetGlobalStore = 'targetGlobal';\n\n/**\n * The key for a DbCollectionParent entry, containing the collection ID\n * and the parent path that contains it. Note that the parent path will be an\n * empty path in the case of root-level collections.\n */\nexport type DbCollectionParentKey = [string, EncodedResourcePath];\n\n/** Name of the IndexedDb object store. */\nexport const DbCollectionParentStore = 'collectionParents';\n\n/** Keys are automatically assigned via the collectionId, parent properties. */\nexport const DbCollectionParentKeyPath = ['collectionId', 'parent'];\n\n/** Name of the IndexedDb object store. */\nexport const DbClientMetadataStore = 'clientMetadata';\n\n/** Keys are automatically assigned via the clientId properties. */\nexport const DbClientMetadataKeyPath = 'clientId';\n\n/** Object keys in the 'clientMetadata' store are clientId strings. */\nexport type DbClientMetadataKey = string;\n\nexport type DbBundlesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbBundleStore = 'bundles';\n\nexport const DbBundleKeyPath = 'bundleId';\n\nexport type DbNamedQueriesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbNamedQueryStore = 'namedQueries';\n\nexport const DbNamedQueryKeyPath = 'name';\n\n/** The key for each index consisting of just the index id. */\nexport type DbIndexConfigurationKey = number;\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexConfigurationStore = 'indexConfiguration';\n\nexport const DbIndexConfigurationKeyPath = 'indexId';\n\n/**\n * An index that provides access to the index configurations by collection\n * group.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexConfigurationCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbIndexConfigurationCollectionGroupIndexPath = 'collectionGroup';\n\n/** The key for each index state consisting of the index id and its user id. */\nexport type DbIndexStateKey = [number, string];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexStateStore = 'indexState';\n\nexport const DbIndexStateKeyPath = ['indexId', 'uid'];\n\n/**\n * An index that provides access to documents in a collection sorted by last\n * update time. Used by the backfiller.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexStateSequenceNumberIndex = 'sequenceNumberIndex';\n\nexport const DbIndexStateSequenceNumberIndexPath = ['uid', 'sequenceNumber'];\n\n/**\n * The key for each index entry consists of the index id and its user id,\n * the encoded array and directional value for the indexed fields as well as\n * an ordered and an encoded document path for the indexed document.\n */\nexport type DbIndexEntryKey = [\n number,\n string,\n Uint8Array,\n Uint8Array,\n Uint8Array,\n string[]\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexEntryStore = 'indexEntries';\n\nexport const DbIndexEntryKeyPath = [\n 'indexId',\n 'uid',\n 'arrayValue',\n 'directionalValue',\n 'orderedDocumentKey',\n 'documentKey'\n];\n\nexport const DbIndexEntryDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbIndexEntryDocumentKeyIndexPath = [\n 'indexId',\n 'uid',\n 'orderedDocumentKey'\n];\n\nexport type DbDocumentOverlayKey = [\n /* userId */ string,\n /* collectionPath */ string,\n /* documentId */ string\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbDocumentOverlayStore = 'documentOverlays';\n\nexport const DbDocumentOverlayKeyPath = [\n 'userId',\n 'collectionPath',\n 'documentId'\n];\n\nexport const DbDocumentOverlayCollectionPathOverlayIndex =\n 'collectionPathOverlayIndex';\n\nexport const DbDocumentOverlayCollectionPathOverlayIndexPath = [\n 'userId',\n 'collectionPath',\n 'largestBatchId'\n];\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndex =\n 'collectionGroupOverlayIndex';\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndexPath = [\n 'userId',\n 'collectionGroup',\n 'largestBatchId'\n];\n\n// Visible for testing\nexport const V1_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStoreLegacy,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore\n];\n\n// Visible for testing\nexport const V3_STORES = V1_STORES;\n// Note: DbRemoteDocumentChanges is no longer used and dropped with v9.\nexport const V4_STORES = [...V3_STORES, DbClientMetadataStore];\nexport const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobalStore];\nexport const V8_STORES = [...V6_STORES, DbCollectionParentStore];\nexport const V11_STORES = [...V8_STORES, DbBundleStore, DbNamedQueryStore];\nexport const V12_STORES = [...V11_STORES, DbDocumentOverlayStore];\nexport const V13_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStore,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore,\n DbClientMetadataStore,\n DbRemoteDocumentGlobalStore,\n DbCollectionParentStore,\n DbBundleStore,\n DbNamedQueryStore,\n DbDocumentOverlayStore\n];\nexport const V14_STORES = V13_STORES;\nexport const V15_STORES = [\n ...V14_STORES,\n DbIndexConfigurationStore,\n DbIndexStateStore,\n DbIndexEntryStore\n];\nexport const V16_STORES = V15_STORES;\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 16) {\n return V16_STORES;\n } else if (schemaVersion === 15) {\n return V15_STORES;\n } else if (schemaVersion === 14) {\n return V14_STORES;\n } else if (schemaVersion === 13) {\n return V13_STORES;\n } else if (schemaVersion === 12) {\n return V12_STORES;\n } else if (schemaVersion === 11) {\n return V11_STORES;\n } else {\n fail('Only schema version 11 and 12 and 13 are supported');\n }\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 { Document as ProtoDocument } from '../protos/firestore_proto_api';\n\nimport { DbNoDocument, DbUnknownDocument } from './indexeddb_schema';\nimport { DbTimestampKey } from './indexeddb_sentinels';\n\n// This file contains older schema definitions for object stores that were\n// migrated to newer schema versions. These object stores should only be used\n// during schema migrations.\n\nexport interface DbRemoteDocument {\n unknownDocument?: DbUnknownDocument;\n noDocument?: DbNoDocument;\n document?: ProtoDocument;\n hasCommittedMutations?: boolean;\n readTime?: DbTimestampKey;\n parentPath?: string[];\n}\n\nexport type DbRemoteDocumentKey = string[];\nexport const DbRemoteDocumentStore = 'remoteDocuments';\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 { ListenSequenceNumber } from '../core/types';\nimport { debugCast } from '../util/assert';\n\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\nexport function getStore(\n txn: PersistenceTransaction,\n store: string\n): SimpleDbStore {\n const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n return SimpleDb.getStore(\n indexedDbTransaction.simpleDbTransaction,\n store\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach(\n obj: Dict | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty(obj: Dict): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\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\nimport { debugAssert, fail } from './assert';\n\n/*\n * 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\nexport type Comparator = (key1: K, key2: K) => number;\n\nexport interface Entry {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\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 // Returns a copy of the map, with the specified key removed.\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 // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const 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 // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\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. 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 inorderTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && 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,\n // 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\n // 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(): Entry {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const 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 } 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(): Entry | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\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 isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. 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 inorderTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. 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 reverseTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\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 // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\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 private removeMin(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\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 // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = 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 LLRBNode.EMPTY;\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 isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\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 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 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 private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\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 // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode {\n get key(): never {\n throw fail('LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail('LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail('LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail('LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail('LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\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 // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet): SortedSet {\n let result: SortedSet = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets(\n before: SortedSet,\n after: SortedSet,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator(it: SortedSetIterator): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\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 { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\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/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\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 { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\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 { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\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 { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 'invalid timestamp: ' + date);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\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 { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n", "import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\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 { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { arrayEquals, primitiveComparator } from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail('Unexpected value type: ' + JSON.stringify(left));\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return primitiveComparator(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail('Invalid value type: ' + leftType);\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n return { mapValue: {} };\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return { mapValue: {} };\n } else if ('mapValue' in value) {\n return MAX_VALUE;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 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 */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be sycned or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\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 { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown FieldFilter operator: ' + this.op);\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail('Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return other !== null && !arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\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\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== 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 { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet {\n let result = new SortedSet(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + orderBy.dir);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { forEach, isEmpty } from './obj';\n\ntype Entry = [K, V];\n\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nexport class ObjectMap {\n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n private inner: {\n [canonicalId: string]: Array>;\n } = {};\n\n /** The number of entries stored in the map */\n private innerSize = 0;\n\n constructor(\n private mapKeyFn: (key: KeyType) => string,\n private equalsFn: (l: KeyType, r: KeyType) => boolean\n ) {}\n\n /** Get a value for this key, or undefined if it does not exist. */\n get(key: KeyType): ValueType | undefined {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (const [otherKey, value] of matches) {\n if (this.equalsFn(otherKey, key)) {\n return value;\n }\n }\n return undefined;\n }\n\n has(key: KeyType): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Put this key and value in the map. */\n set(key: KeyType, value: ValueType): void {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n this.innerSize++;\n return;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n // This is updating an existing entry and does not increase `innerSize`.\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n this.innerSize++;\n }\n\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n delete(key: KeyType): boolean {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n } else {\n matches.splice(i, 1);\n }\n this.innerSize--;\n return true;\n }\n }\n return false;\n }\n\n forEach(fn: (key: KeyType, val: ValueType) => void): void {\n forEach(this.inner, (_, entries) => {\n for (const [k, v] of entries) {\n fn(k, v);\n }\n });\n }\n\n isEmpty(): boolean {\n return isEmpty(this.inner);\n }\n\n size(): number {\n return this.innerSize;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { OverlayedDocument } from '../local/overlayed_document';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\nimport { Overlay } from './overlay';\n\n/** Miscellaneous collection types / constants. */\n\nexport type MutableDocumentMap = SortedMap;\nconst EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap(\n DocumentKey.comparator\n);\nexport function mutableDocumentMap(): MutableDocumentMap {\n return EMPTY_MUTABLE_DOCUMENT_MAP;\n}\n\nexport interface DocumentSizeEntries {\n documents: MutableDocumentMap;\n sizeMap: SortedMap;\n}\n\nexport type DocumentMap = SortedMap;\nconst EMPTY_DOCUMENT_MAP = new SortedMap(\n DocumentKey.comparator\n);\nexport function documentMap(...docs: Document[]): DocumentMap {\n let map = EMPTY_DOCUMENT_MAP;\n for (const doc of docs) {\n map = map.insert(doc.key, doc);\n }\n return map;\n}\n\nexport type OverlayedDocumentMap = DocumentKeyMap;\nexport function newOverlayedDocumentMap(): OverlayedDocumentMap {\n return newDocumentKeyMap();\n}\n\nexport function convertOverlayedDocumentMapToDocumentMap(\n collection: OverlayedDocumentMap\n): DocumentMap {\n let documents = EMPTY_DOCUMENT_MAP;\n collection.forEach(\n (k, v) => (documents = documents.insert(k, v.overlayedDocument))\n );\n return documents;\n}\n\nexport type OverlayMap = DocumentKeyMap;\nexport function newOverlayMap(): OverlayMap {\n return newDocumentKeyMap();\n}\n\nexport type MutationMap = DocumentKeyMap;\nexport function newMutationMap(): MutationMap {\n return newDocumentKeyMap();\n}\n\nexport type DocumentKeyMap = ObjectMap;\nexport function newDocumentKeyMap(): DocumentKeyMap {\n return new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n}\n\nexport type DocumentVersionMap = SortedMap;\nconst EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(\n DocumentKey.comparator\n);\nexport function documentVersionMap(): DocumentVersionMap {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nexport type DocumentKeySet = SortedSet;\nconst EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet(...keys: DocumentKey[]): DocumentKeySet {\n let set = EMPTY_DOCUMENT_KEY_SET;\n for (const key of keys) {\n set = set.add(key);\n }\n return set;\n}\n\nexport type TargetIdSet = SortedSet;\nconst EMPTY_TARGET_ID_SET = new SortedSet(primitiveComparator);\nexport function targetIdSet(): SortedSet {\n return EMPTY_TARGET_ID_SET;\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 { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map {\n const result = new Map();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array\n): Map {\n const transformResults = new Map();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map {\n const transformResults = new Map();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\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 */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n DocumentVersionMap,\n documentVersionMap,\n newMutationMap,\n OverlayedDocumentMap\n} from './collections';\nimport { MutableDocument } from './document';\nimport { FieldMask } from './field_mask';\nimport {\n calculateOverlayMutation,\n Mutation,\n mutationApplyToLocalView,\n mutationApplyToRemoteDocument,\n mutationEquals,\n MutationResult\n} from './mutation';\n\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nexport class MutationBatch {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(\n public batchId: BatchId,\n public localWriteTime: Timestamp,\n public baseMutations: Mutation[],\n public mutations: Mutation[]\n ) {\n debugAssert(mutations.length > 0, 'Cannot create an empty mutation batch');\n }\n\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */\n applyToRemoteDocument(\n document: MutableDocument,\n batchResult: MutationBatchResult\n ): void {\n const mutationResults = batchResult.mutationResults;\n debugAssert(\n mutationResults.length === this.mutations.length,\n `Mismatch between mutations length\n (${this.mutations.length}) and mutation results length\n (${mutationResults.length}).`\n );\n\n for (let i = 0; i < this.mutations.length; i++) {\n const mutation = this.mutations[i];\n if (mutation.key.isEqual(document.key)) {\n const mutationResult = mutationResults[i];\n mutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n }\n }\n\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */\n applyToLocalView(\n document: MutableDocument,\n mutatedFields: FieldMask | null\n ): FieldMask | null {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const mutation of this.baseMutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n\n // Second, apply all user-provided mutations.\n for (const mutation of this.mutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n return mutatedFields;\n }\n\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */\n applyToLocalDocumentSet(\n documentMap: OverlayedDocumentMap,\n documentsWithoutRemoteVersion: DocumentKeySet\n ): MutationMap {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const overlays = newMutationMap();\n this.mutations.forEach(m => {\n const overlayedDocument = documentMap.get(m.key)!;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n const mutableDocument =\n overlayedDocument.overlayedDocument as MutableDocument;\n let mutatedFields = this.applyToLocalView(\n mutableDocument,\n overlayedDocument.mutatedFields\n );\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n mutatedFields = documentsWithoutRemoteVersion.has(m.key)\n ? null\n : mutatedFields;\n const overlay = calculateOverlayMutation(mutableDocument, mutatedFields);\n if (overlay !== null) {\n overlays.set(m.key, overlay);\n }\n\n if (!mutableDocument.isValidDocument()) {\n mutableDocument.convertToNoDocument(SnapshotVersion.min());\n }\n });\n return overlays;\n }\n\n keys(): DocumentKeySet {\n return this.mutations.reduce(\n (keys, m) => keys.add(m.key),\n documentKeySet()\n );\n }\n\n isEqual(other: MutationBatch): boolean {\n return (\n this.batchId === other.batchId &&\n arrayEquals(this.mutations, other.mutations, (l, r) =>\n mutationEquals(l, r)\n ) &&\n arrayEquals(this.baseMutations, other.baseMutations, (l, r) =>\n mutationEquals(l, r)\n )\n );\n }\n}\n\n/** The result of applying a mutation batch to the backend. */\nexport class MutationBatchResult {\n private constructor(\n readonly batch: MutationBatch,\n readonly commitVersion: SnapshotVersion,\n readonly mutationResults: MutationResult[],\n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n readonly docVersions: DocumentVersionMap\n ) {}\n\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */\n static from(\n batch: MutationBatch,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ): MutationBatchResult {\n hardAssert(\n batch.mutations.length === results.length,\n 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length\n );\n\n let versionMap = documentVersionMap();\n const mutations = batch.mutations;\n for (let i = 0; i < mutations.length; i++) {\n versionMap = versionMap.insert(mutations[i].key, results[i].version);\n }\n\n return new MutationBatchResult(batch, commitVersion, results, versionMap);\n }\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 { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\n\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */\nexport class Overlay {\n constructor(readonly largestBatchId: number, readonly mutation: Mutation) {}\n\n getKey(): DocumentKey {\n return this.mutation.key;\n }\n\n isEqual(other: Overlay | null): boolean {\n return other !== null && this.mutation === other.mutation;\n }\n\n toString(): string {\n return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\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\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BloomFilter as ProtoBloomFilter } from '../protos/firestore_proto_api';\n\nexport class ExistenceFilter {\n constructor(public count: number, public unchangedNames?: ProtoBloomFilter) {}\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\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/**\n * The global, singleton instance of TestingHooksSpi.\n *\n * This variable will be `null` in all cases _except_ when running from\n * integration tests that have registered callbacks to be notified of events\n * that happen during the test execution.\n */\nexport let testingHooksSpi: TestingHooksSpi | null = null;\n\n/**\n * Sets the value of the `testingHooksSpi` object.\n * @param instance the instance to set.\n */\nexport function setTestingHooksSpi(instance: TestingHooksSpi): void {\n if (testingHooksSpi) {\n throw new Error('a TestingHooksSpi instance is already set');\n }\n testingHooksSpi = instance;\n}\n\n/**\n * The \"service provider interface\" for the testing hooks.\n *\n * The implementation of this object will handle the callbacks made by the SDK\n * to be handled by the integration tests.\n *\n * This \"SPI\" is separated from the implementation to avoid import cycles and\n * to enable production builds to fully tree-shake away the testing hooks logic.\n */\nexport interface TestingHooksSpi {\n /**\n * Invokes all callbacks registered with\n * `TestingHooks.onExistenceFilterMismatch()` with the given info.\n */\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void;\n}\n\n/**\n * Information about an existence filter mismatch.\n * @internal\n */\nexport interface ExistenceFilterMismatchInfo {\n /** The number of documents that matched the query in the local cache. */\n localCacheCount: number;\n\n /**\n * The number of documents that matched the query on the server, as specified\n * in the ExistenceFilter message's `count` field.\n */\n existenceFilterCount: number;\n\n /**\n * The projectId used when checking documents for membership in the bloom\n * filter.\n */\n projectId: string;\n\n /**\n * The databaseId used when checking documents for membership in the bloom\n * filter.\n */\n databaseId: string;\n\n /**\n * Information about the bloom filter provided by Watch in the ExistenceFilter\n * message's `unchangedNames` field. If this property is omitted or undefined\n * then that means that Watch did _not_ provide a bloom filter.\n */\n bloomFilter?: {\n /**\n * Whether a full requery was averted by using the bloom filter. If false,\n * then something happened, such as a false positive, to prevent using the\n * bloom filter to avoid a full requery.\n */\n applied: boolean;\n\n /** The number of hash functions used in the bloom filter. */\n hashCount: number;\n\n /** The number of bytes in the bloom filter's bitmask. */\n bitmapLength: number;\n\n /** The number of bits of padding in the last byte of the bloom filter. */\n padding: number;\n\n /**\n * Tests the given string for membership in the bloom filter created from\n * the existence filter; will be undefined if creating the bloom filter\n * failed.\n */\n mightContain?: (value: string) => boolean;\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/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\nexport function newTextEncoder(): TextEncoder {\n return new TextEncoder();\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\nexport function newTextDecoder(): TextDecoder {\n return new TextDecoder('utf-8');\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 { Md5, Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { newTextEncoder } from '../platform/text_serializer';\n\nconst MAX_64_BIT_UNSIGNED_INTEGER = new Integer([0xffffffff, 0xffffffff], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction getMd5HashValue(value: string): Uint8Array {\n const encodedValue = newTextEncoder().encode(value);\n const md5 = new Md5();\n md5.update(encodedValue);\n return new Uint8Array(md5.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2’s complement using little endian.\nfunction get64BitUints(Bytes: Uint8Array): [Integer, Integer] {\n const dataView = new DataView(Bytes.buffer);\n const chunk1 = dataView.getUint32(0, /* littleEndian= */ true);\n const chunk2 = dataView.getUint32(4, /* littleEndian= */ true);\n const chunk3 = dataView.getUint32(8, /* littleEndian= */ true);\n const chunk4 = dataView.getUint32(12, /* littleEndian= */ true);\n const integer1 = new Integer([chunk1, chunk2], 0);\n const integer2 = new Integer([chunk3, chunk4], 0);\n return [integer1, integer2];\n}\n\nexport class BloomFilter {\n readonly bitCount: number;\n private readonly bitCountInInteger: Integer;\n\n constructor(\n readonly bitmap: Uint8Array,\n readonly padding: number,\n readonly hashCount: number\n ) {\n if (padding < 0 || padding >= 8) {\n throw new BloomFilterError(`Invalid padding: ${padding}`);\n }\n\n if (hashCount < 0) {\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length > 0 && this.hashCount === 0) {\n // Only empty bloom filter can have 0 hash count.\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length === 0 && padding !== 0) {\n // Empty bloom filter should have 0 padding.\n throw new BloomFilterError(\n `Invalid padding when bitmap length is 0: ${padding}`\n );\n }\n\n this.bitCount = bitmap.length * 8 - padding;\n // Set the bit count in Integer to avoid repetition in mightContain().\n this.bitCountInInteger = Integer.fromNumber(this.bitCount);\n }\n\n // Calculate the ith hash value based on the hashed 64bit integers,\n // and calculate its corresponding bit index in the bitmap to be checked.\n private getBitIndex(num1: Integer, num2: Integer, hashIndex: number): number {\n // Calculate hashed value h(i) = h1 + (i * h2).\n let hashValue = num1.add(num2.multiply(Integer.fromNumber(hashIndex)));\n // Wrap if hash value overflow 64bit.\n if (hashValue.compare(MAX_64_BIT_UNSIGNED_INTEGER) === 1) {\n hashValue = new Integer([hashValue.getBits(0), hashValue.getBits(1)], 0);\n }\n return hashValue.modulo(this.bitCountInInteger).toNumber();\n }\n\n // Return whether the bit on the given index in the bitmap is set to 1.\n private isBitSet(index: number): boolean {\n // To retrieve bit n, calculate: (bitmap[n / 8] & (0x01 << (n % 8))).\n const byte = this.bitmap[Math.floor(index / 8)];\n const offset = index % 8;\n return (byte & (0x01 << offset)) !== 0;\n }\n\n mightContain(value: string): boolean {\n // Empty bitmap should always return false on membership check.\n if (this.bitCount === 0) {\n return false;\n }\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n if (!this.isBitSet(index)) {\n return false;\n }\n }\n return true;\n }\n\n /** Create bloom filter for testing purposes only. */\n static create(\n bitCount: number,\n hashCount: number,\n contains: string[]\n ): BloomFilter {\n const padding = bitCount % 8 === 0 ? 0 : 8 - (bitCount % 8);\n const bitmap = new Uint8Array(Math.ceil(bitCount / 8));\n const bloomFilter = new BloomFilter(bitmap, padding, hashCount);\n contains.forEach(item => bloomFilter.insert(item));\n return bloomFilter;\n }\n\n private insert(value: string): void {\n if (this.bitCount === 0) {\n return;\n }\n\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n this.setBit(index);\n }\n }\n\n private setBit(index: number): void {\n const indexOfByte = Math.floor(index / 8);\n const offset = index % 8;\n this.bitmap[indexOfByte] |= 0x01 << offset;\n }\n}\n\nexport class BloomFilterError extends Error {\n readonly name = 'BloomFilterError';\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap,\n MutableDocumentMap\n} from '../model/collections';\nimport { ByteString } from '../util/byte_string';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\n\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */\nexport class RemoteEvent {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n readonly snapshotVersion: SnapshotVersion,\n /**\n * A map from target to changes to the target. See TargetChange.\n */\n readonly targetChanges: Map,\n /**\n * A map of targets that is known to be inconsistent, and the purpose for\n * re-listening. Listens for these targets should be re-established without\n * resume tokens.\n */\n readonly targetMismatches: SortedMap,\n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n readonly documentUpdates: MutableDocumentMap,\n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n readonly resolvedLimboDocuments: DocumentKeySet\n ) {}\n\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): RemoteEvent {\n const targetChanges = new Map();\n targetChanges.set(\n targetId,\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current,\n resumeToken\n )\n );\n return new RemoteEvent(\n SnapshotVersion.min(),\n targetChanges,\n new SortedMap(primitiveComparator),\n mutableDocumentMap(),\n documentKeySet()\n );\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */\nexport class TargetChange {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n readonly resumeToken: ByteString,\n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n readonly current: boolean,\n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n readonly addedDocuments: DocumentKeySet,\n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n readonly modifiedDocuments: DocumentKeySet,\n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n readonly removedDocuments: DocumentKeySet\n ) {}\n\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */\n static createSynthesizedTargetChangeForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): TargetChange {\n return new TargetChange(\n resumeToken,\n current,\n documentKeySet(),\n documentKeySet(),\n documentKeySet()\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 { DatabaseId } from '../core/database_info';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { ChangeType } from '../core/view_snapshot';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { normalizeByteString } from '../model/normalize';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { Base64DecodeError } from '../util/base64_decode_error';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport {\n testingHooksSpi,\n ExistenceFilterMismatchInfo as TestingHooksExistenceFilterMismatchInfo\n} from '../util/testing_hooks_spi';\n\nimport { BloomFilter, BloomFilterError } from './bloom_filter';\nimport { ExistenceFilter } from './existence_filter';\nimport { RemoteEvent, TargetChange } from './remote_event';\n\n/**\n * Internal representation of the watcher API protocol buffers.\n */\nexport type WatchChange =\n | DocumentWatchChange\n | WatchTargetChange\n | ExistenceFilterChange;\n\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */\nexport class DocumentWatchChange {\n constructor(\n /** The new document applies to all of these targets. */\n public updatedTargetIds: TargetId[],\n /** The new document is removed from all of these targets. */\n public removedTargetIds: TargetId[],\n /** The key of the document for this change. */\n public key: DocumentKey,\n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n public newDoc: MutableDocument | null\n ) {}\n}\n\nexport class ExistenceFilterChange {\n constructor(\n public targetId: TargetId,\n public existenceFilter: ExistenceFilter\n ) {}\n}\n\nexport const enum WatchTargetChangeState {\n NoChange,\n Added,\n Removed,\n Current,\n Reset\n}\n\nconst enum BloomFilterApplicationStatus {\n Success,\n Skipped,\n FalsePositive\n}\nexport class WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n public state: WatchTargetChangeState,\n /** The target IDs that were added/removed/set. */\n public targetIds: TargetId[],\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n public resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /** An RPC error indicating why the watch failed. */\n public cause: FirestoreError | null = null\n ) {}\n}\n\n/** Tracks the internal state of a Watch target. */\nclass TargetState {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n private pendingResponses = 0;\n\n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n private documentChanges: SortedMap =\n snapshotChangesMap();\n\n /** See public getters for explanations of these fields. */\n private _resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n private _current = false;\n\n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n private _hasPendingChanges = true;\n\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */\n get current(): boolean {\n return this._current;\n }\n\n /** The last resume token sent to us for this target. */\n get resumeToken(): ByteString {\n return this._resumeToken;\n }\n\n /** Whether this target has pending target adds or target removes. */\n get isPending(): boolean {\n return this.pendingResponses !== 0;\n }\n\n /** Whether we have modified any state that should trigger a snapshot. */\n get hasPendingChanges(): boolean {\n return this._hasPendingChanges;\n }\n\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */\n updateResumeToken(resumeToken: ByteString): void {\n if (resumeToken.approximateByteSize() > 0) {\n this._hasPendingChanges = true;\n this._resumeToken = resumeToken;\n }\n }\n\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */\n toTargetChange(): TargetChange {\n let addedDocuments = documentKeySet();\n let modifiedDocuments = documentKeySet();\n let removedDocuments = documentKeySet();\n\n this.documentChanges.forEach((key, changeType) => {\n switch (changeType) {\n case ChangeType.Added:\n addedDocuments = addedDocuments.add(key);\n break;\n case ChangeType.Modified:\n modifiedDocuments = modifiedDocuments.add(key);\n break;\n case ChangeType.Removed:\n removedDocuments = removedDocuments.add(key);\n break;\n default:\n fail('Encountered invalid change type: ' + changeType);\n }\n });\n\n return new TargetChange(\n this._resumeToken,\n this._current,\n addedDocuments,\n modifiedDocuments,\n removedDocuments\n );\n }\n\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */\n clearPendingChanges(): void {\n this._hasPendingChanges = false;\n this.documentChanges = snapshotChangesMap();\n }\n\n addDocumentChange(key: DocumentKey, changeType: ChangeType): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.insert(key, changeType);\n }\n\n removeDocumentChange(key: DocumentKey): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.remove(key);\n }\n\n recordPendingTargetRequest(): void {\n this.pendingResponses += 1;\n }\n\n recordTargetResponse(): void {\n this.pendingResponses -= 1;\n hardAssert(\n this.pendingResponses >= 0,\n '`pendingResponses` is less than 0. Actual value: ' +\n this.pendingResponses +\n '. This indicates that the SDK received more target acks from the ' +\n 'server than expected. The SDK should not continue to operate.'\n );\n }\n\n markCurrent(): void {\n this._hasPendingChanges = true;\n this._current = true;\n }\n}\n\n/**\n * Interface implemented by RemoteStore to expose target metadata to the\n * WatchChangeAggregator.\n */\nexport interface TargetMetadataProvider {\n /**\n * Returns the set of remote document keys for the given target ID as of the\n * last raised snapshot.\n */\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet;\n\n /**\n * Returns the TargetData for an active target ID or 'null' if this target\n * has become inactive\n */\n getTargetDataForTarget(targetId: TargetId): TargetData | null;\n\n /**\n * Returns the database ID of the Firestore instance.\n */\n getDatabaseId(): DatabaseId;\n}\n\nconst LOG_TAG = 'WatchChangeAggregator';\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nexport class WatchChangeAggregator {\n constructor(private metadataProvider: TargetMetadataProvider) {}\n\n /** The internal state of all tracked targets. */\n private targetStates = new Map();\n\n /** Keeps track of the documents to update since the last raised snapshot. */\n private pendingDocumentUpdates = mutableDocumentMap();\n\n /** A mapping of document keys to their set of target IDs. */\n private pendingDocumentTargetMapping = documentTargetMap();\n\n /**\n * A map of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n private pendingTargetResets = new SortedMap(\n primitiveComparator\n );\n\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */\n handleDocumentChange(docChange: DocumentWatchChange): void {\n for (const targetId of docChange.updatedTargetIds) {\n if (docChange.newDoc && docChange.newDoc.isFoundDocument()) {\n this.addDocumentToTarget(targetId, docChange.newDoc);\n } else {\n this.removeDocumentFromTarget(\n targetId,\n docChange.key,\n docChange.newDoc\n );\n }\n }\n\n for (const targetId of docChange.removedTargetIds) {\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n }\n }\n\n /** Processes and adds the WatchTargetChange to the current set of changes. */\n handleTargetChange(targetChange: WatchTargetChange): void {\n this.forEachTarget(targetChange, targetId => {\n const targetState = this.ensureTargetState(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (this.isActiveTarget(targetId)) {\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n targetState.clearPendingChanges();\n }\n targetState.updateResumeToken(targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n this.removeTarget(targetId);\n }\n debugAssert(\n !targetChange.cause,\n 'WatchChangeAggregator does not handle errored targets'\n );\n break;\n case WatchTargetChangeState.Current:\n if (this.isActiveTarget(targetId)) {\n targetState.markCurrent();\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (this.isActiveTarget(targetId)) {\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.resetTarget(targetId);\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n }\n\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */\n forEachTarget(\n targetChange: WatchTargetChange,\n fn: (targetId: TargetId) => void\n ): void {\n if (targetChange.targetIds.length > 0) {\n targetChange.targetIds.forEach(fn);\n } else {\n this.targetStates.forEach((_, targetId) => {\n if (this.isActiveTarget(targetId)) {\n fn(targetId);\n }\n });\n }\n }\n\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */\n handleExistenceFilter(watchChange: ExistenceFilterChange): void {\n const targetId = watchChange.targetId;\n const expectedCount = watchChange.existenceFilter.count;\n\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n const target = targetData.target;\n if (targetIsDocumentTarget(target)) {\n if (expectedCount === 0) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const key = new DocumentKey(target.path);\n this.removeDocumentFromTarget(\n targetId,\n key,\n MutableDocument.newNoDocument(key, SnapshotVersion.min())\n );\n } else {\n hardAssert(\n expectedCount === 1,\n 'Single document existence filter with count: ' + expectedCount\n );\n }\n } else {\n const currentSize = this.getCurrentDocumentCountForTarget(targetId);\n // Existence filter mismatch. Mark the documents as being in limbo, and\n // raise a snapshot with `isFromCache:true`.\n if (currentSize !== expectedCount) {\n // Apply bloom filter to identify and mark removed documents.\n const bloomFilter = this.parseBloomFilter(watchChange);\n const status = bloomFilter\n ? this.applyBloomFilter(bloomFilter, watchChange, currentSize)\n : BloomFilterApplicationStatus.Skipped;\n\n if (status !== BloomFilterApplicationStatus.Success) {\n // If bloom filter application fails, we reset the mapping and\n // trigger re-run of the query.\n this.resetTarget(targetId);\n\n const purpose: TargetPurpose =\n status === BloomFilterApplicationStatus.FalsePositive\n ? TargetPurpose.ExistenceFilterMismatchBloom\n : TargetPurpose.ExistenceFilterMismatch;\n this.pendingTargetResets = this.pendingTargetResets.insert(\n targetId,\n purpose\n );\n }\n testingHooksSpi?.notifyOnExistenceFilterMismatch(\n createExistenceFilterMismatchInfoForTestingHooks(\n currentSize,\n watchChange.existenceFilter,\n this.metadataProvider.getDatabaseId(),\n bloomFilter,\n status\n )\n );\n }\n }\n }\n }\n\n /**\n * Parse the bloom filter from the \"unchanged_names\" field of an existence\n * filter.\n */\n private parseBloomFilter(\n watchChange: ExistenceFilterChange\n ): BloomFilter | null {\n const unchangedNames = watchChange.existenceFilter.unchangedNames;\n if (!unchangedNames || !unchangedNames.bits) {\n return null;\n }\n\n const {\n bits: { bitmap = '', padding = 0 },\n hashCount = 0\n } = unchangedNames;\n\n let normalizedBitmap: Uint8Array;\n try {\n normalizedBitmap = normalizeByteString(bitmap).toUint8Array();\n } catch (err) {\n if (err instanceof Base64DecodeError) {\n logWarn(\n 'Decoding the base64 bloom filter in existence filter failed (' +\n err.message +\n '); ignoring the bloom filter and falling back to full re-query.'\n );\n return null;\n } else {\n throw err;\n }\n }\n\n let bloomFilter: BloomFilter;\n try {\n // BloomFilter throws error if the inputs are invalid.\n bloomFilter = new BloomFilter(normalizedBitmap, padding, hashCount);\n } catch (err) {\n if (err instanceof BloomFilterError) {\n logWarn('BloomFilter error: ', err);\n } else {\n logWarn('Applying bloom filter failed: ', err);\n }\n return null;\n }\n\n if (bloomFilter.bitCount === 0) {\n return null;\n }\n\n return bloomFilter;\n }\n\n /**\n * Apply bloom filter to remove the deleted documents, and return the\n * application status.\n */\n private applyBloomFilter(\n bloomFilter: BloomFilter,\n watchChange: ExistenceFilterChange,\n currentCount: number\n ): BloomFilterApplicationStatus {\n const expectedCount = watchChange.existenceFilter.count;\n\n const removedDocumentCount = this.filterRemovedDocuments(\n bloomFilter,\n watchChange.targetId\n );\n\n return expectedCount === currentCount - removedDocumentCount\n ? BloomFilterApplicationStatus.Success\n : BloomFilterApplicationStatus.FalsePositive;\n }\n\n /**\n * Filter out removed documents based on bloom filter membership result and\n * return number of documents removed.\n */\n private filterRemovedDocuments(\n bloomFilter: BloomFilter,\n targetId: number\n ): number {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n let removalCount = 0;\n\n existingKeys.forEach(key => {\n const databaseId = this.metadataProvider.getDatabaseId();\n const documentPath =\n `projects/${databaseId.projectId}` +\n `/databases/${databaseId.database}` +\n `/documents/${key.path.canonicalString()}`;\n\n if (!bloomFilter.mightContain(documentPath)) {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n removalCount++;\n }\n });\n\n return removalCount;\n }\n\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */\n createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent {\n const targetChanges = new Map();\n\n this.targetStates.forEach((targetState, targetId) => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n if (targetState.current && targetIsDocumentTarget(targetData.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n //\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const key = new DocumentKey(targetData.target.path);\n if (\n this.pendingDocumentUpdates.get(key) === null &&\n !this.targetContainsDocument(targetId, key)\n ) {\n this.removeDocumentFromTarget(\n targetId,\n key,\n MutableDocument.newNoDocument(key, snapshotVersion)\n );\n }\n }\n\n if (targetState.hasPendingChanges) {\n targetChanges.set(targetId, targetState.toTargetChange());\n targetState.clearPendingChanges();\n }\n }\n });\n\n let resolvedLimboDocuments = documentKeySet();\n\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n //\n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.pendingDocumentTargetMapping.forEach((key, targets) => {\n let isOnlyLimboTarget = true;\n\n targets.forEachWhile(targetId => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (\n targetData &&\n targetData.purpose !== TargetPurpose.LimboResolution\n ) {\n isOnlyLimboTarget = false;\n return false;\n }\n\n return true;\n });\n\n if (isOnlyLimboTarget) {\n resolvedLimboDocuments = resolvedLimboDocuments.add(key);\n }\n });\n\n this.pendingDocumentUpdates.forEach((_, doc) =>\n doc.setReadTime(snapshotVersion)\n );\n\n const remoteEvent = new RemoteEvent(\n snapshotVersion,\n targetChanges,\n this.pendingTargetResets,\n this.pendingDocumentUpdates,\n resolvedLimboDocuments\n );\n\n this.pendingDocumentUpdates = mutableDocumentMap();\n this.pendingDocumentTargetMapping = documentTargetMap();\n this.pendingTargetResets = new SortedMap(\n primitiveComparator\n );\n\n return remoteEvent;\n }\n\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n addDocumentToTarget(targetId: TargetId, document: MutableDocument): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const changeType = this.targetContainsDocument(targetId, document.key)\n ? ChangeType.Modified\n : ChangeType.Added;\n\n const targetState = this.ensureTargetState(targetId);\n targetState.addDocumentChange(document.key, changeType);\n\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n document.key,\n document\n );\n\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n document.key,\n this.ensureDocumentTargetMapping(document.key).add(targetId)\n );\n }\n\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n removeDocumentFromTarget(\n targetId: TargetId,\n key: DocumentKey,\n updatedDocument: MutableDocument | null\n ): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const targetState = this.ensureTargetState(targetId);\n if (this.targetContainsDocument(targetId, key)) {\n targetState.addDocumentChange(key, ChangeType.Removed);\n } else {\n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n targetState.removeDocumentChange(key);\n }\n\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).delete(targetId)\n );\n\n if (updatedDocument) {\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n key,\n updatedDocument\n );\n }\n }\n\n removeTarget(targetId: TargetId): void {\n this.targetStates.delete(targetId);\n }\n\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */\n private getCurrentDocumentCountForTarget(targetId: TargetId): number {\n const targetState = this.ensureTargetState(targetId);\n const targetChange = targetState.toTargetChange();\n return (\n this.metadataProvider.getRemoteKeysForTarget(targetId).size +\n targetChange.addedDocuments.size -\n targetChange.removedDocuments.size\n );\n }\n\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */\n recordPendingTargetRequest(targetId: TargetId): void {\n // For each request we get we need to record we need a response for it.\n const targetState = this.ensureTargetState(targetId);\n targetState.recordPendingTargetRequest();\n }\n\n private ensureTargetState(targetId: TargetId): TargetState {\n let result = this.targetStates.get(targetId);\n if (!result) {\n result = new TargetState();\n this.targetStates.set(targetId, result);\n }\n return result;\n }\n\n private ensureDocumentTargetMapping(key: DocumentKey): SortedSet {\n let targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(primitiveComparator);\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(key, targetMapping);\n }\n\n return targetMapping;\n }\n\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */\n protected isActiveTarget(targetId: TargetId): boolean {\n const targetActive = this.targetDataForActiveTarget(targetId) !== null;\n if (!targetActive) {\n logDebug(LOG_TAG, 'Detected inactive target', targetId);\n }\n return targetActive;\n }\n\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */\n protected targetDataForActiveTarget(targetId: TargetId): TargetData | null {\n const targetState = this.targetStates.get(targetId);\n return targetState && targetState.isPending\n ? null\n : this.metadataProvider.getTargetDataForTarget(targetId);\n }\n\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */\n private resetTarget(targetId: TargetId): void {\n debugAssert(\n !this.targetStates.get(targetId)!.isPending,\n 'Should only reset active targets'\n );\n this.targetStates.set(targetId, new TargetState());\n\n // Trigger removal for any documents currently mapped to this target.\n // These removals will be part of the initial snapshot if Watch does not\n // resend these documents.\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n existingKeys.forEach(key => {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n });\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */\n private targetContainsDocument(\n targetId: TargetId,\n key: DocumentKey\n ): boolean {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n return existingKeys.has(key);\n }\n}\n\nfunction documentTargetMap(): SortedMap> {\n return new SortedMap>(\n DocumentKey.comparator\n );\n}\n\nfunction snapshotChangesMap(): SortedMap {\n return new SortedMap(DocumentKey.comparator);\n}\n\nfunction createExistenceFilterMismatchInfoForTestingHooks(\n localCacheCount: number,\n existenceFilter: ExistenceFilter,\n databaseId: DatabaseId,\n bloomFilter: BloomFilter | null,\n bloomFilterStatus: BloomFilterApplicationStatus\n): TestingHooksExistenceFilterMismatchInfo {\n const result: TestingHooksExistenceFilterMismatchInfo = {\n localCacheCount,\n existenceFilterCount: existenceFilter.count,\n databaseId: databaseId.database,\n projectId: databaseId.projectId\n };\n\n const unchangedNames = existenceFilter.unchangedNames;\n if (unchangedNames) {\n result.bloomFilter = {\n applied: bloomFilterStatus === BloomFilterApplicationStatus.Success,\n hashCount: unchangedNames?.hashCount ?? 0,\n bitmapLength: unchangedNames?.bits?.bitmap?.length ?? 0,\n padding: unchangedNames?.bits?.padding ?? 0,\n mightContain: (value: string): boolean =>\n bloomFilter?.mightContain(value) ?? false\n };\n }\n\n return result;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\nfunction fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined ||\n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n value instanceof Buffer ||\n value instanceof Uint8Array,\n 'value must be undefined, Buffer, or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 'tried to deserialize invalid key ' + resourceName.toString()\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[],\n skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = skipAliasing\n ? aggregate.alias\n : `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified operator');\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail('Unrecognized filter type ' + JSON.stringify(filter));\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { ByteString } from '../util/byte_string';\n\n/** An enumeration of the different purposes we have for targets. */\nexport const enum TargetPurpose {\n /** A regular, normal query target. */\n Listen = 'TargetPurposeListen',\n\n /**\n * The query target was used to refill a query after an existence filter\n * mismatch.\n */\n ExistenceFilterMismatch = 'TargetPurposeExistenceFilterMismatch',\n\n /**\n * The query target was used if the query is the result of a false positive in\n * the bloom filter.\n */\n ExistenceFilterMismatchBloom = 'TargetPurposeExistenceFilterMismatchBloom',\n\n /** The query target was used to resolve a limbo document. */\n LimboResolution = 'TargetPurposeLimboResolution'\n}\n\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */\nexport class TargetData {\n constructor(\n /** The target being listened to. */\n readonly target: Target,\n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n readonly targetId: TargetId,\n /** The purpose of the target. */\n readonly purpose: TargetPurpose,\n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n readonly sequenceNumber: ListenSequenceNumber,\n /** The latest snapshot version seen for this target. */\n readonly snapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */\n readonly lastLimboFreeSnapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n readonly resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /**\n * The number of documents that last matched the query at the resume token or\n * read time. Documents are counted only when making a listen request with\n * resume token or read time, otherwise, keep it null.\n */\n readonly expectedCount: number | null = null\n ) {}\n\n /** Creates a new target data instance with an updated sequence number. */\n withSequenceNumber(sequenceNumber: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n this.expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */\n withResumeToken(\n resumeToken: ByteString,\n snapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n resumeToken,\n /* expectedCount= */ null\n );\n }\n\n /**\n * Creates a new target data instance with an updated expected count.\n */\n withExpectedCount(expectedCount: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */\n withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n lastLimboFreeSnapshotVersion,\n this.resumeToken,\n this.expectedCount\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 { Timestamp } from '../api/timestamp';\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport { LimitType, Query, queryWithLimit } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetIsDocumentTarget } from '../core/target';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n IndexOffset,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { Overlay } from '../model/overlay';\nimport { FieldPath } from '../model/path';\nimport {\n BundledQuery as ProtoBundledQuery,\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { DocumentsTarget as PublicDocumentsTarget } from '../protos/firestore_proto_api';\nimport {\n convertQueryTargetToQuery,\n fromDocument,\n fromDocumentsTarget,\n fromMutation,\n fromQueryTarget,\n fromVersion,\n JsonProtoSerializer,\n toDocument,\n toDocumentsTarget,\n toMutation,\n toQueryTarget\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport {\n DbBundle,\n DbDocumentOverlay,\n DbIndexConfiguration,\n DbIndexState,\n DbMutationBatch,\n DbNamedQuery,\n DbQuery,\n DbRemoteDocument,\n DbTarget,\n DbTimestamp\n} from './indexeddb_schema';\nimport { DbDocumentOverlayKey, DbTimestampKey } from './indexeddb_sentinels';\nimport { TargetData, TargetPurpose } from './target_data';\n\n/** Serializer for values stored in the LocalStore. */\nexport class LocalSerializer {\n constructor(readonly remoteSerializer: JsonProtoSerializer) {}\n}\n\n/** Decodes a remote document from storage locally to a Document. */\nexport function fromDbRemoteDocument(\n localSerializer: LocalSerializer,\n remoteDoc: DbRemoteDocument\n): MutableDocument {\n let doc: MutableDocument;\n if (remoteDoc.document) {\n doc = fromDocument(\n localSerializer.remoteSerializer,\n remoteDoc.document,\n !!remoteDoc.hasCommittedMutations\n );\n } else if (remoteDoc.noDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n const version = fromDbTimestamp(remoteDoc.noDocument.readTime);\n doc = MutableDocument.newNoDocument(key, version);\n if (remoteDoc.hasCommittedMutations) {\n doc.setHasCommittedMutations();\n }\n } else if (remoteDoc.unknownDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n const version = fromDbTimestamp(remoteDoc.unknownDocument.version);\n doc = MutableDocument.newUnknownDocument(key, version);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n\n if (remoteDoc.readTime) {\n doc.setReadTime(fromDbTimestampKey(remoteDoc.readTime));\n }\n\n return doc;\n}\n\n/** Encodes a document for storage locally. */\nexport function toDbRemoteDocument(\n localSerializer: LocalSerializer,\n document: MutableDocument\n): DbRemoteDocument {\n const key = document.key;\n const remoteDoc: DbRemoteDocument = {\n prefixPath: key.getCollectionPath().popLast().toArray(),\n collectionGroup: key.collectionGroup,\n documentId: key.path.lastSegment(),\n readTime: toDbTimestampKey(document.readTime),\n hasCommittedMutations: document.hasCommittedMutations\n };\n\n if (document.isFoundDocument()) {\n remoteDoc.document = toDocument(localSerializer.remoteSerializer, document);\n } else if (document.isNoDocument()) {\n remoteDoc.noDocument = {\n path: key.path.toArray(),\n readTime: toDbTimestamp(document.version)\n };\n } else if (document.isUnknownDocument()) {\n remoteDoc.unknownDocument = {\n path: key.path.toArray(),\n version: toDbTimestamp(document.version)\n };\n } else {\n return fail('Unexpected Document ' + document);\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n ).queryTarget;\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n uid: string,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid,\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\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 { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n DbBundlesKey,\n DbBundleStore,\n DbNamedQueriesKey,\n DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbBundle,\n fromDbNamedQuery,\n toDbBundle,\n toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return bundlesStore(transaction)\n .get(bundleId)\n .next(bundle => {\n if (bundle) {\n return fromDbBundle(bundle);\n }\n return undefined;\n });\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return namedQueriesStore(transaction)\n .get(queryName)\n .next(query => {\n if (query) {\n return fromDbNamedQuery(query);\n }\n return undefined;\n });\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbNamedQueryStore);\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 { User } from '../auth/user';\nimport {\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayKey,\n DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbDocumentOverlay,\n LocalSerializer,\n toDbDocumentOverlay,\n toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(\n private readonly serializer: LocalSerializer,\n private readonly userId: string\n ) {}\n\n static forUser(\n serializer: LocalSerializer,\n user: User\n ): IndexedDbDocumentOverlayCache {\n const userId = user.uid || '';\n return new IndexedDbDocumentOverlayCache(serializer, userId);\n }\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return documentOverlayStore(transaction)\n .get(toDbDocumentOverlayKey(this.userId, key))\n .next(dbOverlay => {\n if (dbOverlay) {\n return fromDbDocumentOverlay(this.serializer, dbOverlay);\n }\n return null;\n });\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\n const result = newOverlayMap();\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n return this.getOverlay(transaction, key).next(overlay => {\n if (overlay !== null) {\n result.set(key, overlay);\n }\n });\n }).next(() => result);\n }\n\n saveOverlays(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n overlays: MutationMap\n ): PersistencePromise {\n const promises: Array> = [];\n overlays.forEach((_, mutation) => {\n const overlay = new Overlay(largestBatchId, mutation);\n promises.push(this.saveOverlay(transaction, overlay));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const collectionPaths = new Set();\n\n // Get the set of unique collection paths.\n documentKeys.forEach(key =>\n collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n );\n\n const promises: Array> = [];\n collectionPaths.forEach(collectionPath => {\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, batchId],\n [this.userId, collectionPath, batchId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n promises.push(\n documentOverlayStore(transaction).deleteAll(\n DbDocumentOverlayCollectionPathOverlayIndex,\n range\n )\n );\n });\n return PersistencePromise.waitFor(promises);\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n const collectionPath = encodeResourcePath(collection);\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, sinceBatchId],\n [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n .next(dbOverlays => {\n for (const dbOverlay of dbOverlays) {\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n result.set(overlay.getKey(), overlay);\n }\n return result;\n });\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n const result = newOverlayMap();\n let currentBatchId: number | undefined = undefined;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionGroup, sinceBatchId],\n [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .iterate(\n {\n index: DbDocumentOverlayCollectionGroupOverlayIndex,\n range\n },\n (_, dbOverlay, control) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n if (\n result.size() < count ||\n overlay.largestBatchId === currentBatchId\n ) {\n result.set(overlay.getKey(), overlay);\n currentBatchId = overlay.largestBatchId;\n } else {\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n overlay: Overlay\n ): PersistencePromise {\n return documentOverlayStore(transaction).put(\n toDbDocumentOverlay(this.serializer, this.userId, overlay)\n );\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentOverlayStore\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 { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { isMaxValue } from '../model/values';\nimport { ArrayValue, MapValue, Value } from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { isNegativeZero } from '../util/types';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\n\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n\nconst INDEX_TYPE_NULL = 5;\nconst INDEX_TYPE_BOOLEAN = 10;\nconst INDEX_TYPE_NAN = 13;\nconst INDEX_TYPE_NUMBER = 15;\nconst INDEX_TYPE_TIMESTAMP = 20;\nconst INDEX_TYPE_STRING = 25;\nconst INDEX_TYPE_BLOB = 30;\nconst INDEX_TYPE_REFERENCE = 37;\nconst INDEX_TYPE_GEOPOINT = 45;\nconst INDEX_TYPE_ARRAY = 50;\nconst INDEX_TYPE_MAP = 55;\nconst INDEX_TYPE_REFERENCE_SEGMENT = 60;\n\n// A terminator that indicates that a truncatable value was not truncated.\n// This must be smaller than all other type labels.\nconst NOT_TRUNCATED = 2;\n\n/** Firestore index value writer. */\nexport class FirestoreIndexValueWriter {\n static INSTANCE = new FirestoreIndexValueWriter();\n\n private constructor() {}\n\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n //\n // As an example, consider the resulting encoding for:\n //\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n\n /** Writes an index value. */\n writeIndexValue(value: Value, encoder: DirectionalIndexByteEncoder): void {\n this.writeIndexValueAux(value, encoder);\n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n encoder.writeInfinity();\n }\n\n private writeIndexValueAux(\n indexValue: Value,\n encoder: DirectionalIndexByteEncoder\n ): void {\n if ('nullValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NULL);\n } else if ('booleanValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BOOLEAN);\n encoder.writeNumber(indexValue.booleanValue ? 1 : 0);\n } else if ('integerValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n encoder.writeNumber(normalizeNumber(indexValue.integerValue));\n } else if ('doubleValue' in indexValue) {\n const n = normalizeNumber(indexValue.doubleValue);\n if (isNaN(n)) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NAN);\n } else {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n if (isNegativeZero(n)) {\n // -0.0, 0 and 0.0 are all considered the same\n encoder.writeNumber(0.0);\n } else {\n encoder.writeNumber(n);\n }\n }\n } else if ('timestampValue' in indexValue) {\n let timestamp = indexValue.timestampValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_TIMESTAMP);\n if (typeof timestamp === 'string') {\n timestamp = normalizeTimestamp(timestamp);\n }\n encoder.writeString(`${timestamp.seconds || ''}`);\n encoder.writeNumber(timestamp.nanos || 0);\n } else if ('stringValue' in indexValue) {\n this.writeIndexString(indexValue.stringValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else if ('bytesValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BLOB);\n encoder.writeBytes(normalizeByteString(indexValue.bytesValue!));\n this.writeTruncationMarker(encoder);\n } else if ('referenceValue' in indexValue) {\n this.writeIndexEntityRef(indexValue.referenceValue!, encoder);\n } else if ('geoPointValue' in indexValue) {\n const geoPoint = indexValue.geoPointValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_GEOPOINT);\n encoder.writeNumber(geoPoint.latitude || 0);\n encoder.writeNumber(geoPoint.longitude || 0);\n } else if ('mapValue' in indexValue) {\n if (isMaxValue(indexValue)) {\n this.writeValueTypeLabel(encoder, Number.MAX_SAFE_INTEGER);\n } else {\n this.writeIndexMap(indexValue.mapValue!, encoder);\n this.writeTruncationMarker(encoder);\n }\n } else if ('arrayValue' in indexValue) {\n this.writeIndexArray(indexValue.arrayValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else {\n fail('unknown index value type ' + indexValue);\n }\n }\n\n private writeIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_STRING);\n this.writeUnlabeledIndexString(stringIndexValue, encoder);\n }\n\n private writeUnlabeledIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n encoder.writeString(stringIndexValue);\n }\n\n private writeIndexMap(\n mapIndexValue: MapValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const map = mapIndexValue.fields || {};\n this.writeValueTypeLabel(encoder, INDEX_TYPE_MAP);\n for (const key of Object.keys(map)) {\n this.writeIndexString(key, encoder);\n this.writeIndexValueAux(map[key], encoder);\n }\n }\n\n private writeIndexArray(\n arrayIndexValue: ArrayValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const values = arrayIndexValue.values || [];\n this.writeValueTypeLabel(encoder, INDEX_TYPE_ARRAY);\n for (const element of values) {\n this.writeIndexValueAux(element, encoder);\n }\n }\n\n private writeIndexEntityRef(\n referenceValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE);\n const path = DocumentKey.fromName(referenceValue).path;\n path.forEach(segment => {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE_SEGMENT);\n this.writeUnlabeledIndexString(segment, encoder);\n });\n }\n\n private writeValueTypeLabel(\n encoder: DirectionalIndexByteEncoder,\n typeOrder: number\n ): void {\n encoder.writeNumber(typeOrder);\n }\n\n private writeTruncationMarker(encoder: DirectionalIndexByteEncoder): void {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n encoder.writeNumber(NOT_TRUNCATED);\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 | agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n/** These constants are taken from the backend. */\nconst MIN_SURROGATE = '\\uD800';\nconst MAX_SURROGATE = '\\uDBFF';\n\nconst ESCAPE1 = 0x00;\nconst NULL_BYTE = 0xff; // Combined with ESCAPE1\nconst SEPARATOR = 0x01; // Combined with ESCAPE1\n\nconst ESCAPE2 = 0xff;\nconst INFINITY = 0xff; // Combined with ESCAPE2\nconst FF_BYTE = 0x00; // Combined with ESCAPE2\n\nconst LONG_SIZE = 64;\nconst BYTE_SIZE = 8;\n\n/**\n * The default size of the buffer. This is arbitrary, but likely larger than\n * most index values so that less copies of the underlying buffer will be made.\n * For large values, a single copy will made to double the buffer length.\n */\nconst DEFAULT_BUFFER_SIZE = 1024;\n\n/** Converts a JavaScript number to a byte array (using big endian encoding). */\nfunction doubleToLongBits(value: number): Uint8Array {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value, /* littleEndian= */ false);\n return new Uint8Array(dv.buffer);\n}\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nexport function numberOfLeadingZerosInByte(x: number): number {\n debugAssert(x < 256, 'Provided value is not a byte: ' + x);\n if (x === 0) {\n return 8;\n }\n\n let zeros = 0;\n if (x >> 4 === 0) {\n // Test if the first four bits are zero.\n zeros += 4;\n x = x << 4;\n }\n if (x >> 6 === 0) {\n // Test if the first two (or next two) bits are zero.\n zeros += 2;\n x = x << 2;\n }\n if (x >> 7 === 0) {\n // Test if the remaining bit is zero.\n zeros += 1;\n }\n return zeros;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\nfunction numberOfLeadingZeros(bytes: Uint8Array): number {\n debugAssert(\n bytes.length === 8,\n 'Can only count leading zeros in 64-bit numbers'\n );\n let leadingZeros = 0;\n for (let i = 0; i < 8; ++i) {\n const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff);\n leadingZeros += zeros;\n if (zeros !== 8) {\n break;\n }\n }\n return leadingZeros;\n}\n\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction unsignedNumLength(value: Uint8Array): number {\n // This is just the number of bytes for the unsigned representation of the number.\n const numBits = LONG_SIZE - numberOfLeadingZeros(value);\n return Math.ceil(numBits / BYTE_SIZE);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */\nexport class OrderedCodeWriter {\n buffer = new Uint8Array(DEFAULT_BUFFER_SIZE);\n position = 0;\n\n writeBytesAscending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteAscending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorAscending();\n }\n\n writeBytesDescending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteDescending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorDescending();\n }\n\n /** Writes utf8 bytes into this byte sequence, ascending. */\n writeUtf8Ascending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteAscending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteAscending((0x0f << 6) | (charCode >>> 6));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteAscending((0x0f << 5) | (charCode >>> 12));\n this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteAscending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorAscending();\n }\n\n /** Writes utf8 bytes into this byte sequence, descending */\n writeUtf8Descending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteDescending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteDescending((0x0f << 6) | (charCode >>> 6));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteDescending((0x0f << 5) | (charCode >>> 12));\n this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteDescending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorDescending();\n }\n\n writeNumberAscending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = len & 0xff; // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = value[i] & 0xff;\n }\n }\n\n writeNumberDescending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = ~(len & 0xff); // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = ~(value[i] & 0xff);\n }\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */\n writeInfinityAscending(): void {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(INFINITY);\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */\n writeInfinityDescending(): void {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(INFINITY);\n }\n\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */\n reset(): void {\n this.position = 0;\n }\n\n seed(encodedBytes: Uint8Array): void {\n this.ensureAvailable(encodedBytes.length);\n this.buffer.set(encodedBytes, this.position);\n this.position += encodedBytes.length;\n }\n\n /** Makes a copy of the encoded bytes in this buffer. */\n encodedBytes(): Uint8Array {\n return this.buffer.slice(0, this.position);\n }\n\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */\n private toOrderedBits(val: number): Uint8Array {\n const value = doubleToLongBits(val);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n const isNegative = (value[0] & 0x80) !== 0;\n\n // Revert the two complement to get natural ordering\n value[0] ^= isNegative ? 0xff : 0x80;\n for (let i = 1; i < value.length; ++i) {\n value[i] ^= isNegative ? 0xff : 0x00;\n }\n return value;\n }\n\n /** Writes a single byte ascending to the buffer. */\n private writeByteAscending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(FF_BYTE);\n } else {\n this.writeEscapedByteAscending(masked);\n }\n }\n\n /** Writes a single byte descending to the buffer. */\n private writeByteDescending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(FF_BYTE);\n } else {\n this.writeEscapedByteDescending(b);\n }\n }\n\n private writeSeparatorAscending(): void {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(SEPARATOR);\n }\n\n private writeSeparatorDescending(): void {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(SEPARATOR);\n }\n\n private writeEscapedByteAscending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = b;\n }\n\n private writeEscapedByteDescending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = ~b;\n }\n\n private ensureAvailable(bytes: number): void {\n const minCapacity = bytes + this.position;\n if (minCapacity <= this.buffer.length) {\n return;\n }\n // Try doubling.\n let newLength = this.buffer.length * 2;\n // Still not big enough? Just allocate the right size.\n if (newLength < minCapacity) {\n newLength = minCapacity;\n }\n // Create the new buffer.\n const newBuffer = new Uint8Array(newLength);\n newBuffer.set(this.buffer); // copy old data\n this.buffer = newBuffer;\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 */\nimport { IndexKind } from '../model/field_index';\nimport { ByteString } from '../util/byte_string';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\nimport { OrderedCodeWriter } from './ordered_code_writer';\n\nclass AscendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesAscending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Ascending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberAscending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityAscending();\n }\n}\n\nclass DescendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesDescending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Descending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberDescending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityDescending();\n }\n}\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */\nexport class IndexByteEncoder {\n private orderedCode = new OrderedCodeWriter();\n private ascending = new AscendingIndexByteEncoder(this.orderedCode);\n private descending = new DescendingIndexByteEncoder(this.orderedCode);\n\n seed(encodedBytes: Uint8Array): void {\n this.orderedCode.seed(encodedBytes);\n }\n\n forKind(kind: IndexKind): DirectionalIndexByteEncoder {\n return kind === IndexKind.ASCENDING ? this.ascending : this.descending;\n }\n\n encodedBytes(): Uint8Array {\n return this.orderedCode.encodedBytes();\n }\n\n reset(): void {\n this.orderedCode.reset();\n }\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 { DocumentKey } from '../model/document_key';\n\n/** Represents an index entry saved by the SDK in persisted storage. */\nexport class IndexEntry {\n constructor(\n readonly indexId: number,\n readonly documentKey: DocumentKey,\n readonly arrayValue: Uint8Array,\n readonly directionalValue: Uint8Array\n ) {}\n\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */\n successor(): IndexEntry {\n const currentLength = this.directionalValue.length;\n const newLength =\n currentLength === 0 || this.directionalValue[currentLength - 1] === 255\n ? currentLength + 1\n : currentLength;\n\n const successor = new Uint8Array(newLength);\n successor.set(this.directionalValue, 0);\n if (newLength !== currentLength) {\n successor.set([0], this.directionalValue.length);\n } else {\n ++successor[successor.length - 1];\n }\n\n return new IndexEntry(\n this.indexId,\n this.documentKey,\n this.arrayValue,\n successor\n );\n }\n}\n\nexport function indexEntryComparator(\n left: IndexEntry,\n right: IndexEntry\n): number {\n let cmp = left.indexId - right.indexId;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left.arrayValue, right.arrayValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left.directionalValue, right.directionalValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n return DocumentKey.comparator(left.documentKey, right.documentKey);\n}\n\nexport function compareByteArrays(left: Uint8Array, right: Uint8Array): number {\n for (let i = 0; i < left.length && i < right.length; ++i) {\n const compare = left[i] - right[i];\n if (compare !== 0) {\n return compare;\n }\n }\n return left.length - right.length;\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 { FieldFilter, Operator } from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { Target } from '../core/target';\nimport { hardAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind,\n IndexSegment,\n IndexState\n} from './field_index';\nimport { FieldPath } from './path';\n\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */\nexport class TargetIndexMatcher {\n // The collection ID (or collection group) of the query target.\n private readonly collectionId: string;\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n private inequalityFilters = new SortedSet((lhs, rhs) =>\n FieldPath.comparator(lhs.field, rhs.field)\n );\n\n // The list of equality filters of the target.\n private readonly equalityFilters: FieldFilter[];\n // The list of orderBys of the target.\n private readonly orderBys: OrderBy[];\n\n constructor(target: Target) {\n this.collectionId =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n this.orderBys = target.orderBy;\n this.equalityFilters = [];\n for (const filter of target.filters) {\n const fieldFilter = filter as FieldFilter;\n if (fieldFilter.isInequality()) {\n this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n } else {\n this.equalityFilters.push(fieldFilter);\n }\n }\n }\n\n get hasMultipleInequality(): boolean {\n return this.inequalityFilters.size > 1;\n }\n\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */\n servedByIndex(index: FieldIndex): boolean {\n hardAssert(\n index.collectionGroup === this.collectionId,\n 'Collection IDs do not match'\n );\n\n if (this.hasMultipleInequality) {\n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return false;\n }\n\n // If there is an array element, find a matching filter.\n const arraySegment = fieldIndexGetArraySegment(index);\n if (\n arraySegment !== undefined &&\n !this.hasMatchingEqualityFilter(arraySegment)\n ) {\n return false;\n }\n\n const segments = fieldIndexGetDirectionalSegments(index);\n let equalitySegments = new Set();\n let segmentIndex = 0;\n let orderBysIndex = 0;\n\n // Process all equalities first. Equalities can appear out of order.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n // We attempt to greedily match all segments to equality filters. If a\n // filter matches an index segment, we can mark the segment as used.\n if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n equalitySegments = equalitySegments.add(\n segments[segmentIndex].fieldPath.canonicalString()\n );\n } else {\n // If we cannot find a matching filter, we need to verify whether the\n // remaining segments map to the target's inequality and its orderBy\n // clauses.\n break;\n }\n }\n\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (segmentIndex === segments.length) {\n return true;\n }\n\n if (this.inequalityFilters.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n const segment = segments[segmentIndex];\n\n if (\n !this.matchesFilter(inequalityFilter, segment) ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n ++segmentIndex;\n }\n\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n const segment = segments[segmentIndex];\n if (\n orderBysIndex >= this.orderBys.length ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */\n buildTargetIndex(): FieldIndex | null {\n if (this.hasMultipleInequality) {\n return null;\n }\n\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let uniqueFields = new SortedSet(FieldPath.comparator);\n const segments: IndexSegment[] = [];\n\n for (const filter of this.equalityFilters) {\n if (filter.field.isKeyField()) {\n continue;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n if (isArrayOperator) {\n segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n } else {\n if (uniqueFields.has(filter.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(filter.field);\n segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n }\n }\n\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const orderBy of this.orderBys) {\n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n if (orderBy.field.isKeyField()) {\n continue;\n }\n\n if (uniqueFields.has(orderBy.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(orderBy.field);\n\n segments.push(\n new IndexSegment(\n orderBy.field,\n orderBy.dir === Direction.ASCENDING\n ? IndexKind.ASCENDING\n : IndexKind.DESCENDING\n )\n );\n }\n\n return new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n this.collectionId,\n segments,\n IndexState.empty()\n );\n }\n\n private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n for (const filter of this.equalityFilters) {\n if (this.matchesFilter(filter, segment)) {\n return true;\n }\n }\n return false;\n }\n\n private matchesFilter(\n filter: FieldFilter | undefined,\n segment: IndexSegment\n ): boolean {\n if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n return false;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n }\n\n private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n if (!orderBy.field.isEqual(segment.fieldPath)) {\n return false;\n }\n return (\n (segment.kind === IndexKind.ASCENDING &&\n orderBy.dir === Direction.ASCENDING) ||\n (segment.kind === IndexKind.DESCENDING &&\n orderBy.dir === Direction.DESCENDING)\n );\n }\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 {\n CompositeFilter,\n compositeFilterIsConjunction,\n compositeFilterIsDisjunction,\n compositeFilterIsFlat,\n compositeFilterIsFlatConjunction,\n compositeFilterWithAddedFilters,\n CompositeOperator,\n FieldFilter,\n Filter,\n InFilter,\n Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n if (filter instanceof InFilter) {\n const expandedFilters =\n filter.value.arrayValue?.values?.map(value =>\n FieldFilter.create(filter.field, Operator.EQUAL, value)\n ) || [];\n\n return CompositeFilter.create(expandedFilters, CompositeOperator.OR);\n } else {\n // We have reached other kinds of field filters.\n return filter;\n }\n }\n\n // We have a composite filter.\n const expandedFilters = filter.filters.map(subfilter =>\n computeInExpansion(subfilter)\n );\n return CompositeFilter.create(expandedFilters, filter.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

    Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */\nexport function getDnfTerms(filter: CompositeFilter): Filter[] {\n if (filter.getFilters().length === 0) {\n return [];\n }\n\n const result: Filter = computeDistributedNormalForm(\n computeInExpansion(filter)\n );\n\n hardAssert(\n isDisjunctiveNormalForm(result),\n 'computeDistributedNormalForm did not result in disjunctive normal form'\n );\n\n if (isSingleFieldFilter(result) || isFlatConjunction(result)) {\n return [result];\n }\n\n return result.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */\nfunction isSingleFieldFilter(filter: Filter): boolean {\n return filter instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */\nfunction isFlatConjunction(filter: Filter): boolean {\n return (\n filter instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(filter)\n );\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

    In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

    For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n return (\n isSingleFieldFilter(filter) ||\n isFlatConjunction(filter) ||\n isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n filter: Filter\n): boolean {\n if (filter instanceof CompositeFilter) {\n if (compositeFilterIsDisjunction(filter)) {\n for (const subFilter of filter.getFilters()) {\n if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n if (filter.filters.length === 1) {\n return computeDistributedNormalForm(filter.filters[0]);\n }\n\n // Compute DNF for each of the subfilters first\n const result = filter.filters.map(subfilter =>\n computeDistributedNormalForm(subfilter)\n );\n\n let newFilter: Filter = CompositeFilter.create(result, filter.op);\n newFilter = applyAssociation(newFilter);\n\n if (isDisjunctiveNormalForm(newFilter)) {\n return newFilter;\n }\n\n hardAssert(\n newFilter instanceof CompositeFilter,\n 'field filters are already in DNF form'\n );\n hardAssert(\n compositeFilterIsConjunction(newFilter),\n 'Disjunction of filters all of which are already in DNF form is itself in DNF form.'\n );\n hardAssert(\n newFilter.filters.length > 1,\n 'Single-filter composite filters are already in DNF form.'\n );\n\n return newFilter.filters.reduce((runningResult, filter) =>\n applyDistribution(runningResult, filter)\n );\n}\n\nexport function applyDistribution(lhs: Filter, rhs: Filter): Filter {\n hardAssert(\n lhs instanceof FieldFilter || lhs instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n hardAssert(\n rhs instanceof FieldFilter || rhs instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n let result: Filter;\n\n if (lhs instanceof FieldFilter) {\n if (rhs instanceof FieldFilter) {\n // FieldFilter FieldFilter\n result = applyDistributionFieldFilters(lhs, rhs);\n } else {\n // FieldFilter CompositeFilter\n result = applyDistributionFieldAndCompositeFilters(lhs, rhs);\n }\n } else {\n if (rhs instanceof FieldFilter) {\n // CompositeFilter FieldFilter\n result = applyDistributionFieldAndCompositeFilters(rhs, lhs);\n } else {\n // CompositeFilter CompositeFilter\n result = applyDistributionCompositeFilters(lhs, rhs);\n }\n }\n\n return applyAssociation(result);\n}\n\nfunction applyDistributionFieldFilters(\n lhs: FieldFilter,\n rhs: FieldFilter\n): Filter {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([lhs, rhs], CompositeOperator.AND);\n}\n\nfunction applyDistributionCompositeFilters(\n lhs: CompositeFilter,\n rhs: CompositeFilter\n): Filter {\n hardAssert(\n lhs.filters.length > 0 && rhs.filters.length > 0,\n 'Found an empty composite filter'\n );\n\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n\n // Case 1 is a merge.\n if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {\n return compositeFilterWithAddedFilters(lhs, rhs.getFilters());\n }\n\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;\n const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;\n const results = disjunctionSide.filters.map(subfilter =>\n applyDistribution(subfilter, otherSide)\n );\n return CompositeFilter.create(results, CompositeOperator.OR);\n}\n\nfunction applyDistributionFieldAndCompositeFilters(\n fieldFilter: FieldFilter,\n compositeFilter: CompositeFilter\n): Filter {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (compositeFilterIsConjunction(compositeFilter)) {\n // Case 1\n return compositeFilterWithAddedFilters(\n compositeFilter,\n fieldFilter.getFilters()\n );\n } else {\n // Case 2\n const newFilters = compositeFilter.filters.map(subfilter =>\n applyDistribution(fieldFilter, subfilter)\n );\n\n return CompositeFilter.create(newFilters, CompositeOperator.OR);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

      \n *
    • A | (B | C) == (A | B) | C == (A | B | C)\n *
    • A & (B & C) == (A & B) & C == (A & B & C)\n *
    \n *\n *

    For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n const filters = filter.getFilters();\n\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (filters.length === 1) {\n return applyAssociation(filters[0]);\n }\n\n // Associativity applied to a flat composite filter results is itself.\n if (compositeFilterIsFlat(filter)) {\n return filter;\n }\n\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));\n\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n const newSubfilters: Filter[] = [];\n updatedFilters.forEach(subfilter => {\n if (subfilter instanceof FieldFilter) {\n newSubfilters.push(subfilter);\n } else if (subfilter instanceof CompositeFilter) {\n if (subfilter.op === filter.op) {\n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n newSubfilters.push(...subfilter.filters);\n } else {\n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n newSubfilters.push(subfilter);\n }\n }\n });\n\n if (newSubfilters.length === 1) {\n return newSubfilters[0];\n }\n\n return CompositeFilter.create(newSubfilters, filter.op);\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 { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\n this.collectionParentIndex.add(collectionPath);\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise {\n return PersistencePromise.resolve(\n this.collectionParentIndex.getEntries(collectionId)\n );\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(IndexType.NONE);\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve([]);\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */\nexport class MemoryCollectionParentIndex {\n private index = {} as {\n [collectionId: string]: SortedSet;\n };\n\n // Returns false if the entry already existed.\n add(collectionPath: ResourcePath): boolean {\n debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents =\n this.index[collectionId] ||\n new SortedSet(ResourcePath.comparator);\n const added = !existingParents.has(parentPath);\n this.index[collectionId] = existingParents.add(parentPath);\n return added;\n }\n\n has(collectionPath: ResourcePath): boolean {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents = this.index[collectionId];\n return existingParents && existingParents.has(parentPath);\n }\n\n getEntries(collectionId: string): ResourcePath[] {\n const parentPaths =\n this.index[collectionId] ||\n new SortedSet(ResourcePath.comparator);\n return parentPaths.toArray();\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\nimport { User } from '../auth/user';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport {\n canonifyTarget,\n newTarget,\n Target,\n targetEquals,\n targetGetArrayValues,\n targetGetLowerBound,\n targetGetNotInValues,\n targetGetSegmentCount,\n targetGetUpperBound,\n targetHasLimit\n} from '../core/target';\nimport { FirestoreIndexValueWriter } from '../index/firestore_index_value_writer';\nimport { IndexByteEncoder } from '../index/index_byte_encoder';\nimport { IndexEntry, indexEntryComparator } from '../index/index_entry';\nimport { documentKeySet, DocumentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n fieldIndexGetKeyOrder,\n fieldIndexToString,\n IndexKind,\n IndexOffset,\n indexOffsetComparator,\n IndexSegment\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { TargetIndexMatcher } from '../model/target_index_matcher';\nimport { isArray, refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { getDnfTerms } from '../util/logic_utils';\nimport { immediateSuccessor, primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { diffSortedSets, SortedSet } from '../util/sorted_set';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexManager, IndexType } from './index_manager';\nimport {\n DbCollectionParent,\n DbIndexConfiguration,\n DbIndexEntry,\n DbIndexState\n} from './indexeddb_schema';\nimport {\n DbCollectionParentKey,\n DbCollectionParentStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationKey,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryKey,\n DbIndexEntryStore,\n DbIndexStateKey,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbIndexConfiguration,\n toDbIndexConfiguration,\n toDbIndexState\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nconst LOG_TAG = 'IndexedDbIndexManager';\n\nconst EMPTY_VALUE = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nexport class IndexedDbIndexManager implements IndexManager {\n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n private collectionParentsCache = new MemoryCollectionParentIndex();\n\n private readonly uid: string;\n\n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n private targetToDnfSubTargets = new ObjectMap(\n t => canonifyTarget(t),\n (l, r) => targetEquals(l, r)\n );\n\n constructor(user: User, private readonly databaseId: DatabaseId) {\n this.uid = user.uid || '';\n }\n\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\n debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n if (!this.collectionParentsCache.has(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n\n transaction.addOnCommittedListener(() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.collectionParentsCache.add(collectionPath);\n });\n\n const collectionParent: DbCollectionParent = {\n collectionId,\n parent: encodeResourcePath(parentPath)\n };\n return collectionParentsStore(transaction).put(collectionParent);\n }\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise {\n const parentPaths = [] as ResourcePath[];\n const range = IDBKeyRange.bound(\n [collectionId, ''],\n [immediateSuccessor(collectionId), ''],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return collectionParentsStore(transaction)\n .loadAll(range)\n .next(entries => {\n for (const entry of entries) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (entry.collectionId !== collectionId) {\n break;\n }\n parentPaths.push(decodeResourcePath(entry.parent));\n }\n return parentPaths;\n });\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const indexes = indexConfigurationStore(transaction);\n const dbIndex = toDbIndexConfiguration(index);\n delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb\n const result = indexes.add(dbIndex);\n if (index.indexState) {\n const states = indexStateStore(transaction);\n return result.next(indexId => {\n states.put(\n toDbIndexState(\n indexId,\n this.uid,\n index.indexState.sequenceNumber,\n index.indexState.offset\n )\n );\n });\n } else {\n return result.next();\n }\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n const entries = indexEntriesStore(transaction);\n return indexes\n .delete(index.indexId)\n .next(() =>\n states.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n )\n .next(() =>\n entries.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n );\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const indexes = indexConfigurationStore(transaction);\n const entries = indexEntriesStore(transaction);\n const states = indexStateStore(transaction);\n\n return indexes\n .deleteAll()\n .next(() => entries.deleteAll())\n .next(() => states.deleteAll());\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getIndexType(transaction, subTarget).next(type => {\n if (type === IndexType.NONE || type === IndexType.PARTIAL) {\n const targetIndexMatcher = new TargetIndexMatcher(subTarget);\n const fieldIndex = targetIndexMatcher.buildTargetIndex();\n if (fieldIndex != null) {\n return this.addFieldIndex(transaction, fieldIndex);\n }\n }\n });\n }\n );\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n const indexEntries = indexEntriesStore(transaction);\n\n let canServeTarget = true;\n const indexes = new Map();\n\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getFieldIndex(transaction, subTarget).next(index => {\n canServeTarget &&= !!index;\n indexes.set(subTarget, index);\n });\n }\n ).next(() => {\n if (!canServeTarget) {\n return PersistencePromise.resolve(null as DocumentKey[] | null);\n } else {\n let existingKeys = documentKeySet();\n const result: DocumentKey[] = [];\n return PersistencePromise.forEach(indexes, (index, subTarget) => {\n logDebug(\n LOG_TAG,\n `Using index ${fieldIndexToString(\n index!\n )} to execute ${canonifyTarget(target)}`\n );\n\n const arrayValues = targetGetArrayValues(subTarget, index!);\n const notInValues = targetGetNotInValues(subTarget, index!);\n const lowerBound = targetGetLowerBound(subTarget, index!);\n const upperBound = targetGetUpperBound(subTarget, index!);\n\n const lowerBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n lowerBound\n );\n const upperBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n upperBound\n );\n const notInEncoded = this.encodeValues(\n index!,\n subTarget,\n notInValues\n );\n\n const indexRanges = this.generateIndexRanges(\n index!.indexId,\n arrayValues,\n lowerBoundEncoded,\n lowerBound.inclusive,\n upperBoundEncoded,\n upperBound.inclusive,\n notInEncoded\n );\n return PersistencePromise.forEach(\n indexRanges,\n (indexRange: IDBKeyRange) => {\n return indexEntries\n .loadFirst(indexRange, target.limit)\n .next(entries => {\n entries.forEach(entry => {\n const documentKey = DocumentKey.fromSegments(\n entry.documentKey\n );\n if (!existingKeys.has(documentKey)) {\n existingKeys = existingKeys.add(documentKey);\n result.push(documentKey);\n }\n });\n });\n }\n );\n }).next(() => result as DocumentKey[] | null);\n }\n });\n }\n\n private getSubTargets(target: Target): Target[] {\n let subTargets = this.targetToDnfSubTargets.get(target);\n if (subTargets) {\n return subTargets;\n }\n\n if (target.filters.length === 0) {\n subTargets = [target];\n } else {\n // There is an implicit AND operation between all the filters stored in the target\n const dnf: Filter[] = getDnfTerms(\n CompositeFilter.create(target.filters, CompositeOperator.AND)\n );\n\n subTargets = dnf.map(term =>\n newTarget(\n target.path,\n target.collectionGroup,\n target.orderBy,\n term.getFilters(),\n target.limit,\n target.startAt,\n target.endAt\n )\n );\n }\n\n this.targetToDnfSubTargets.set(target, subTargets);\n return subTargets;\n }\n\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */\n private generateIndexRanges(\n indexId: number,\n arrayValues: ProtoValue[] | null,\n lowerBounds: Uint8Array[],\n lowerBoundInclusive: boolean,\n upperBounds: Uint8Array[],\n upperBoundInclusive: boolean,\n notInValues: Uint8Array[]\n ): IDBKeyRange[] {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const totalScans =\n (arrayValues != null ? arrayValues.length : 1) *\n Math.max(lowerBounds.length, upperBounds.length);\n const scansPerArrayElement =\n totalScans / (arrayValues != null ? arrayValues.length : 1);\n\n const indexRanges: IDBKeyRange[] = [];\n for (let i = 0; i < totalScans; ++i) {\n const arrayValue = arrayValues\n ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement])\n : EMPTY_VALUE;\n\n const lowerBound = this.generateLowerBound(\n indexId,\n arrayValue,\n lowerBounds[i % scansPerArrayElement],\n lowerBoundInclusive\n );\n const upperBound = this.generateUpperBound(\n indexId,\n arrayValue,\n upperBounds[i % scansPerArrayElement],\n upperBoundInclusive\n );\n\n const notInBound = notInValues.map(notIn =>\n this.generateLowerBound(\n indexId,\n arrayValue,\n notIn,\n /* inclusive= */ true\n )\n );\n\n indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound));\n }\n\n return indexRanges;\n }\n\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */\n private generateLowerBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry : entry.successor();\n }\n\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */\n private generateUpperBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry.successor() : entry;\n }\n\n private getFieldIndex(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n const targetIndexMatcher = new TargetIndexMatcher(target);\n const collectionGroup =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n\n return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {\n // Return the index with the most number of segments.\n let index: FieldIndex | null = null;\n for (const candidate of indexes) {\n const matches = targetIndexMatcher.servedByIndex(candidate);\n if (\n matches &&\n (!index || candidate.fields.length > index.fields.length)\n ) {\n index = candidate;\n }\n }\n return index;\n });\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n let indexType = IndexType.FULL;\n const subTargets = this.getSubTargets(target);\n return PersistencePromise.forEach(subTargets, (target: Target) => {\n return this.getFieldIndex(transaction, target).next(index => {\n if (!index) {\n indexType = IndexType.NONE;\n } else if (\n indexType !== IndexType.NONE &&\n index.fields.length < targetGetSegmentCount(target)\n ) {\n indexType = IndexType.PARTIAL;\n }\n });\n }).next(() => {\n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n if (\n targetHasLimit(target) &&\n subTargets.length > 1 &&\n indexType === IndexType.FULL\n ) {\n return IndexType.PARTIAL;\n }\n\n return indexType;\n });\n }\n\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */\n private encodeDirectionalElements(\n fieldIndex: FieldIndex,\n document: Document\n ): Uint8Array | null {\n const encoder = new IndexByteEncoder();\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const field = document.data.field(segment.fieldPath);\n if (field == null) {\n return null;\n }\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n field,\n directionalEncoder\n );\n }\n return encoder.encodedBytes();\n }\n\n /** Encodes a single value to the ascending index format. */\n private encodeSingleElement(value: ProtoValue): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n encoder.forKind(IndexKind.ASCENDING)\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */\n private encodeDirectionalKey(\n fieldIndex: FieldIndex,\n documentKey: DocumentKey\n ): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n refValue(this.databaseId, documentKey),\n encoder.forKind(fieldIndexGetKeyOrder(fieldIndex))\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */\n private encodeValues(\n fieldIndex: FieldIndex,\n target: Target,\n values: ProtoValue[] | null\n ): Uint8Array[] {\n if (values === null) {\n return [];\n }\n\n let encoders: IndexByteEncoder[] = [];\n encoders.push(new IndexByteEncoder());\n\n let valueIdx = 0;\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const value = values[valueIdx++];\n for (const encoder of encoders) {\n if (this.isInFilter(target, segment.fieldPath) && isArray(value)) {\n encoders = this.expandIndexValues(encoders, segment, value);\n } else {\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n directionalEncoder\n );\n }\n }\n }\n return this.getEncodedBytes(encoders);\n }\n\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */\n private encodeBound(\n fieldIndex: FieldIndex,\n target: Target,\n bound: Bound\n ): Uint8Array[] {\n return this.encodeValues(fieldIndex, target, bound.position);\n }\n\n /** Returns the byte representation for the provided encoders. */\n private getEncodedBytes(encoders: IndexByteEncoder[]): Uint8Array[] {\n const result: Uint8Array[] = [];\n for (let i = 0; i < encoders.length; ++i) {\n result[i] = encoders[i].encodedBytes();\n }\n return result;\n }\n\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */\n private expandIndexValues(\n encoders: IndexByteEncoder[],\n segment: IndexSegment,\n value: ProtoValue\n ): IndexByteEncoder[] {\n const prefixes = [...encoders];\n const results: IndexByteEncoder[] = [];\n for (const arrayElement of value.arrayValue!.values || []) {\n for (const prefix of prefixes) {\n const clonedEncoder = new IndexByteEncoder();\n clonedEncoder.seed(prefix.encodedBytes());\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n arrayElement,\n clonedEncoder.forKind(segment.kind)\n );\n results.push(clonedEncoder);\n }\n }\n return results;\n }\n\n private isInFilter(target: Target, fieldPath: FieldPath): boolean {\n return !!target.filters.find(\n f =>\n f instanceof FieldFilter &&\n f.field.isEqual(fieldPath) &&\n (f.op === Operator.IN || f.op === Operator.NOT_IN)\n );\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n\n return (\n collectionGroup\n ? indexes.loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n : indexes.loadAll()\n ).next(indexConfigs => {\n const result: FieldIndex[] = [];\n return PersistencePromise.forEach(\n indexConfigs,\n (indexConfig: DbIndexConfiguration) => {\n return states\n .get([indexConfig.indexId!, this.uid])\n .next(indexState => {\n result.push(fromDbIndexConfiguration(indexConfig, indexState));\n });\n }\n ).next(() => result);\n });\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.getFieldIndexes(transaction).next(indexes => {\n if (indexes.length === 0) {\n return null;\n }\n indexes.sort((l, r) => {\n const cmp = l.indexState.sequenceNumber - r.indexState.sequenceNumber;\n return cmp !== 0\n ? cmp\n : primitiveComparator(l.collectionGroup, r.collectionGroup);\n });\n return indexes[0].collectionGroup;\n });\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n return this.getNextSequenceNumber(transaction).next(nextSequenceNumber =>\n indexes\n .loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n .next(configs =>\n PersistencePromise.forEach(configs, (config: DbIndexConfiguration) =>\n states.put(\n toDbIndexState(\n config.indexId!,\n this.uid,\n nextSequenceNumber,\n offset\n )\n )\n )\n )\n );\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const memoizedIndexes = new Map();\n return PersistencePromise.forEach(documents, (key, doc) => {\n const memoizedCollectionIndexes = memoizedIndexes.get(\n key.collectionGroup\n );\n const fieldIndexes = memoizedCollectionIndexes\n ? PersistencePromise.resolve(memoizedCollectionIndexes)\n : this.getFieldIndexes(transaction, key.collectionGroup);\n\n return fieldIndexes.next(fieldIndexes => {\n memoizedIndexes.set(key.collectionGroup, fieldIndexes);\n return PersistencePromise.forEach(\n fieldIndexes,\n (fieldIndex: FieldIndex) => {\n return this.getExistingIndexEntries(\n transaction,\n key,\n fieldIndex\n ).next(existingEntries => {\n const newEntries = this.computeIndexEntries(doc, fieldIndex);\n if (!existingEntries.isEqual(newEntries)) {\n return this.updateEntries(\n transaction,\n doc,\n fieldIndex,\n existingEntries,\n newEntries\n );\n }\n return PersistencePromise.resolve();\n });\n }\n );\n });\n });\n }\n\n private addIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.put({\n indexId: indexEntry.indexId,\n uid: this.uid,\n arrayValue: indexEntry.arrayValue,\n directionalValue: indexEntry.directionalValue,\n orderedDocumentKey: this.encodeDirectionalKey(fieldIndex, document.key),\n documentKey: document.key.path.toArray()\n });\n }\n\n private deleteIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.delete([\n indexEntry.indexId,\n this.uid,\n indexEntry.arrayValue,\n indexEntry.directionalValue,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key.path.toArray()\n ]);\n }\n\n private getExistingIndexEntries(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n fieldIndex: FieldIndex\n ): PersistencePromise> {\n const indexEntries = indexEntriesStore(transaction);\n let results = new SortedSet(indexEntryComparator);\n return indexEntries\n .iterate(\n {\n index: DbIndexEntryDocumentKeyIndex,\n range: IDBKeyRange.only([\n fieldIndex.indexId,\n this.uid,\n this.encodeDirectionalKey(fieldIndex, documentKey)\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n entry.arrayValue,\n entry.directionalValue\n )\n );\n }\n )\n .next(() => results);\n }\n\n /** Creates the index entries for the given document. */\n private computeIndexEntries(\n document: Document,\n fieldIndex: FieldIndex\n ): SortedSet {\n let results = new SortedSet(indexEntryComparator);\n\n const directionalValue = this.encodeDirectionalElements(\n fieldIndex,\n document\n );\n if (directionalValue == null) {\n return results;\n }\n\n const arraySegment = fieldIndexGetArraySegment(fieldIndex);\n if (arraySegment != null) {\n const value = document.data.field(arraySegment.fieldPath);\n if (isArray(value)) {\n for (const arrayValue of value.arrayValue!.values || []) {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n this.encodeSingleElement(arrayValue),\n directionalValue\n )\n );\n }\n }\n } else {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n EMPTY_VALUE,\n directionalValue\n )\n );\n }\n\n return results;\n }\n\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */\n private updateEntries(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n existingEntries: SortedSet,\n newEntries: SortedSet\n ): PersistencePromise {\n logDebug(LOG_TAG, \"Updating index entries for document '%s'\", document.key);\n\n const promises: Array> = [];\n diffSortedSets(\n existingEntries,\n newEntries,\n indexEntryComparator,\n /* onAdd= */ entry => {\n promises.push(\n this.addIndexEntry(transaction, document, fieldIndex, entry)\n );\n },\n /* onRemove= */ entry => {\n promises.push(\n this.deleteIndexEntry(transaction, document, fieldIndex, entry)\n );\n }\n );\n\n return PersistencePromise.waitFor(promises);\n }\n\n private getNextSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n let nextSequenceNumber = 1;\n const states = indexStateStore(transaction);\n return states\n .iterate(\n {\n index: DbIndexStateSequenceNumberIndex,\n reverse: true,\n range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])\n },\n (_, state, controller) => {\n controller.done();\n nextSequenceNumber = state.sequenceNumber + 1;\n }\n )\n .next(() => nextSequenceNumber);\n }\n\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */\n private createRange(\n lower: IndexEntry,\n upper: IndexEntry,\n notInValues: IndexEntry[]\n ): IDBKeyRange[] {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n notInValues = notInValues\n .sort((l, r) => indexEntryComparator(l, r))\n .filter(\n (el, i, values) => !i || indexEntryComparator(el, values[i - 1]) !== 0\n );\n\n const bounds: IndexEntry[] = [];\n bounds.push(lower);\n for (const notInValue of notInValues) {\n const cmpToLower = indexEntryComparator(notInValue, lower);\n const cmpToUpper = indexEntryComparator(notInValue, upper);\n\n if (cmpToLower === 0) {\n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n bounds[0] = lower.successor();\n } else if (cmpToLower > 0 && cmpToUpper < 0) {\n // `notInValue` is in the middle of the range\n bounds.push(notInValue);\n bounds.push(notInValue.successor());\n } else if (cmpToUpper > 0) {\n // `notInValue` (and all following values) are out of the range\n break;\n }\n }\n bounds.push(upper);\n\n const ranges: IDBKeyRange[] = [];\n for (let i = 0; i < bounds.length; i += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.isRangeMatchable(bounds[i], bounds[i + 1])) {\n return [];\n }\n\n const lowerBound = [\n bounds[i].indexId,\n this.uid,\n bounds[i].arrayValue,\n bounds[i].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n const upperBound = [\n bounds[i + 1].indexId,\n this.uid,\n bounds[i + 1].arrayValue,\n bounds[i + 1].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n ranges.push(IDBKeyRange.bound(lowerBound, upperBound));\n }\n return ranges;\n }\n\n isRangeMatchable(lowerBound: IndexEntry, upperBound: IndexEntry): boolean {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return indexEntryComparator(lowerBound, upperBound) > 0;\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise {\n return this.getFieldIndexes(transaction, collectionGroup).next(\n getMinOffsetFromFieldIndexes\n );\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n return PersistencePromise.mapArray(\n this.getSubTargets(target),\n (subTarget: Target) =>\n this.getFieldIndex(transaction, subTarget).next(index =>\n index ? index : fail('Target cannot be served from index')\n )\n ).next(getMinOffsetFromFieldIndexes);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */\nfunction collectionParentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbCollectionParentStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */\nfunction indexEntriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbIndexEntryStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */\nfunction indexConfigurationStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbIndexConfigurationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */\nfunction indexStateStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbIndexStateStore);\n}\n\nfunction getMinOffsetFromFieldIndexes(fieldIndexes: FieldIndex[]): IndexOffset {\n hardAssert(\n fieldIndexes.length !== 0,\n 'Found empty index group when looking for least recent index offset.'\n );\n\n let minOffset: IndexOffset = fieldIndexes[0].indexState.offset;\n let maxBatchId: number = minOffset.largestBatchId;\n for (let i = 1; i < fieldIndexes.length; i++) {\n const newOffset: IndexOffset = fieldIndexes[i].indexState.offset;\n if (indexOffsetComparator(newOffset, minOffset) < 0) {\n minOffset = newOffset;\n }\n if (maxBatchId < newOffset.largestBatchId) {\n maxBatchId = newOffset.largestBatchId;\n }\n }\n return new IndexOffset(minOffset.readTime, minOffset.documentKey, maxBatchId);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\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 { DocumentKey } from '../model/document_key';\nimport { fail, hardAssert } from '../util/assert';\n\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbRemoteDocument\n} from './indexeddb_schema';\nimport { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n newDbDocumentMutationKey\n} from './indexeddb_sentinels';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: { batchId: number; mutations: Array<{ key: DocumentKey }> }\n): PersistencePromise {\n const mutationStore = txn.store(\n DbMutationBatchStore\n );\n const indexTxn = txn.store(\n DbDocumentMutationStore\n );\n const promises: Array> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n hardAssert(\n numDeleted === 1,\n 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = newDbDocumentMutationKey(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Returns an approximate size for the given document.\n */\nexport function dbDocumentSize(\n doc: DbRemoteDocument | DbRemoteDocumentLegacy | null\n): number {\n if (!doc) {\n return 0;\n }\n\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail('Unknown remote document type');\n }\n return JSON.stringify(value).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 { User } from '../auth/user';\nimport { isCollectionGroupQuery, isDocumentQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { decodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { removeMutationBatch } from './indexeddb_mutation_batch_impl';\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue\n} from './indexeddb_schema';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationPlaceholder,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationQueueKey,\n DbMutationQueueStore,\n newDbDocumentMutationKey,\n newDbDocumentMutationPrefixForPath,\n newDbDocumentMutationPrefixForUser\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction, getStore } from './indexeddb_transaction';\nimport {\n fromDbMutationBatch,\n LocalSerializer,\n toDbMutationBatch\n} from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n hardAssert(user.uid !== '', 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n hardAssert(\n typeof batchId === 'number',\n 'Auto-generated key is not a number'\n );\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch);\n\n const promises: Array> = [];\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = newDbDocumentMutationKey(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutationPlaceholder)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n hardAssert(\n dbBatch.userId === this.userId,\n `Unexpected user '${dbBatch.userId}' for mutation batch ${batchId}`\n );\n return fromDbMutationBatch(this.serializer, dbBatch);\n }\n return null;\n });\n }\n\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n hardAssert(\n dbBatch.batchId >= nextBatchId,\n 'Should have found mutation after ' + nextBatchId\n );\n foundBatch = fromDbMutationBatch(this.serializer, dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 'Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n batchId\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n const promises: Array> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isDocumentQuery(query),\n \"Document queries shouldn't go down this path\"\n );\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet\n ): PersistencePromise {\n const results: MutationBatch[] = [];\n const promises: Array> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 'Dangling document-mutation reference found, ' +\n 'which points to ' +\n batchId\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n key\n );\n }\n );\n });\n }\n\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n newDbDocumentMutationPrefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = decodeResourcePath(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n hardAssert(\n danglingMutationReferences.length === 0,\n 'Document leak -- detected dangling mutation references when queue is empty. ' +\n 'Dangling keys: ' +\n danglingMutationReferences.map(p => p.canonicalString())\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\n\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata || {\n userId: this.userId,\n lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n lastStreamToken: ''\n }\n );\n });\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise {\n const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationBatchStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentMutationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationQueueStore\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentKey,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetQueryTargetsIndexName,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\n\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n metadata.highestTargetId = targetIdGenerator.next();\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion =\n lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n hardAssert(\n metadata.targetCount > 0,\n 'Removing from an empty target cache'\n );\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const promises: Array> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return globalTargetStore(transaction)\n .get(DbTargetGlobalKey)\n .next(metadata => {\n hardAssert(metadata !== null, 'Missing metadata row.');\n return metadata;\n });\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise {\n return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return targetsStore(transaction).put(\n toDbTarget(this.serializer, targetData)\n );\n }\n\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const canonicalId = canonifyTarget(target);\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTargetQueryTargetsIndexName },\n (key, value, control) => {\n const found = fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (targetEquals(target, found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = encodeResourcePath(key.path);\n promises.push(store.put({ targetId, path }));\n promises.push(this.referenceDelegate.addReference(txn, targetId, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = encodeResourcePath(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, targetId, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = decodeResourcePath(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const path = encodeResourcePath(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetGlobalStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbTargetDocumentStore\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 { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = new SortedSet(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\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 { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n decodeResourcePath,\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n documentTargetStore,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n ActiveTargets,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: Persistence, params: LruParams) {\n this.garbageCollector = newLruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return (this.db.getTargetCache() as IndexedDbTargetCache).removeTargets(\n txn,\n upperBound,\n activeTargetIds\n );\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise {\n return mutationQueuesContainKey(txn, docKey);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey, SnapshotVersion.min());\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }\n )\n .next(() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber };\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n private changesApplied = false;\n\n protected abstract getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise;\n\n protected abstract getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise;\n\n protected abstract applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n addEntry(document: MutableDocument): void {\n this.assertNotApplied();\n this.changes.set(document.key, document);\n }\n\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n removeEntry(key: DocumentKey, readTime: SnapshotVersion): void {\n this.assertNotApplied();\n this.changes.set(\n key,\n MutableDocument.newInvalidDocument(key).setReadTime(readTime)\n );\n }\n\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n this.assertNotApplied();\n const bufferedEntry = this.changes.get(documentKey);\n if (bufferedEntry !== undefined) {\n return PersistencePromise.resolve(bufferedEntry);\n } else {\n return this.getFromCache(transaction, documentKey);\n }\n }\n\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n return this.getAllFromCache(transaction, documentKeys);\n }\n\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n apply(transaction: PersistenceTransaction): PersistencePromise {\n this.assertNotApplied();\n this.changesApplied = true;\n return this.applyChanges(transaction);\n }\n\n /** Helper to assert this.changes is not null */\n protected assertNotApplied(): void {\n debugAssert(!this.changesApplied, 'Changes have already been applied.');\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentSizeEntries,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentStore,\n DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbRemoteDocument,\n LocalSerializer,\n toDbRemoteDocument,\n toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n document: MutableDocument;\n size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n indexManager!: IndexManager;\n\n constructor(readonly serializer: LocalSerializer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(doc);\n }\n\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n ): PersistencePromise {\n const store = remoteDocumentsStore(transaction);\n return store.delete(dbReadTimeKey(documentKey, readTime));\n }\n\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */\n updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let doc = MutableDocument.newInvalidDocument(documentKey);\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n }\n )\n .next(() => doc);\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let result = {\n size: 0,\n document: MutableDocument.newInvalidDocument(documentKey)\n };\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n result = {\n document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n };\n }\n )\n .next(() => result);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n let sizeMap = new SortedMap(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n }\n ).next(() => {\n return { documents: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n let sortedKeys = new SortedSet(dbKeyComparator);\n documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n const range = IDBKeyRange.bound(\n dbKey(sortedKeys.first()!),\n dbKey(sortedKeys.last()!)\n );\n const keyIter = sortedKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate(\n { index: DbRemoteDocumentDocumentKeyIndex, range },\n (_, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments([\n ...dbRemoteDoc.prefixPath,\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n ]);\n\n // Go through keys not found in cache.\n while (nextKey && dbKeyComparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(dbKey(nextKey));\n } else {\n control.done();\n }\n }\n )\n .next(() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap,\n context?: QueryContext\n ): PersistencePromise {\n const collection = query.path;\n const startKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n toDbTimestampKey(offset.readTime),\n offset.documentKey.path.isEmpty()\n ? ''\n : offset.documentKey.path.lastSegment()\n ];\n const endKey: DbRemoteDocumentKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n ''\n ];\n\n return remoteDocumentsStore(transaction)\n .loadAll(IDBKeyRange.bound(startKey, endKey, true))\n .next(dbRemoteDocs => {\n context?.incrementDocumentReadCount(dbRemoteDocs.length);\n let results = mutableDocumentMap();\n for (const dbRemoteDoc of dbRemoteDocs) {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n if (\n document.isFoundDocument() &&\n (queryMatches(query, document) || mutatedDocs.has(document.key))\n ) {\n // Either the document matches the given query, or it is mutated.\n results = results.insert(document.key, document);\n }\n }\n return results;\n });\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limit: number\n ): PersistencePromise {\n debugAssert(limit > 0, 'Limit should be at least 1');\n let results = mutableDocumentMap();\n\n const startKey = dbCollectionGroupKey(collectionGroup, offset);\n const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentCollectionGroupIndex,\n range: IDBKeyRange.bound(startKey, endKey, true)\n },\n (_, dbRemoteDoc, control) => {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n results = results.insert(document.key, document);\n if (results.size === limit) {\n control.done();\n }\n }\n )\n .next(() => results);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobalKey)\n .next(metadata => {\n hardAssert(!!metadata, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata);\n }\n\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n documentKey: DocumentKey,\n dbRemoteDoc: DbRemoteDocument | null\n ): MutableDocument {\n if (dbRemoteDoc) {\n const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n const isSentinelRemoval =\n doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n if (!isSentinelRemoval) {\n return doc;\n }\n }\n return MutableDocument.newInvalidDocument(documentKey);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n return new IndexedDbRemoteDocumentCacheImpl(serializer);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n protected documentStates: ObjectMap<\n DocumentKey,\n { size: number; readTime: SnapshotVersion }\n > = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(\n private readonly documentCache: IndexedDbRemoteDocumentCacheImpl,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, documentChange) => {\n const previousDoc = this.documentStates.get(key);\n debugAssert(\n previousDoc !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n promises.push(\n this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n );\n if (documentChange.isValidDocument()) {\n debugAssert(\n !documentChange.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n const doc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousDoc.size;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousDoc.size;\n if (this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const deletedDoc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange.convertToNoDocument(SnapshotVersion.min())\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n this.documentStates.set(documentKey, {\n size: getResult.size,\n readTime: getResult.document.readTime\n });\n return getResult.document;\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ documents, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentStates.set(documentKey, {\n size,\n readTime: documents.get(documentKey)!.readTime\n });\n });\n return documents;\n });\n }\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentGlobalStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentStore\n );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n toDbTimestampKey(readTime),\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n collectionGroup: string,\n offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n const path = offset.documentKey.path.toArray();\n return [\n /* collection id */ collectionGroup,\n toDbTimestampKey(offset.readTime),\n /* prefix path */ path.slice(0, path.length - 2),\n /* document id */ path.length > 0 ? path[path.length - 1] : ''\n ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n const left = l.path.toArray();\n const right = r.path.toArray();\n\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let cmp = 0;\n for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n cmp = primitiveComparator(left[i], right[i]);\n if (cmp) {\n return cmp;\n }\n }\n\n cmp = primitiveComparator(left.length, right.length);\n if (cmp) {\n return cmp;\n }\n\n cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n if (cmp) {\n return cmp;\n }\n\n return primitiveComparator(left[left.length - 1], right[right.length - 1]);\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 { Document } from '../model/document';\nimport { FieldMask } from '../model/field_mask';\n\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nexport class OverlayedDocument {\n constructor(\n readonly overlayedDocument: Document,\n\n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n readonly mutatedFields: FieldMask | 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 */\n\nimport {\n asCollectionQueryAtPath,\n isCollectionGroupQuery,\n isDocumentQuery,\n Query,\n queryMatches\n} from '../core/query';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n DocumentKeySet,\n OverlayMap,\n DocumentMap,\n MutableDocumentMap,\n newDocumentKeyMap,\n newMutationMap,\n newOverlayMap,\n documentMap,\n mutableDocumentMap,\n documentKeySet,\n DocumentKeyMap,\n convertOverlayedDocumentMapToDocumentMap,\n OverlayedDocumentMap,\n newOverlayedDocumentMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset, INITIAL_LARGEST_BATCH_ID } from '../model/field_index';\nimport { FieldMask } from '../model/field_mask';\nimport {\n calculateOverlayMutation,\n mutationApplyToLocalView,\n PatchMutation\n} from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly documentOverlayCache: DocumentOverlayCache,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n let overlay: Overlay | null = null;\n return this.documentOverlayCache\n .getOverlay(transaction, key)\n .next(value => {\n overlay = value;\n return this.remoteDocumentCache.getEntry(transaction, key);\n })\n .next(document => {\n if (overlay !== null) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n return document as Document;\n });\n }\n\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */\n getDocuments(\n transaction: PersistenceTransaction,\n keys: DocumentKeySet\n ): PersistencePromise {\n return this.remoteDocumentCache\n .getEntries(transaction, keys)\n .next(docs =>\n this.getLocalViewOfDocuments(transaction, docs, documentKeySet()).next(\n () => docs as DocumentMap\n )\n );\n }\n\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */\n getLocalViewOfDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n existenceStateChanged: DocumentKeySet = documentKeySet()\n ): PersistencePromise {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() => {\n return this.computeViews(\n transaction,\n docs,\n overlays,\n existenceStateChanged\n ).next(computeViewsResult => {\n let result = documentMap();\n computeViewsResult.forEach((documentKey, overlayedDocument) => {\n result = result.insert(\n documentKey,\n overlayedDocument.overlayedDocument\n );\n });\n return result;\n });\n });\n }\n\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */\n getOverlayedDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() =>\n this.computeViews(transaction, docs, overlays, documentKeySet())\n );\n }\n\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */\n private populateOverlays(\n transaction: PersistenceTransaction,\n overlays: OverlayMap,\n docs: MutableDocumentMap\n ): PersistencePromise {\n const missingOverlays: DocumentKey[] = [];\n docs.forEach(key => {\n if (!overlays.has(key)) {\n missingOverlays.push(key);\n }\n });\n return this.documentOverlayCache\n .getOverlays(transaction, missingOverlays)\n .next(result => {\n result.forEach((key, val) => {\n overlays.set(key, val);\n });\n });\n }\n\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */\n computeViews(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n overlays: OverlayMap,\n existenceStateChanged: DocumentKeySet\n ): PersistencePromise {\n let recalculateDocuments = mutableDocumentMap();\n const mutatedFields = newDocumentKeyMap();\n const results = newOverlayedDocumentMap();\n docs.forEach((_, doc) => {\n const overlay = overlays.get(doc.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n if (\n existenceStateChanged.has(doc.key) &&\n (overlay === undefined || overlay.mutation instanceof PatchMutation)\n ) {\n recalculateDocuments = recalculateDocuments.insert(doc.key, doc);\n } else if (overlay !== undefined) {\n mutatedFields.set(doc.key, overlay.mutation.getFieldMask());\n mutationApplyToLocalView(\n overlay.mutation,\n doc,\n overlay.mutation.getFieldMask(),\n Timestamp.now()\n );\n } else {\n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n mutatedFields.set(doc.key, FieldMask.empty());\n }\n });\n\n return this.recalculateAndSaveOverlays(\n transaction,\n recalculateDocuments\n ).next(recalculatedFields => {\n recalculatedFields.forEach((documentKey, mask) =>\n mutatedFields.set(documentKey, mask)\n );\n docs.forEach((documentKey, document) =>\n results.set(\n documentKey,\n new OverlayedDocument(\n document,\n mutatedFields.get(documentKey) ?? null\n )\n )\n );\n return results;\n });\n }\n\n private recalculateAndSaveOverlays(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise> {\n const masks = newDocumentKeyMap();\n // A reverse lookup map from batch id to the documents within that batch.\n let documentsByBatchId = new SortedMap(\n (key1: number, key2: number) => key1 - key2\n );\n let processed = documentKeySet();\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKeys(transaction, docs)\n .next(batches => {\n for (const batch of batches) {\n batch.keys().forEach(key => {\n const baseDoc = docs.get(key);\n if (baseDoc === null) {\n return;\n }\n let mask: FieldMask | null = masks.get(key) || FieldMask.empty();\n mask = batch.applyToLocalView(baseDoc, mask);\n masks.set(key, mask);\n const newSet = (\n documentsByBatchId.get(batch.batchId) || documentKeySet()\n ).add(key);\n documentsByBatchId = documentsByBatchId.insert(\n batch.batchId,\n newSet\n );\n });\n }\n })\n .next(() => {\n const promises: Array> = [];\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n const iter = documentsByBatchId.getReverseIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const batchId = entry.key;\n const keys = entry.value;\n const overlays = newMutationMap();\n keys.forEach(key => {\n if (!processed.has(key)) {\n const overlayMutation = calculateOverlayMutation(\n docs.get(key)!,\n masks.get(key)!\n );\n if (overlayMutation !== null) {\n overlays.set(key, overlayMutation);\n }\n processed = processed.add(key);\n }\n });\n promises.push(\n this.documentOverlayCache.saveOverlays(\n transaction,\n batchId,\n overlays\n )\n );\n }\n return PersistencePromise.waitFor(promises);\n })\n .next(() => masks);\n }\n\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */\n recalculateAndSaveOverlaysForDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise> {\n return this.remoteDocumentCache\n .getEntries(transaction, documentKeys)\n .next(docs => this.recalculateAndSaveOverlays(transaction, docs));\n }\n\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n * @param context - A optional tracker to keep a record of important details\n * during database local query execution.\n */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise {\n if (isDocumentQuery(query)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n } else if (isCollectionGroupQuery(query)) {\n return this.getDocumentsMatchingCollectionGroupQuery(\n transaction,\n query,\n offset,\n context\n );\n } else {\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n query,\n offset,\n context\n );\n }\n }\n\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n *

    The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */\n getNextDocuments(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n count: number\n ): PersistencePromise {\n return this.remoteDocumentCache\n .getAllFromCollectionGroup(transaction, collectionGroup, offset, count)\n .next((originalDocs: MutableDocumentMap) => {\n const overlaysPromise: PersistencePromise =\n count - originalDocs.size > 0\n ? this.documentOverlayCache.getOverlaysForCollectionGroup(\n transaction,\n collectionGroup,\n offset.largestBatchId,\n count - originalDocs.size\n )\n : PersistencePromise.resolve(newOverlayMap());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let largestBatchId = INITIAL_LARGEST_BATCH_ID;\n let modifiedDocs = originalDocs;\n return overlaysPromise.next(overlays => {\n return PersistencePromise.forEach(\n overlays,\n (key: DocumentKey, overlay: Overlay) => {\n if (largestBatchId < overlay.largestBatchId) {\n largestBatchId = overlay.largestBatchId;\n }\n if (originalDocs.get(key)) {\n return PersistencePromise.resolve();\n }\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(doc => {\n modifiedDocs = modifiedDocs.insert(key, doc);\n });\n }\n )\n .next(() =>\n this.populateOverlays(transaction, overlays, originalDocs)\n )\n .next(() =>\n this.computeViews(\n transaction,\n modifiedDocs,\n overlays,\n documentKeySet()\n )\n )\n .next(localDocs => ({\n batchId: largestBatchId,\n changes: convertOverlayedDocumentMapToDocumentMap(localDocs)\n }));\n });\n });\n }\n\n private getDocumentsMatchingDocumentQuery(\n transaction: PersistenceTransaction,\n docPath: ResourcePath\n ): PersistencePromise {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(\n document => {\n let result = documentMap();\n if (document.isFoundDocument()) {\n result = result.insert(document.key, document);\n }\n return result;\n }\n );\n }\n\n private getDocumentsMatchingCollectionGroupQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise {\n debugAssert(\n query.path.isEmpty(),\n 'Currently we only support collection group queries at the root.'\n );\n const collectionId = query.collectionGroup!;\n let results = documentMap();\n return this.indexManager\n .getCollectionParents(transaction, collectionId)\n .next(parents => {\n // Perform a collection query against each parent that contains the\n // collectionId and aggregate the results.\n return PersistencePromise.forEach(parents, (parent: ResourcePath) => {\n const collectionQuery = asCollectionQueryAtPath(\n query,\n parent.child(collectionId)\n );\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n collectionQuery,\n offset,\n context\n ).next(r => {\n r.forEach((key, doc) => {\n results = results.insert(key, doc);\n });\n });\n }).next(() => results);\n });\n }\n\n private getDocumentsMatchingCollectionQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise {\n // Query the remote documents and overlay mutations.\n let overlays: OverlayMap;\n return this.documentOverlayCache\n .getOverlaysForCollection(transaction, query.path, offset.largestBatchId)\n .next(result => {\n overlays = result;\n return this.remoteDocumentCache.getDocumentsMatchingQuery(\n transaction,\n query,\n offset,\n overlays,\n context\n );\n })\n .next(remoteDocuments => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n overlays.forEach((_, overlay) => {\n const key = overlay.getKey();\n if (remoteDocuments.get(key) === null) {\n remoteDocuments = remoteDocuments.insert(\n key,\n MutableDocument.newInvalidDocument(key)\n );\n }\n });\n\n // Apply the overlays and match against the query.\n let results = documentMap();\n remoteDocuments.forEach((key, document) => {\n const overlay = overlays.get(key);\n if (overlay !== undefined) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n // Finally, insert the documents that still match the query\n if (queryMatches(query, document)) {\n results = results.insert(key, document);\n }\n });\n return results;\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 { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n NamedQuery as ProtoNamedQuery,\n BundleMetadata as ProtoBundleMetadata\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport {\n fromBundleMetadata,\n fromProtoNamedQuery,\n LocalSerializer\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\nexport class MemoryBundleCache implements BundleCache {\n private bundles = new Map();\n private namedQueries = new Map();\n\n constructor(private serializer: LocalSerializer) {}\n\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return PersistencePromise.resolve(this.bundles.get(bundleId));\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n this.bundles.set(bundleMetadata.id!, fromBundleMetadata(bundleMetadata));\n return PersistencePromise.resolve();\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return PersistencePromise.resolve(this.namedQueries.get(queryName));\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n this.namedQueries.set(query.name!, fromProtoNamedQuery(query));\n return PersistencePromise.resolve();\n }\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 {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */\nexport class MemoryDocumentOverlayCache implements DocumentOverlayCache {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n private overlays = new SortedMap(\n DocumentKey.comparator\n );\n private overlayByBatchId = new Map();\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.resolve(this.overlays.get(key));\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\n const result = newOverlayMap();\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n return this.getOverlay(transaction, key).next(overlay => {\n if (overlay !== null) {\n result.set(key, overlay);\n }\n });\n }).next(() => result);\n }\n\n saveOverlays(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n overlays: MutationMap\n ): PersistencePromise {\n overlays.forEach((_, mutation) => {\n this.saveOverlay(transaction, largestBatchId, mutation);\n });\n return PersistencePromise.resolve();\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const keys = this.overlayByBatchId.get(batchId);\n if (keys !== undefined) {\n keys.forEach(key => (this.overlays = this.overlays.remove(key)));\n this.overlayByBatchId.delete(batchId);\n }\n return PersistencePromise.resolve();\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n\n const immediateChildrenPathLength = collection.length + 1;\n const prefix = new DocumentKey(collection.child(''));\n const iter = this.overlays.getIteratorFrom(prefix);\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (!collection.isPrefixOf(key.path)) {\n break;\n }\n // Documents from sub-collections\n if (key.path.length !== immediateChildrenPathLength) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n result.set(overlay.getKey(), overlay);\n }\n }\n\n return PersistencePromise.resolve(result);\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n let batchIdToOverlays = new SortedMap(\n (key1: number, key2: number) => key1 - key2\n );\n\n const iter = this.overlays.getIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (key.getCollectionGroup() !== collectionGroup) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId);\n if (overlaysForBatchId === null) {\n overlaysForBatchId = newOverlayMap();\n batchIdToOverlays = batchIdToOverlays.insert(\n overlay.largestBatchId,\n overlaysForBatchId\n );\n }\n overlaysForBatchId.set(overlay.getKey(), overlay);\n }\n }\n\n const result = newOverlayMap();\n const batchIter = batchIdToOverlays.getIterator();\n while (batchIter.hasNext()) {\n const entry = batchIter.getNext();\n const overlays = entry.value;\n overlays.forEach((key, overlay) => result.set(key, overlay));\n if (result.size() >= count) {\n break;\n }\n }\n return PersistencePromise.resolve(result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n mutation: Mutation\n ): void {\n // Remove the association of the overlay to its batch id.\n const existing = this.overlays.get(mutation.key);\n if (existing !== null) {\n const newSet = this.overlayByBatchId\n .get(existing.largestBatchId)!\n .delete(mutation.key);\n this.overlayByBatchId.set(existing.largestBatchId, newSet);\n }\n\n this.overlays = this.overlays.insert(\n mutation.key,\n new Overlay(largestBatchId, mutation)\n );\n\n // Create the association of this overlay to the given largestBatchId.\n let batch = this.overlayByBatchId.get(largestBatchId);\n if (batch === undefined) {\n batch = documentKeySet();\n this.overlayByBatchId.set(largestBatchId, batch);\n }\n this.overlayByBatchId.set(largestBatchId, batch.add(mutation.key));\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, TargetId } from '../core/types';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */\nexport class ReferenceSet {\n // A set of outstanding references to a document sorted by key.\n private refsByKey = new SortedSet(DocReference.compareByKey);\n\n // A set of outstanding references to a document sorted by target id.\n private refsByTarget = new SortedSet(DocReference.compareByTargetId);\n\n /** Returns true if the reference set contains no references. */\n isEmpty(): boolean {\n return this.refsByKey.isEmpty();\n }\n\n /** Adds a reference to the given document key for the given ID. */\n addReference(key: DocumentKey, id: TargetId | BatchId): void {\n const ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n }\n\n /** Add references to the given document keys for the given ID. */\n addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.addReference(key, id));\n }\n\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n removeReference(key: DocumentKey, id: TargetId | BatchId): void {\n this.removeRef(new DocReference(key, id));\n }\n\n removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.removeReference(key, id));\n }\n\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n removeReferencesForId(id: TargetId | BatchId): DocumentKey[] {\n const emptyKey = new DocumentKey(new ResourcePath([]));\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n const keys: DocumentKey[] = [];\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n this.removeRef(ref);\n keys.push(ref.key);\n });\n return keys;\n }\n\n removeAllReferences(): void {\n this.refsByKey.forEach(ref => this.removeRef(ref));\n }\n\n private removeRef(ref: DocReference): void {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n }\n\n referencesForId(id: TargetId | BatchId): DocumentKeySet {\n const emptyKey = new DocumentKey(new ResourcePath([]));\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n let keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n keys = keys.add(ref.key);\n });\n return keys;\n }\n\n containsKey(key: DocumentKey): boolean {\n const ref = new DocReference(key, 0);\n const firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return firstRef !== null && key.isEqual(firstRef.key);\n }\n}\n\nexport class DocReference {\n constructor(\n public key: DocumentKey,\n public targetOrBatchId: TargetId | BatchId\n ) {}\n\n /** Compare by key then by ID */\n static compareByKey(left: DocReference, right: DocReference): number {\n return (\n DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId)\n );\n }\n\n /** Compare by ID then by key */\n static compareByTargetId(left: DocReference, right: DocReference): number {\n return (\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.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\nimport { isCollectionGroupQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { DocReference } from './reference_set';\n\nexport class MemoryMutationQueue implements MutationQueue {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n private mutationQueue: MutationBatch[] = [];\n\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n private nextBatchId: BatchId = 1;\n\n /** An ordered mapping between documents and the mutations batch IDs. */\n private batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n\n constructor(\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n debugAssert(mutations.length !== 0, 'Mutation batches should not be empty');\n\n const batchId = this.nextBatchId;\n this.nextBatchId++;\n\n if (this.mutationQueue.length > 0) {\n const prior = this.mutationQueue[this.mutationQueue.length - 1];\n debugAssert(\n prior.batchId < batchId,\n 'Mutation batchIDs must be monotonically increasing order'\n );\n }\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n this.mutationQueue.push(batch);\n\n // Track references by document key and index collection parents.\n for (const mutation of mutations) {\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(\n new DocReference(mutation.key, batchId)\n );\n\n this.indexManager.addToCollectionParentIndex(\n transaction,\n mutation.key.path.popLast()\n );\n }\n\n return PersistencePromise.resolve(batch);\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n const rawIndex = this.indexOfBatchId(nextBatchId);\n const index = rawIndex < 0 ? 0 : rawIndex;\n return PersistencePromise.resolve(\n this.mutationQueue.length > index ? this.mutationQueue[index] : null\n );\n }\n\n getHighestUnacknowledgedBatchId(): PersistencePromise {\n return PersistencePromise.resolve(\n this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1\n );\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n const result: MutationBatch[] = [];\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n debugAssert(\n documentKey.isEqual(ref.key),\n \"Should only iterate over a single key's batches\"\n );\n const batch = this.findMutationBatch(ref.targetOrBatchId);\n debugAssert(\n batch !== null,\n 'Batches in the index must exist in the main table'\n );\n result.push(batch!);\n });\n\n return PersistencePromise.resolve(result);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n documentKeys.forEach(documentKey => {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n debugAssert(\n documentKey.isEqual(ref.key),\n \"For each key, should only iterate over a single key's batches\"\n );\n\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n });\n });\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const prefix = query.path;\n const immediateChildrenPathLength = prefix.length + 1;\n\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n\n const start = new DocReference(new DocumentKey(startPath), 0);\n\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n this.batchesByDocumentKey.forEachWhile(ref => {\n const rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n } else {\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n private findMutationBatches(batchIDs: SortedSet): MutationBatch[] {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const result: MutationBatch[] = [];\n batchIDs.forEach(batchId => {\n const batch = this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return result;\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n // Find the position of the first batch for removal.\n const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n hardAssert(\n batchIndex === 0,\n 'Can only remove the first entry of the mutation queue'\n );\n this.mutationQueue.shift();\n\n let references = this.batchesByDocumentKey;\n return PersistencePromise.forEach(batch.mutations, (mutation: Mutation) => {\n const ref = new DocReference(mutation.key, batch.batchId);\n references = references.delete(ref);\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n mutation.key\n );\n }).next(() => {\n this.batchesByDocumentKey = references;\n });\n }\n\n removeCachedMutationKeys(batchId: BatchId): void {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const ref = new DocReference(key, 0);\n const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.mutationQueue.length === 0) {\n debugAssert(\n this.batchesByDocumentKey.isEmpty(),\n 'Document leak -- detected dangling mutation references when queue is empty.'\n );\n }\n return PersistencePromise.resolve();\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */\n private indexOfExistingBatchId(batchId: BatchId, action: string): number {\n const index = this.indexOfBatchId(batchId);\n debugAssert(\n index >= 0 && index < this.mutationQueue.length,\n 'Batches must exist to be ' + action\n );\n return index;\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */\n private indexOfBatchId(batchId: BatchId): number {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\n\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n const firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n }\n\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */\n private findMutationBatch(batchId: BatchId): MutationBatch | null {\n const index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n\n const batch = this.mutationQueue[index];\n debugAssert(batch.batchId === batchId, 'If found batch must match');\n return batch;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert, fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { IndexManager } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\n\nexport type DocumentSizer = (doc: Document) => number;\n\n/** Miscellaneous collection types / constants. */\ninterface MemoryRemoteDocumentCacheEntry {\n document: Document;\n size: number;\n}\n\ntype DocumentEntryMap = SortedMap;\nfunction documentEntryMap(): DocumentEntryMap {\n return new SortedMap(\n DocumentKey.comparator\n );\n}\n\nexport interface MemoryRemoteDocumentCache extends RemoteDocumentCache {\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise\n ): PersistencePromise;\n}\n\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass MemoryRemoteDocumentCacheImpl implements MemoryRemoteDocumentCache {\n /** Underlying cache of documents and their read times. */\n private docs = documentEntryMap();\n private indexManager!: IndexManager;\n\n /** Size of all cached documents. */\n private size = 0;\n\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(private readonly sizer: DocumentSizer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n addEntry(\n transaction: PersistenceTransaction,\n doc: MutableDocument\n ): PersistencePromise {\n debugAssert(\n !doc.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n\n const key = doc.key;\n const entry = this.docs.get(key);\n const previousSize = entry ? entry.size : 0;\n const currentSize = this.sizer(doc);\n\n this.docs = this.docs.insert(key, {\n document: doc.mutableCopy(),\n size: currentSize\n });\n\n this.size += currentSize - previousSize;\n\n return this.indexManager.addToCollectionParentIndex(\n transaction,\n key.path.popLast()\n );\n }\n\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n removeEntry(documentKey: DocumentKey): void {\n const entry = this.docs.get(documentKey);\n if (entry) {\n this.docs = this.docs.remove(documentKey);\n this.size -= entry.size;\n }\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n const entry = this.docs.get(documentKey);\n return PersistencePromise.resolve(\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n documentKeys.forEach(documentKey => {\n const entry = this.docs.get(documentKey);\n results = results.insert(\n documentKey,\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n });\n return PersistencePromise.resolve(results);\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap\n ): PersistencePromise {\n let results = mutableDocumentMap();\n\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const collectionPath = query.path;\n const prefix = new DocumentKey(collectionPath.child(''));\n const iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n const {\n key,\n value: { document }\n } = iterator.getNext();\n if (!collectionPath.isPrefixOf(key.path)) {\n break;\n }\n if (key.path.length > collectionPath.length + 1) {\n // Exclude entries from subcollections.\n continue;\n }\n if (\n indexOffsetComparator(newIndexOffsetFromDocument(document), offset) <= 0\n ) {\n // The document sorts before the offset.\n continue;\n }\n if (!mutatedDocs.has(document.key) && !queryMatches(query, document)) {\n // The document cannot possibly match the query.\n continue;\n }\n\n results = results.insert(document.key, document.mutableCopy());\n }\n return PersistencePromise.resolve(results);\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limti: number\n ): PersistencePromise {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n fail('getAllFromCollectionGroup() is not supported.');\n }\n\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise\n ): PersistencePromise {\n return PersistencePromise.forEach(this.docs, (key: DocumentKey) => f(key));\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new MemoryRemoteDocumentChangeBuffer(this);\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return PersistencePromise.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\nexport function newMemoryRemoteDocumentCache(\n sizer: DocumentSizer\n): MemoryRemoteDocumentCache {\n return new MemoryRemoteDocumentCacheImpl(sizer);\n}\n\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n constructor(private readonly documentCache: MemoryRemoteDocumentCacheImpl) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n this.changes.forEach((key, doc) => {\n if (doc.isValidDocument()) {\n promises.push(this.documentCache.addEntry(transaction, doc));\n } else {\n this.documentCache.removeEntry(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n return this.documentCache.getEntry(transaction, documentKey);\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n return this.documentCache.getEntries(transaction, documentKeys);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class MemoryTargetCache implements TargetCache {\n /**\n * Maps a target to the data about that target\n */\n private targets = new ObjectMap(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /** The last received snapshot version. */\n private lastRemoteSnapshotVersion = SnapshotVersion.min();\n /** The highest numbered target ID encountered. */\n private highestTargetId: TargetId = 0;\n /** The highest sequence number encountered. */\n private highestSequenceNumber: ListenSequenceNumber = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n private references = new ReferenceSet();\n\n private targetCount = 0;\n\n private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n constructor(private readonly persistence: Persistence) {}\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n this.targets.forEach((_, targetData) => f(targetData));\n return PersistencePromise.resolve();\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.highestSequenceNumber);\n }\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n this.highestTargetId = this.targetIdGenerator.next();\n return PersistencePromise.resolve(this.highestTargetId);\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n if (lastRemoteSnapshotVersion) {\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n if (highestListenSequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = highestListenSequenceNumber;\n }\n return PersistencePromise.resolve();\n }\n\n private saveTargetData(targetData: TargetData): void {\n this.targets.set(targetData.target, targetData);\n const targetId = targetData.targetId;\n if (targetId > this.highestTargetId) {\n this.targetIdGenerator = new TargetIdGenerator(targetId);\n this.highestTargetId = targetId;\n }\n if (targetData.sequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = targetData.sequenceNumber;\n }\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n debugAssert(\n !this.targets.has(targetData.target),\n 'Adding a target that already exists'\n );\n this.saveTargetData(targetData);\n this.targetCount += 1;\n return PersistencePromise.resolve();\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n debugAssert(\n this.targets.has(targetData.target),\n 'Updating a non-existent target'\n );\n this.saveTargetData(targetData);\n return PersistencePromise.resolve();\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n debugAssert(this.targetCount > 0, 'Removing a target from an empty cache');\n debugAssert(\n this.targets.has(targetData.target),\n 'Removing a non-existent target from the cache'\n );\n this.targets.delete(targetData.target);\n this.references.removeReferencesForId(targetData.targetId);\n this.targetCount -= 1;\n return PersistencePromise.resolve();\n }\n\n removeTargets(\n transaction: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const removals: Array> = [];\n this.targets.forEach((key, targetData) => {\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n this.targets.delete(key);\n removals.push(\n this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n );\n count++;\n }\n });\n return PersistencePromise.waitFor(removals).next(() => count);\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.targetCount);\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n const targetData = this.targets.get(target) || null;\n return PersistencePromise.resolve(targetData);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n this.references.addReferences(keys, targetId);\n return PersistencePromise.resolve();\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n this.references.removeReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array> = [];\n if (referenceDelegate) {\n keys.forEach(key => {\n promises.push(referenceDelegate.markPotentiallyOrphaned(txn, key));\n });\n }\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.resolve(this.references.containsKey(key));\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { estimateByteSize } from '../model/values';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { fail } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { LocalSerializer } from './local_serializer';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { MemoryBundleCache } from './memory_bundle_cache';\nimport { MemoryDocumentOverlayCache } from './memory_document_overlay_cache';\nimport { MemoryIndexManager } from './memory_index_manager';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport {\n MemoryRemoteDocumentCache,\n newMemoryRemoteDocumentCache\n} from './memory_remote_document_cache';\nimport { MemoryTargetCache } from './memory_target_cache';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode\n} from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetData } from './target_data';\n\nconst LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nexport class MemoryPersistence implements Persistence {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n private readonly indexManager: MemoryIndexManager;\n private mutationQueues: { [user: string]: MemoryMutationQueue } = {};\n private overlays: { [user: string]: MemoryDocumentOverlayCache } = {};\n private readonly remoteDocumentCache: MemoryRemoteDocumentCache;\n private readonly targetCache: MemoryTargetCache;\n private readonly bundleCache: MemoryBundleCache;\n private readonly listenSequence = new ListenSequence(0);\n private serializer: LocalSerializer;\n\n private _started = false;\n\n readonly referenceDelegate: MemoryReferenceDelegate;\n\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(\n referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate,\n serializer: JsonProtoSerializer\n ) {\n this._started = true;\n this.referenceDelegate = referenceDelegateFactory(this);\n this.targetCache = new MemoryTargetCache(this);\n const sizer = (doc: Document): number =>\n this.referenceDelegate.documentSize(doc);\n this.indexManager = new MemoryIndexManager();\n this.remoteDocumentCache = newMemoryRemoteDocumentCache(sizer);\n this.serializer = new LocalSerializer(serializer);\n this.bundleCache = new MemoryBundleCache(this.serializer);\n }\n\n start(): Promise {\n return Promise.resolve();\n }\n\n shutdown(): Promise {\n // No durable state to ensure is closed on shutdown.\n this._started = false;\n return Promise.resolve();\n }\n\n get started(): boolean {\n return this._started;\n }\n\n setDatabaseDeletedListener(): void {\n // No op.\n }\n\n setNetworkEnabled(): void {\n // No op.\n }\n\n getIndexManager(user: User): MemoryIndexManager {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n let overlay = this.overlays[user.toKey()];\n if (!overlay) {\n overlay = new MemoryDocumentOverlayCache();\n this.overlays[user.toKey()] = overlay;\n }\n return overlay;\n }\n\n getMutationQueue(user: User, indexManager: IndexManager): MutationQueue {\n let queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue(indexManager, this.referenceDelegate);\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n }\n\n getTargetCache(): MemoryTargetCache {\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): MemoryRemoteDocumentCache {\n return this.remoteDocumentCache;\n }\n\n getBundleCache(): MemoryBundleCache {\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n const txn = new MemoryTransaction(this.listenSequence.next());\n this.referenceDelegate.onTransactionStarted();\n return transactionOperation(txn)\n .next(result => {\n return this.referenceDelegate\n .onTransactionCommitted(txn)\n .next(() => result);\n })\n .toPromise()\n .then(result => {\n txn.raiseOnCommittedEvent();\n return result;\n });\n }\n\n mutationQueuesContainKey(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.or(\n Object.values(this.mutationQueues).map(\n queue => () => queue.containsKey(transaction, key)\n )\n );\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */\nexport class MemoryTransaction extends PersistenceTransaction {\n constructor(readonly currentSequenceNumber: ListenSequenceNumber) {\n super();\n }\n}\n\nexport interface MemoryReferenceDelegate extends ReferenceDelegate {\n documentSize(doc: Document): number;\n onTransactionStarted(): void;\n onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise;\n}\n\nexport class MemoryEagerDelegate implements MemoryReferenceDelegate {\n /** Tracks all documents that are active in Query views. */\n private localViewReferences: ReferenceSet = new ReferenceSet();\n /** The list of documents that are potentially GCed after each transaction. */\n private _orphanedDocuments: Set | null = null;\n\n private constructor(private readonly persistence: MemoryPersistence) {}\n\n static factory(persistence: MemoryPersistence): MemoryEagerDelegate {\n return new MemoryEagerDelegate(persistence);\n }\n\n private get orphanedDocuments(): Set {\n if (!this._orphanedDocuments) {\n throw fail('orphanedDocuments is only valid during a transaction.');\n } else {\n return this._orphanedDocuments;\n }\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n this.localViewReferences.addReference(key, targetId);\n this.orphanedDocuments.delete(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n this.localViewReferences.removeReference(key, targetId);\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const orphaned = this.localViewReferences.removeReferencesForId(\n targetData.targetId\n );\n orphaned.forEach(key => this.orphanedDocuments.add(key.toString()));\n const cache = this.persistence.getTargetCache();\n return cache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(keys => {\n keys.forEach(key => this.orphanedDocuments.add(key.toString()));\n })\n .next(() => cache.removeTargetData(txn, targetData));\n }\n\n onTransactionStarted(): void {\n this._orphanedDocuments = new Set();\n }\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise {\n // Remove newly orphaned documents.\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n return PersistencePromise.forEach(\n this.orphanedDocuments,\n (path: string) => {\n const key = DocumentKey.fromPath(path);\n return this.isReferenced(txn, key).next(isReferenced => {\n if (!isReferenced) {\n changeBuffer.removeEntry(key, SnapshotVersion.min());\n }\n });\n }\n ).next(() => {\n this._orphanedDocuments = null;\n return changeBuffer.apply(txn);\n });\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return this.isReferenced(txn, key).next(isReferenced => {\n if (isReferenced) {\n this.orphanedDocuments.delete(key.toString());\n } else {\n this.orphanedDocuments.add(key.toString());\n }\n });\n }\n\n documentSize(doc: Document): number {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n\n private isReferenced(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.or([\n () =>\n PersistencePromise.resolve(this.localViewReferences.containsKey(key)),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => this.persistence.mutationQueuesContainKey(txn, key)\n ]);\n }\n}\n\nexport class MemoryLruDelegate implements ReferenceDelegate, LruDelegate {\n private orphanedSequenceNumbers: ObjectMap<\n DocumentKey,\n ListenSequenceNumber\n > = new ObjectMap(\n k => encodeResourcePath(k.path),\n (l, r) => l.isEqual(r)\n );\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(\n private readonly persistence: MemoryPersistence,\n lruParams: LruParams\n ) {\n this.garbageCollector = newLruGarbageCollector(this, lruParams);\n }\n\n static factory(\n persistence: MemoryPersistence,\n lruParams: LruParams\n ): MemoryLruDelegate {\n return new MemoryLruDelegate(persistence, lruParams);\n }\n\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n onTransactionStarted(): void {}\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve();\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.persistence.getTargetCache().forEachTarget(txn, f);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.persistence\n .getTargetCache()\n .getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return PersistencePromise.forEach(\n this.orphanedSequenceNumbers,\n (key, sequenceNumber) => {\n // Pass in the exact sequence number as the upper bound so we know it won't be pinned by\n // being too recent.\n return this.isPinned(txn, key, sequenceNumber).next(isPinned => {\n if (!isPinned) {\n return f(sequenceNumber);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n );\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.persistence\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n let count = 0;\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n const p = cache.forEachDocumentKey(txn, key => {\n return this.isPinned(txn, key, upperBound).next(isPinned => {\n if (!isPinned) {\n count++;\n changeBuffer.removeEntry(key, SnapshotVersion.min());\n }\n });\n });\n return p.next(() => changeBuffer.apply(txn)).next(() => count);\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(txn, updated);\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n documentSize(document: Document): number {\n let documentSize = document.key.toString().length;\n if (document.isFoundDocument()) {\n documentSize += estimateByteSize(document.data.value);\n }\n return documentSize;\n }\n\n private isPinned(\n txn: PersistenceTransaction,\n key: DocumentKey,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return PersistencePromise.or([\n () => this.persistence.mutationQueuesContainKey(txn, key),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => {\n const orphanedAt = this.orphanedSequenceNumbers.get(key);\n return PersistencePromise.resolve(\n orphanedAt !== undefined && orphanedAt > upperBound\n );\n }\n ]);\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.persistence.getRemoteDocumentCache().getSize(txn);\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 { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport {\n dbDocumentSize,\n removeMutationBatch\n} from './indexeddb_mutation_batch_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { newIndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n DbCollectionParent,\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue,\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbTarget,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport {\n DbRemoteDocument as DbRemoteDocumentLegacy,\n DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy,\n DbRemoteDocumentKey as DbRemoteDocumentKeyLegacy\n} from './indexeddb_schema_legacy';\nimport {\n DbBundleKeyPath,\n DbBundleStore,\n DbClientMetadataKeyPath,\n DbClientMetadataStore,\n DbCollectionParentKey,\n DbCollectionParentKeyPath,\n DbCollectionParentStore,\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n DbDocumentOverlayKeyPath,\n DbDocumentOverlayStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n DbIndexConfigurationKeyPath,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n DbIndexEntryKeyPath,\n DbIndexEntryStore,\n DbIndexStateKeyPath,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n DbIndexStateStore,\n DbMutationBatchKey,\n DbMutationBatchKeyPath,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n DbMutationQueueKey,\n DbMutationQueueKeyPath,\n DbMutationQueueStore,\n DbNamedQueryKeyPath,\n DbNamedQueryStore,\n DbPrimaryClientStore,\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentKeyPath,\n DbRemoteDocumentStore,\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n DbTargetDocumentKey,\n DbTargetDocumentKeyPath,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetKeyPath,\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalDocumentsView } from './local_documents_view';\nimport {\n fromDbMutationBatch,\n fromDbTarget,\n LocalSerializer,\n toDbTarget\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { MemoryEagerDelegate, MemoryPersistence } from './memory_persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\n\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise {\n debugAssert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createLegacyRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.next(() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n dropRemoteDocumentChangesStore(db);\n\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n });\n }\n\n if (fromVersion < 10 && toVersion >= 10) {\n p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n }\n\n if (fromVersion < 11 && toVersion >= 11) {\n p = p.next(() => {\n createBundlesStore(db);\n createNamedQueriesStore(db);\n });\n }\n\n if (fromVersion < 12 && toVersion >= 12) {\n p = p.next(() => {\n createDocumentOverlayStore(db);\n });\n }\n\n if (fromVersion < 13 && toVersion >= 13) {\n p = p\n .next(() => createRemoteDocumentCache(db))\n .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n }\n\n if (fromVersion < 14 && toVersion >= 14) {\n p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n }\n\n if (fromVersion < 15 && toVersion >= 15) {\n p = p.next(() => createFieldIndex(db));\n }\n\n if (fromVersion < 16 && toVersion >= 16) {\n // Clear the object stores to remove possibly corrupted index entries\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n let byteSize = 0;\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate((_, doc) => {\n byteSize += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata: DbRemoteDocumentGlobal = { byteSize };\n return txn\n .store(\n DbRemoteDocumentGlobalStore\n )\n .put(DbRemoteDocumentGlobalKey, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const queuesStore = txn.store(\n DbMutationQueueStore\n );\n const mutationsStore = txn.store(\n DbMutationBatchStore\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n hardAssert(\n dbBatch.userId === queue.userId,\n `Cannot process batch ${dbBatch.batchId} from unexpected user`\n );\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(\n () => {}\n );\n }\n );\n });\n });\n });\n }\n\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocumentStore);\n const documentsStore = txn.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentKeyLegacy\n >(DbRemoteDocumentStoreLegacy);\n const globalTargetStore = txn.store(\n DbTargetGlobalStore\n );\n\n return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n debugAssert(\n !!metadata,\n 'Metadata should have been written during the version 3 migration'\n );\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise => {\n return documentTargetStore.put({\n targetId: 0,\n path: encodeResourcePath(path),\n sequenceNumber: metadata!.highestListenSequenceNumber!\n });\n };\n\n const promises: Array> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise {\n // Create the index.\n db.createObjectStore(DbCollectionParentStore, {\n keyPath: DbCollectionParentKeyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParentStore);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encodeResourcePath(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store(\n DbDocumentMutationStore\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decodeResourcePath(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n\n private rewriteCanonicalIds(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const targetStore = txn.store(DbTargetStore);\n return targetStore.iterate((key, originalDbTarget) => {\n const originalTargetData = fromDbTarget(originalDbTarget);\n const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n return targetStore.put(updatedDbTarget);\n });\n }\n\n private rewriteRemoteDocumentCache(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const legacyRemoteDocumentStore = transaction.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentLegacy\n >(DbRemoteDocumentStoreLegacy);\n\n const writes: Array> = [];\n return legacyRemoteDocumentStore\n .iterate((_, legacyDocument) => {\n const remoteDocumentStore = transaction.store<\n DbRemoteDocumentKey,\n DbRemoteDocument\n >(DbRemoteDocumentStore);\n\n const path = extractKey(legacyDocument).path.toArray();\n const dbRemoteDocument = {\n prefixPath: path.slice(0, path.length - 2),\n collectionGroup: path[path.length - 2],\n documentId: path[path.length - 1],\n readTime: legacyDocument.readTime || [0, 0],\n unknownDocument: legacyDocument.unknownDocument,\n noDocument: legacyDocument.noDocument,\n document: legacyDocument.document,\n hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n };\n writes.push(remoteDocumentStore.put(dbRemoteDocument));\n })\n .next(() => PersistencePromise.waitFor(writes));\n }\n\n private runOverlayMigration(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const mutationsStore = transaction.store<\n DbMutationBatchKey,\n DbMutationBatch\n >(DbMutationBatchStore);\n\n const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n this.serializer\n );\n const memoryPersistence = new MemoryPersistence(\n MemoryEagerDelegate.factory,\n this.serializer.remoteSerializer\n );\n\n return mutationsStore.loadAll().next(dbBatches => {\n const userToDocumentSet = new Map();\n dbBatches.forEach(dbBatch => {\n let documentSet =\n userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n userToDocumentSet.set(dbBatch.userId, documentSet);\n });\n return PersistencePromise.forEach(\n userToDocumentSet,\n (allDocumentKeysForUser, userId) => {\n const user = new User(userId);\n const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n this.serializer,\n user\n );\n // NOTE: The index manager and the reference delegate are\n // irrelevant for the purpose of recalculating and saving\n // overlays. We can therefore simply use the memory\n // implementation.\n const indexManager = memoryPersistence.getIndexManager(user);\n const mutationQueue = IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n memoryPersistence.referenceDelegate\n );\n const localDocumentsView = new LocalDocumentsView(\n remoteDocumentCache,\n mutationQueue,\n documentOverlayCache,\n indexManager\n );\n return localDocumentsView\n .recalculateAndSaveOverlaysForDocumentKeys(\n new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n allDocumentKeysForUser\n )\n .next();\n }\n );\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueueStore, {\n keyPath: DbMutationQueueKeyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutationStore);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatchStore\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatchStore);\n\n const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store(\n DbMutationBatchStore\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n keyPath: DbRemoteDocumentKeyPath\n });\n remoteDocumentStore.createIndex(\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath\n );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n keyPath: DbTargetDocumentKeyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTargetStore, {\n keyPath: DbTargetKeyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocumentStore);\n db.deleteObjectStore(DbTargetStore);\n db.deleteObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise {\n const globalStore = txn.store(\n DbTargetGlobalStore\n );\n const metadata: DbTargetGlobal = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadataStore, {\n keyPath: DbClientMetadataKeyPath\n });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n db.createObjectStore(DbBundleStore, {\n keyPath: DbBundleKeyPath\n });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n db.createObjectStore(DbNamedQueryStore, {\n keyPath: DbNamedQueryKeyPath\n });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n const indexConfigurationStore = db.createObjectStore(\n DbIndexConfigurationStore,\n {\n keyPath: DbIndexConfigurationKeyPath,\n autoIncrement: true\n }\n );\n indexConfigurationStore.createIndex(\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n { unique: false }\n );\n\n const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n keyPath: DbIndexStateKeyPath\n });\n indexStateStore.createIndex(\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n { unique: false }\n );\n\n const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n keyPath: DbIndexEntryKeyPath\n });\n indexEntryStore.createIndex(\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n { unique: false }\n );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n keyPath: DbDocumentOverlayKeyPath\n });\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n { unique: false }\n );\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n { unique: false }\n );\n}\n\nfunction extractKey(remoteDoc: DbRemoteDocumentLegacy): DocumentKey {\n if (remoteDoc.document) {\n return new DocumentKey(\n ResourcePath.fromString(remoteDoc.document.name!).popFirst(5)\n );\n } else if (remoteDoc.noDocument) {\n return DocumentKey.fromSegments(remoteDoc.noDocument.path);\n } else if (remoteDoc.unknownDocument) {\n return DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafari } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { DatabaseId } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { DocumentLike, WindowLike } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbBundleCache } from './indexeddb_bundle_cache';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport {\n IndexedDbRemoteDocumentCache,\n newIndexedDbRemoteDocumentCache\n} from './indexeddb_remote_document_cache';\nimport {\n DbClientMetadata,\n DbPrimaryClient,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport { SchemaConverter } from './indexeddb_schema_converter';\nimport {\n DbClientMetadataKey,\n DbClientMetadataStore,\n DbPrimaryClientKey,\n DbPrimaryClientStore,\n getObjectStores\n} from './indexeddb_sentinels';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { getStore, IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalSerializer } from './local_serializer';\nimport { LruParams } from './lru_garbage_collector';\nimport { Persistence, PrimaryStateListener } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence_transaction';\nimport { ClientId } from './shared_client_state';\nimport {\n isIndexedDbTransactionError,\n SimpleDb,\n SimpleDbStore\n} from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Failed to obtain exclusive access to the persistence layer. To allow ' +\n 'shared access, multi-tab synchronization has to be enabled in all tabs. ' +\n 'If you are using `experimentalForceOwningTab:true`, make sure that only ' +\n 'one tab has persistence enabled at any given time.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing IndexedDB or is known to have ' +\n 'an incomplete implementation. Offline persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie__\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\n/**\n * The name of the main (and currently only) IndexedDB database. This name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\nexport const MAIN_DATABASE = 'main';\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nexport class IndexedDbPersistence implements Persistence {\n private simpleDb: SimpleDb;\n\n private listenSequence: ListenSequence | null = null;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: DelayedOperation | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly targetCache: IndexedDbTargetCache;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly bundleCache: IndexedDbBundleCache;\n private readonly webStorage: Storage | null;\n readonly referenceDelegate: IndexedDbLruDelegateImpl;\n\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n private readonly allowTabSynchronization: boolean,\n\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n private readonly window: WindowLike | null,\n private readonly document: DocumentLike | null,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer,\n\n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n private readonly forceOwningTab: boolean,\n private readonly schemaVersion = SCHEMA_VERSION\n ) {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);\n this.dbName = persistenceKey + MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.simpleDb = new SimpleDb(\n this.dbName,\n this.schemaVersion,\n new SchemaConverter(this.serializer)\n );\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);\n this.bundleCache = new IndexedDbBundleCache();\n if (this.window && this.window.localStorage) {\n this.webStorage = this.window.localStorage;\n } else {\n this.webStorage = null;\n if (forceOwningTab === false) {\n logError(\n LOG_TAG,\n 'LocalStorage is unavailable. As a result, persistence may not work ' +\n 'reliably. In particular enablePersistence() could fail immediately ' +\n 'after refreshing the page.'\n );\n }\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */\n start(): Promise {\n debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => {\n if (!this.isPrimary && !this.allowTabSynchronization) {\n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.runTransaction(\n 'getHighestListenSequenceNumber',\n 'readonly',\n txn => this.targetCache.getHighestSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\n }\n\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */\n private updateClientMetadataAndTryBecomePrimary(): Promise {\n return this.runTransaction(\n 'updateClientMetadataAndTryBecomePrimary',\n 'readwrite',\n txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n })\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n }\n )\n .catch(e => {\n if (isIndexedDbTransactionError(e)) {\n logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return this.isPrimary;\n }\n\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n logDebug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = getStore(\n txn,\n DbClientMetadataStore\n );\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.webStorage) {\n for (const inactiveClient of inactiveClients) {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n }\n }\n }\n }\n\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\n\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */\n private canActAsPrimary(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.forceOwningTab) {\n return PersistencePromise.resolve(true);\n }\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClientKey)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n logDebug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n\n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.simpleDb.runTransaction(\n 'shutdown',\n 'readwrite',\n [DbPrimaryClientStore, DbClientMetadataStore],\n simpleDbTxn => {\n const persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n ListenSequence.INVALID\n );\n return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n this.removeClientMetadata(persistenceTransaction)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n getActiveClients(): Promise {\n return this.runTransaction('getActiveClients', 'readonly', txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n });\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getMutationQueue(\n user: User,\n indexManager: IndexManager\n ): IndexedDbMutationQueue {\n debugAssert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n debugAssert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n debugAssert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(user: User): IndexManager {\n debugAssert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return new IndexedDbIndexManager(\n user,\n this.serializer.remoteSerializer.databaseId\n );\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n debugAssert(\n this.started,\n 'Cannot initialize IndexedDbDocumentOverlayCache before persistence is started.'\n );\n return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);\n }\n\n getBundleCache(): BundleCache {\n debugAssert(\n this.started,\n 'Cannot initialize BundleCache before persistence is started.'\n );\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n const objectStores = getObjectStores(this.schemaVersion);\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence\n ? this.listenSequence.next()\n : ListenSequence.INVALID\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(persistenceTransaction)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(persistenceTransaction);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n logError(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(\n persistenceTransaction\n ).next(() => result);\n });\n } else {\n return this.verifyAllowTabSynchronization(\n persistenceTransaction\n ).next(() => transactionOperation(persistenceTransaction));\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\n\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n private verifyAllowTabSynchronization(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (\n !this.forceOwningTab &&\n (!this.allowTabSynchronization ||\n !currentPrimary!.allowTabSynchronization)\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\n }\n\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */\n private acquireOrExtendPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const newPrimary: DbPrimaryClient = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n logDebug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClientKey);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n logError(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n debugAssert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\n\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */\n private attachWindowUnloadHook(): void {\n if (typeof this.window?.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.markClientZombied();\n\n const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n if (\n isSafari() &&\n (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n navigator.userAgent.match(safariIndexdbBugVersionRegex))\n ) {\n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n }\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('pagehide', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n debugAssert(\n typeof this.window?.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window!.removeEventListener('pagehide', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\n\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage?.getItem(\n this.zombiedClientLocalStorageKey(clientId)\n ) !== null;\n logDebug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n logError(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\n }\n\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */\n private markClientZombied(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n logError('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbPrimaryClientStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbClientMetadataStore\n );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n databaseId: DatabaseId,\n persistenceKey: string\n): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseId.projectId;\n if (!databaseId.isDefaultDatabase) {\n database += '.' + databaseId.database;\n }\n\n return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n persistenceKey: string\n): Promise {\n if (!SimpleDb.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { IndexKind } from '../model/field_index';\nimport { BundledQuery } from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n DocumentsTarget as ProtoDocumentsTarget,\n QueryTarget as ProtoQueryTarget,\n Write as ProtoWrite\n} from '../protos/firestore_proto_api';\n\nimport { EncodedResourcePath } from './encoded_resource_path';\nimport { DbTimestampKey } from './indexeddb_sentinels';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n * 16. Parse timestamp strings before creating index entries.\n */\n\nexport const SCHEMA_VERSION = 16;\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport interface DbTimestamp {\n seconds: number;\n nanoseconds: number;\n}\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport interface DbPrimaryClient {\n ownerId: string;\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization: boolean;\n leaseTimestampMs: number;\n}\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport interface DbMutationQueue {\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId: string;\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastAcknowledgedBatchId: number;\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastStreamToken: string;\n}\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport interface DbMutationBatch {\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId: string;\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n batchId: BatchId;\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs: number;\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n baseMutations?: ProtoWrite[];\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */\n mutations: ProtoWrite[];\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport interface DbDocumentMutation {}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbNoDocument {\n path: string[];\n readTime: DbTimestamp;\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbUnknownDocument {\n path: string[];\n version: DbTimestamp;\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * The document key is split up across `prefixPath`, `collectionGroup` and\n * `documentId`.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport interface DbRemoteDocument {\n /** The path to the document's collection (excluding). */\n prefixPath: string[];\n\n /** The collection ID the document is direclty nested under. */\n collectionGroup: string;\n\n /** The document ID. */\n documentId: string;\n\n /** When the document was read from the backend. */\n readTime: DbTimestampKey;\n\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n unknownDocument?: DbUnknownDocument;\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument?: DbNoDocument;\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document?: ProtoDocument;\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n hasCommittedMutations: boolean;\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport interface DbRemoteDocumentGlobal {\n /**\n * Approximately the total size in bytes of all the\n * documents in the document cache.\n */\n byteSize: number;\n}\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport interface DbTarget {\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId: TargetId;\n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId: string;\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime: DbTimestamp;\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken: string;\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber: number;\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n lastLimboFreeSnapshotVersion?: DbTimestamp;\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query: DbQuery;\n}\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport interface DbTargetDocument {\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n targetId: TargetId;\n /**\n * The path to the document, as encoded in the key.\n */\n path: EncodedResourcePath;\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n sequenceNumber?: ListenSequenceNumber;\n}\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport interface DbTargetGlobal {\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId: TargetId;\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber: number;\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion: DbTimestamp;\n /**\n * The number of targets persisted.\n */\n targetCount: number;\n}\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport interface DbCollectionParent {\n /**\n * The collectionId (e.g. 'messages')\n */\n collectionId: string;\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n parent: EncodedResourcePath;\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport interface DbClientMetadata {\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n clientId: string;\n /** The last time this state was updated. */\n updateTimeMs: number;\n /** Whether the client's network connection is enabled. */\n networkEnabled: boolean;\n /** Whether this client is running in a foreground tab. */\n inForeground: boolean;\n}\n\n/** An object representing a bundle loaded by the SDK. */\nexport interface DbBundle {\n /** The ID of the loaded bundle. */\n bundleId: string;\n /** The create time of the loaded bundle. */\n createTime: DbTimestamp;\n /** The schema version of the loaded bundle. */\n version: number;\n}\n\n/** An object representing a named query loaded by the SDK via a bundle. */\nexport interface DbNamedQuery {\n /** The name of the query. */\n name: string;\n /** The read time of the results saved in the bundle from the named query. */\n readTime: DbTimestamp;\n /** The query saved in the bundle. */\n bundledQuery: BundledQuery;\n}\n\n/** An object representing the global configuration for a field index. */\nexport interface DbIndexConfiguration {\n /**\n * The index id for this entry. Undefined for indexes that are not yet\n * persisted.\n */\n indexId?: number;\n /** The collection group this index belongs to. */\n collectionGroup: string;\n /** The fields to index for this index. */\n fields: Array<[name: string, kind: IndexKind]>;\n}\n\n/**\n * An object describing how up-to-date the index backfill is for each user and\n * index.\n */\nexport interface DbIndexState {\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /**\n * A number that indicates when the index was last updated (relative to\n * other indexes).\n */\n sequenceNumber: number;\n /**\n * The latest read time that has been indexed by Firestore for this field\n * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed.\n */\n readTime: DbTimestamp;\n /**\n * The last document that has been indexed for this field index. Empty if\n * no documents have been indexed.\n */\n documentKey: EncodedResourcePath;\n /**\n * The largest mutation batch id that has been processed for this index. -1\n * if no mutations have been indexed.\n */\n largestBatchId: number;\n}\n\n/** An object that stores the encoded entries for all documents and fields. */\nexport interface DbIndexEntry {\n // TODO(indexing): Consider just storing `orderedDocumentKey` and decoding\n // the ordered key into a document key. This would reduce storage space on\n // disk but require us to port parts of OrderedCodeReader.\n\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /** The encoded array index value for this entry. */\n arrayValue: Uint8Array;\n /** The encoded directional value for equality and inequality filters. */\n directionalValue: Uint8Array;\n /**\n * The document key this entry points to. This entry is encoded by an ordered\n * encoder to match the key order of the index.\n */\n orderedDocumentKey: Uint8Array;\n /** The segments of the document key this entry points to. */\n documentKey: string[];\n}\n\n/**\n * An object representing a document overlay.\n */\nexport interface DbDocumentOverlay {\n /** The user ID to whom this overlay belongs. */\n userId: string;\n /** The path to the collection that contains the document. */\n collectionPath: string;\n /** The ID (key) of the document within the collection. */\n documentId: string;\n /** The collection group to which the document belongs. */\n collectionGroup: string;\n /** The largest batch ID that's been applied for this overlay. */\n largestBatchId: number;\n /** The overlay mutation. */\n overlayMutation: ProtoWrite;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from '../core/types';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\n\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nexport class LocalViewChanges {\n constructor(\n readonly targetId: TargetId,\n readonly fromCache: boolean,\n readonly addedKeys: DocumentKeySet,\n readonly removedKeys: DocumentKeySet\n ) {}\n\n static fromSnapshot(\n targetId: TargetId,\n viewSnapshot: ViewSnapshot\n ): LocalViewChanges {\n let addedKeys = documentKeySet();\n let removedKeys = documentKeySet();\n\n for (const docChange of viewSnapshot.docChanges) {\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n // do nothing\n }\n }\n\n return new LocalViewChanges(\n targetId,\n viewSnapshot.fromCache,\n addedKeys,\n removedKeys\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\n/**\n * A tracker to keep a record of important details during database local query\n * execution.\n */\nexport class QueryContext {\n /**\n * Counts the number of documents passed through during local query execution.\n */\n private _documentReadCount = 0;\n\n get documentReadCount(): number {\n return this._documentReadCount;\n }\n\n incrementDocumentReadCount(amount: number): void {\n this._documentReadCount += amount;\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\nimport { getUA, isSafari } from '@firebase/util';\n\nimport {\n LimitType,\n newQueryComparator,\n Query,\n queryMatches,\n queryMatchesAllDocuments,\n queryToTarget,\n queryWithLimit,\n stringifyQuery\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport {\n IndexOffset,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { Iterable } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { getAndroidVersion } from './simple_db';\n\nconst DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE = 100;\n\n/**\n * This cost represents the evaluation result of\n * (([index, docKey] + [docKey, docContent]) per document in the result set)\n * / ([docKey, docContent] per documents in full collection scan) coming from\n * experiment [enter PR experiment URL here].\n */\nfunction getDefaultRelativeIndexReadCostPerDocument(): number {\n // These values were derived from an experiment where several members of the\n // Firestore SDK team ran a performance test in various environments.\n // Googlers can see b/299284287 for details.\n if (isSafari()) {\n return 8;\n } else if (getAndroidVersion(getUA()) > 0) {\n return 6;\n } else {\n return 4;\n }\n}\n\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */\nexport class QueryEngine {\n private localDocumentsView!: LocalDocumentsView;\n private indexManager!: IndexManager;\n private initialized = false;\n\n indexAutoCreationEnabled = false;\n\n /**\n * SDK only decides whether it should create index when collection size is\n * larger than this.\n */\n indexAutoCreationMinCollectionSize =\n DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE;\n\n relativeIndexReadCostPerDocument =\n getDefaultRelativeIndexReadCostPerDocument();\n\n /** Sets the document view to query against. */\n initialize(\n localDocuments: LocalDocumentsView,\n indexManager: IndexManager\n ): void {\n this.localDocumentsView = localDocuments;\n this.indexManager = indexManager;\n this.initialized = true;\n }\n\n /** Returns all local documents matching the specified query. */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n lastLimboFreeSnapshotVersion: SnapshotVersion,\n remoteKeys: DocumentKeySet\n ): PersistencePromise {\n debugAssert(this.initialized, 'initialize() not called');\n\n // Stores the result from executing the query; using this object is more\n // convenient than passing the result between steps of the persistence\n // transaction and improves readability comparatively.\n const queryResult: { result: DocumentMap | null } = { result: null };\n\n return this.performQueryUsingIndex(transaction, query)\n .next(result => {\n queryResult.result = result;\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n return this.performQueryUsingRemoteKeys(\n transaction,\n query,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n ).next(result => {\n queryResult.result = result;\n });\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n const context = new QueryContext();\n return this.executeFullCollectionScan(transaction, query, context).next(\n result => {\n queryResult.result = result;\n if (this.indexAutoCreationEnabled) {\n return this.createCacheIndexes(\n transaction,\n query,\n context,\n result.size\n );\n }\n }\n );\n })\n .next(() => queryResult.result!);\n }\n\n createCacheIndexes(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext,\n resultSize: number\n ): PersistencePromise {\n if (context.documentReadCount < this.indexAutoCreationMinCollectionSize) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'SDK will not create cache indexes for query:',\n stringifyQuery(query),\n 'since it only creates cache indexes for collection contains',\n 'more than or equal to',\n this.indexAutoCreationMinCollectionSize,\n 'documents'\n );\n }\n return PersistencePromise.resolve();\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Query:',\n stringifyQuery(query),\n 'scans',\n context.documentReadCount,\n 'local documents and returns',\n resultSize,\n 'documents as results.'\n );\n }\n\n if (\n context.documentReadCount >\n this.relativeIndexReadCostPerDocument * resultSize\n ) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'The SDK decides to create cache indexes for query:',\n stringifyQuery(query),\n 'as using cache indexes may help improve performance.'\n );\n }\n return this.indexManager.createTargetIndexes(\n transaction,\n queryToTarget(query)\n );\n }\n\n return PersistencePromise.resolve();\n }\n\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */\n private performQueryUsingIndex(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve(null);\n }\n\n let target = queryToTarget(query);\n return this.indexManager\n .getIndexType(transaction, target)\n .next(indexType => {\n if (indexType === IndexType.NONE) {\n // The target cannot be served from any index.\n return null;\n }\n\n if (query.limit !== null && indexType === IndexType.PARTIAL) {\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n query = queryWithLimit(query, null, LimitType.First);\n target = queryToTarget(query);\n }\n\n return this.indexManager\n .getDocumentsMatchingTarget(transaction, target)\n .next(keys => {\n debugAssert(\n !!keys,\n 'Index manager must return results for partial and full indexes.'\n );\n const sortedKeys = documentKeySet(...keys);\n return this.localDocumentsView\n .getDocuments(transaction, sortedKeys)\n .next(indexedDocuments => {\n return this.indexManager\n .getMinOffset(transaction, target)\n .next(offset => {\n const previousResults = this.applyQuery(\n query,\n indexedDocuments\n );\n\n if (\n this.needsRefill(\n query,\n previousResults,\n sortedKeys,\n offset.readTime\n )\n ) {\n // A limit query whose boundaries change due to local\n // edits can be re-run against the cache by excluding the\n // limit. This ensures that all documents that match the\n // query's filters are included in the result set. The SDK\n // can then apply the limit once all local edits are\n // incorporated.\n return this.performQueryUsingIndex(\n transaction,\n queryWithLimit(query, null, LimitType.First)\n );\n }\n\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n offset\n ) as PersistencePromise;\n });\n });\n });\n });\n }\n\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */\n private performQueryUsingRemoteKeys(\n transaction: PersistenceTransaction,\n query: Query,\n remoteKeys: DocumentKeySet,\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): PersistencePromise {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve(null);\n }\n\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) {\n return PersistencePromise.resolve(null);\n }\n\n return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(\n documents => {\n const previousResults = this.applyQuery(query, documents);\n\n if (\n this.needsRefill(\n query,\n previousResults,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n )\n ) {\n return PersistencePromise.resolve(null);\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Re-using previous result from %s to execute query: %s',\n lastLimboFreeSnapshotVersion.toString(),\n stringifyQuery(query)\n );\n }\n\n // Retrieve all results for documents that were updated since the last\n // limbo-document free remote snapshot.\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n newIndexOffsetSuccessorFromReadTime(\n lastLimboFreeSnapshotVersion,\n INITIAL_LARGEST_BATCH_ID\n )\n ).next(results => results);\n }\n );\n }\n\n /** Applies the query filter and sorting to the provided documents. */\n private applyQuery(\n query: Query,\n documents: DocumentMap\n ): SortedSet {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let queryResults = new SortedSet(newQueryComparator(query));\n documents.forEach((_, maybeDoc) => {\n if (queryMatches(query, maybeDoc)) {\n queryResults = queryResults.add(maybeDoc);\n }\n });\n return queryResults;\n }\n\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */\n private needsRefill(\n query: Query,\n sortedPreviousResults: SortedSet,\n remoteKeys: DocumentKeySet,\n limboFreeSnapshotVersion: SnapshotVersion\n ): boolean {\n if (query.limit === null) {\n // Queries without limits do not need to be refilled.\n return false;\n }\n\n if (remoteKeys.size !== sortedPreviousResults.size) {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return true;\n }\n\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const docAtLimitEdge =\n query.limitType === LimitType.First\n ? sortedPreviousResults.last()\n : sortedPreviousResults.first();\n if (!docAtLimitEdge) {\n // We don't need to refill the query if there were already no documents.\n return false;\n }\n return (\n docAtLimitEdge.hasPendingWrites ||\n docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0\n );\n }\n\n private executeFullCollectionScan(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext\n ): PersistencePromise {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Using full collection scan to execute query:',\n stringifyQuery(query)\n );\n }\n\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n IndexOffset.min(),\n context\n );\n }\n\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */\n private appendRemainingResults(\n transaction: PersistenceTransaction,\n indexedResults: Iterable,\n query: Query,\n offset: IndexOffset\n ): PersistencePromise {\n // Retrieve all results for documents that were updated since the offset.\n return this.localDocumentsView\n .getDocumentsMatchingQuery(transaction, query, offset)\n .next(remainingResults => {\n // Merge with existing results\n indexedResults.forEach(d => {\n remainingResults = remainingResults.insert(d.key, d);\n });\n return remainingResults;\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 { User } from '../auth/user';\nimport { BundleConverter, BundledDocuments, NamedQuery } from '../core/bundle';\nimport {\n newQueryForPath,\n Query,\n queryCollectionGroup,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { BatchId, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n convertOverlayedDocumentMapToDocumentMap,\n documentKeySet,\n DocumentKeySet,\n DocumentMap,\n mutableDocumentMap,\n MutableDocumentMap,\n OverlayedDocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexSemanticComparator,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport {\n mutationExtractBaseValue,\n Mutation,\n PatchMutation,\n Precondition\n} from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { extractFieldMask } from '../model/object_value';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { fromVersion, JsonProtoSerializer } from '../remote/serializer';\nimport { diffArrays } from '../util/array';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { fromBundledQuery } from './local_serializer';\nimport { LocalStore } from './local_store';\nimport { LocalViewChanges } from './local_view_changes';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryEngine } from './query_engine';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { ClientId } from './shared_client_state';\nimport { isIndexedDbTransactionError } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData, TargetPurpose } from './target_data';\n\nexport const LOG_TAG = 'LocalStore';\n\n/**\n * The maximum time to leave a resume token buffered without writing it out.\n * This value is arbitrary: it's long enough to avoid several writes\n * (possibly indefinitely if updates come more frequently than this) but\n * short enough that restarting after crashing will still have a pretty\n * recent resume token.\n */\nconst RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n\n/** The result of a write to the local store. */\nexport interface LocalWriteResult {\n batchId: BatchId;\n changes: DocumentMap;\n}\n\n/** The result of a user-change operation in the local store. */\nexport interface UserChangeResult {\n readonly affectedDocuments: DocumentMap;\n readonly removedBatchIds: BatchId[];\n readonly addedBatchIds: BatchId[];\n}\n\n/** The result of executing a query against the local store. */\nexport interface QueryResult {\n readonly documents: DocumentMap;\n readonly remoteKeys: DocumentKeySet;\n}\n\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass LocalStoreImpl implements LocalStore {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n mutationQueue!: MutationQueue;\n\n /**\n * The overlays that can be used to short circuit applying all mutations from\n * mutation queue.\n */\n documentOverlayCache!: DocumentOverlayCache;\n\n /** The set of all cached remote documents. */\n remoteDocuments: RemoteDocumentCache;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments!: LocalDocumentsView;\n\n /** Manages the list of active field and collection indices. */\n indexManager!: IndexManager;\n\n /** The set of all cached bundle metadata and named queries. */\n bundleCache: BundleCache;\n\n /** Maps a target to its `TargetData`. */\n targetCache: TargetCache;\n\n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n targetDataByTarget = new SortedMap(primitiveComparator);\n\n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n targetIdByTarget = new ObjectMap(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n collectionGroupReadTime = new Map();\n\n constructor(\n /** Manages our in-memory or durable persistence. */\n readonly persistence: Persistence,\n readonly queryEngine: QueryEngine,\n initialUser: User,\n readonly serializer: JsonProtoSerializer\n ) {\n debugAssert(\n persistence.started,\n 'LocalStore was passed an unstarted persistence implementation'\n );\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.targetCache = persistence.getTargetCache();\n this.bundleCache = persistence.getBundleCache();\n\n this.initializeUserComponents(initialUser);\n }\n\n initializeUserComponents(user: User): void {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(user);\n this.indexManager = this.persistence.getIndexManager(user);\n this.mutationQueue = this.persistence.getMutationQueue(\n user,\n this.indexManager\n );\n this.localDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n this.mutationQueue,\n this.documentOverlayCache,\n this.indexManager\n );\n this.remoteDocuments.setIndexManager(this.indexManager);\n this.queryEngine.initialize(this.localDocuments, this.indexManager);\n }\n\n collectGarbage(garbageCollector: LruGarbageCollector): Promise {\n return this.persistence.runTransaction(\n 'Collect garbage',\n 'readwrite-primary',\n txn => garbageCollector.collect(txn, this.targetDataByTarget)\n );\n }\n}\n\ninterface DocumentChangeResult {\n changedDocuments: MutableDocumentMap;\n existenceChangedKeys: DocumentKeySet;\n}\n\nexport function newLocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence: Persistence,\n queryEngine: QueryEngine,\n initialUser: User,\n serializer: JsonProtoSerializer\n): LocalStore {\n return new LocalStoreImpl(persistence, queryEngine, initialUser, serializer);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nexport async function localStoreHandleUserChange(\n localStore: LocalStore,\n user: User\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n const result = await localStoreImpl.persistence.runTransaction(\n 'Handle user change',\n 'readonly',\n txn => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let oldBatches: MutationBatch[];\n return localStoreImpl.mutationQueue\n .getAllMutationBatches(txn)\n .next(promisedOldBatches => {\n oldBatches = promisedOldBatches;\n localStoreImpl.initializeUserComponents(user);\n return localStoreImpl.mutationQueue.getAllMutationBatches(txn);\n })\n .next(newBatches => {\n const removedBatchIds: BatchId[] = [];\n const addedBatchIds: BatchId[] = [];\n\n // Union the old/new changed keys.\n let changedKeys = documentKeySet();\n\n for (const batch of oldBatches) {\n removedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n for (const batch of newBatches) {\n addedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return localStoreImpl.localDocuments\n .getDocuments(txn, changedKeys)\n .next(affectedDocuments => {\n return {\n affectedDocuments,\n removedBatchIds,\n addedBatchIds\n };\n });\n });\n }\n );\n\n return result;\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\nexport function localStoreWriteLocally(\n localStore: LocalStore,\n mutations: Mutation[]\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const localWriteTime = Timestamp.now();\n const keys = mutations.reduce((keys, m) => keys.add(m.key), documentKeySet());\n\n let overlayedDocuments: OverlayedDocumentMap;\n let mutationBatch: MutationBatch;\n\n return localStoreImpl.persistence\n .runTransaction('Locally write mutations', 'readwrite', txn => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let remoteDocs = mutableDocumentMap();\n let docsWithoutRemoteVersion = documentKeySet();\n return localStoreImpl.remoteDocuments\n .getEntries(txn, keys)\n .next(docs => {\n remoteDocs = docs;\n remoteDocs.forEach((key, doc) => {\n if (!doc.isValidDocument()) {\n docsWithoutRemoteVersion = docsWithoutRemoteVersion.add(key);\n }\n });\n })\n .next(() => {\n // Load and apply all existing mutations. This lets us compute the\n // current base state for all non-idempotent transforms before applying\n // any additional user-provided writes.\n return localStoreImpl.localDocuments.getOverlayedDocuments(\n txn,\n remoteDocs\n );\n })\n .next((docs: OverlayedDocumentMap) => {\n overlayedDocuments = docs;\n\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const baseMutations: Mutation[] = [];\n\n for (const mutation of mutations) {\n const baseValue = mutationExtractBaseValue(\n mutation,\n overlayedDocuments.get(mutation.key)!.overlayedDocument\n );\n if (baseValue != null) {\n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n baseMutations.push(\n new PatchMutation(\n mutation.key,\n baseValue,\n extractFieldMask(baseValue.value.mapValue),\n Precondition.exists(true)\n )\n );\n }\n }\n\n return localStoreImpl.mutationQueue.addMutationBatch(\n txn,\n localWriteTime,\n baseMutations,\n mutations\n );\n })\n .next(batch => {\n mutationBatch = batch;\n const overlays = batch.applyToLocalDocumentSet(\n overlayedDocuments,\n docsWithoutRemoteVersion\n );\n return localStoreImpl.documentOverlayCache.saveOverlays(\n txn,\n batch.batchId,\n overlays\n );\n });\n })\n .then(() => ({\n batchId: mutationBatch.batchId,\n changes: convertOverlayedDocumentMapToDocumentMap(overlayedDocuments)\n }));\n}\n\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nexport function localStoreAcknowledgeBatch(\n localStore: LocalStore,\n batchResult: MutationBatchResult\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Acknowledge batch',\n 'readwrite-primary',\n txn => {\n const affected = batchResult.batch.keys();\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n return applyWriteToRemoteDocuments(\n localStoreImpl,\n txn,\n batchResult,\n documentBuffer\n )\n .next(() => documentBuffer.apply(txn))\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affected,\n batchResult.batch.batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n getKeysWithTransformResults(batchResult)\n )\n )\n .next(() => localStoreImpl.localDocuments.getDocuments(txn, affected));\n }\n );\n}\n\nfunction getKeysWithTransformResults(\n batchResult: MutationBatchResult\n): DocumentKeySet {\n let result = documentKeySet();\n\n for (let i = 0; i < batchResult.mutationResults.length; ++i) {\n const mutationResult = batchResult.mutationResults[i];\n if (mutationResult.transformResults.length > 0) {\n result = result.add(batchResult.batch.mutations[i].key);\n }\n }\n return result;\n}\n\n/**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\nexport function localStoreRejectBatch(\n localStore: LocalStore,\n batchId: BatchId\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Reject batch',\n 'readwrite-primary',\n txn => {\n let affectedKeys: DocumentKeySet;\n return localStoreImpl.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next((batch: MutationBatch | null) => {\n hardAssert(batch !== null, 'Attempt to reject nonexistent batch!');\n affectedKeys = batch.keys();\n return localStoreImpl.mutationQueue.removeMutationBatch(txn, batch);\n })\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affectedKeys,\n batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n affectedKeys\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getDocuments(txn, affectedKeys)\n );\n }\n );\n}\n\n/**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */\nexport function localStoreGetHighestUnacknowledgedBatchId(\n localStore: LocalStore\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get highest unacknowledged batch id',\n 'readonly',\n txn => localStoreImpl.mutationQueue.getHighestUnacknowledgedBatchId(txn)\n );\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nexport function localStoreGetLastRemoteSnapshotVersion(\n localStore: LocalStore\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get last remote snapshot version',\n 'readonly',\n txn => localStoreImpl.targetCache.getLastRemoteSnapshotVersion(txn)\n );\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport function localStoreApplyRemoteEventToLocalCache(\n localStore: LocalStore,\n remoteEvent: RemoteEvent\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const remoteVersion = remoteEvent.snapshotVersion;\n let newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n return localStoreImpl.persistence\n .runTransaction('Apply remote event', 'readwrite-primary', txn => {\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n const promises = [] as Array>;\n remoteEvent.targetChanges.forEach((change, targetId) => {\n const oldTargetData = newTargetDataByTargetMap.get(targetId);\n if (!oldTargetData) {\n return;\n }\n\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n promises.push(\n localStoreImpl.targetCache\n .removeMatchingKeys(txn, change.removedDocuments, targetId)\n .next(() => {\n return localStoreImpl.targetCache.addMatchingKeys(\n txn,\n change.addedDocuments,\n targetId\n );\n })\n );\n\n let newTargetData = oldTargetData.withSequenceNumber(\n txn.currentSequenceNumber\n );\n if (remoteEvent.targetMismatches.get(targetId) !== null) {\n newTargetData = newTargetData\n .withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n SnapshotVersion.min()\n )\n .withLastLimboFreeSnapshotVersion(SnapshotVersion.min());\n } else if (change.resumeToken.approximateByteSize() > 0) {\n newTargetData = newTargetData.withResumeToken(\n change.resumeToken,\n remoteVersion\n );\n }\n\n newTargetDataByTargetMap = newTargetDataByTargetMap.insert(\n targetId,\n newTargetData\n );\n\n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n if (shouldPersistTargetData(oldTargetData, newTargetData, change)) {\n promises.push(\n localStoreImpl.targetCache.updateTargetData(txn, newTargetData)\n );\n }\n });\n\n let changedDocs = mutableDocumentMap();\n let existenceChangedKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(key => {\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\n promises.push(\n localStoreImpl.persistence.referenceDelegate.updateLimboDocument(\n txn,\n key\n )\n );\n }\n });\n\n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n promises.push(\n populateDocumentChangeBuffer(\n txn,\n documentBuffer,\n remoteEvent.documentUpdates\n ).next(result => {\n changedDocs = result.changedDocuments;\n existenceChangedKeys = result.existenceChangedKeys;\n })\n );\n\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (!remoteVersion.isEqual(SnapshotVersion.min())) {\n const updateRemoteVersion = localStoreImpl.targetCache\n .getLastRemoteSnapshotVersion(txn)\n .next(lastRemoteSnapshotVersion => {\n debugAssert(\n remoteVersion.compareTo(lastRemoteSnapshotVersion) >= 0,\n 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteSnapshotVersion\n );\n return localStoreImpl.targetCache.setTargetsMetadata(\n txn,\n txn.currentSequenceNumber,\n remoteVersion\n );\n });\n promises.push(updateRemoteVersion);\n }\n\n return PersistencePromise.waitFor(promises)\n .next(() => documentBuffer.apply(txn))\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n changedDocs,\n existenceChangedKeys\n )\n )\n .next(() => changedDocs);\n })\n .then(changedDocs => {\n localStoreImpl.targetDataByTarget = newTargetDataByTargetMap;\n return changedDocs;\n });\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */\nfunction populateDocumentChangeBuffer(\n txn: PersistenceTransaction,\n documentBuffer: RemoteDocumentChangeBuffer,\n documents: MutableDocumentMap\n): PersistencePromise {\n let updatedKeys = documentKeySet();\n let existenceChangedKeys = documentKeySet();\n documents.forEach(k => (updatedKeys = updatedKeys.add(k)));\n return documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => {\n let changedDocuments = mutableDocumentMap();\n documents.forEach((key, doc) => {\n const existingDoc = existingDocs.get(key)!;\n\n // Check if see if there is a existence state change for this document.\n if (doc.isFoundDocument() !== existingDoc.isFoundDocument()) {\n existenceChangedKeys = existenceChangedKeys.add(key);\n }\n\n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n if (doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min())) {\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n documentBuffer.removeEntry(key, doc.readTime);\n changedDocuments = changedDocuments.insert(key, doc);\n } else if (\n !existingDoc.isValidDocument() ||\n doc.version.compareTo(existingDoc.version) > 0 ||\n (doc.version.compareTo(existingDoc.version) === 0 &&\n existingDoc.hasPendingWrites)\n ) {\n debugAssert(\n !SnapshotVersion.min().isEqual(doc.readTime),\n 'Cannot add a document when the remote version is zero'\n );\n documentBuffer.addEntry(doc);\n changedDocuments = changedDocuments.insert(key, doc);\n } else {\n logDebug(\n LOG_TAG,\n 'Ignoring outdated watch update for ',\n key,\n '. Current version:',\n existingDoc.version,\n ' Watch version:',\n doc.version\n );\n }\n });\n return { changedDocuments, existenceChangedKeys };\n });\n}\n\n/**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\nfunction shouldPersistTargetData(\n oldTargetData: TargetData,\n newTargetData: TargetData,\n change: TargetChange\n): boolean {\n // Always persist target data if we don't already have a resume token.\n if (oldTargetData.resumeToken.approximateByteSize() === 0) {\n return true;\n }\n\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n const timeDelta =\n newTargetData.snapshotVersion.toMicroseconds() -\n oldTargetData.snapshotVersion.toMicroseconds();\n if (timeDelta >= RESUME_TOKEN_MAX_AGE_MICROS) {\n return true;\n }\n\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n const changes =\n change.addedDocuments.size +\n change.modifiedDocuments.size +\n change.removedDocuments.size;\n return changes > 0;\n}\n\n/**\n * Notifies local store of the changed views to locally pin documents.\n */\nexport async function localStoreNotifyLocalViewChanges(\n localStore: LocalStore,\n viewChanges: LocalViewChanges[]\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n try {\n await localStoreImpl.persistence.runTransaction(\n 'notifyLocalViewChanges',\n 'readwrite',\n txn => {\n return PersistencePromise.forEach(\n viewChanges,\n (viewChange: LocalViewChanges) => {\n return PersistencePromise.forEach(\n viewChange.addedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.addReference(\n txn,\n viewChange.targetId,\n key\n )\n ).next(() =>\n PersistencePromise.forEach(\n viewChange.removedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.removeReference(\n txn,\n viewChange.targetId,\n key\n )\n )\n );\n }\n );\n }\n );\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n logDebug(LOG_TAG, 'Failed to update sequence numbers: ' + e);\n } else {\n throw e;\n }\n }\n\n for (const viewChange of viewChanges) {\n const targetId = viewChange.targetId;\n\n if (!viewChange.fromCache) {\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Can't set limbo-free snapshot version for unknown target: ${targetId}`\n );\n\n // Advance the last limbo free snapshot version\n const lastLimboFreeSnapshotVersion = targetData.snapshotVersion;\n const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData);\n\n // TODO(b/272564316): Apply the optimization done on other platforms.\n // This is a problem for web because saving the updated targetData from\n // non-primary client conflicts with what primary client saved.\n }\n }\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nexport function localStoreGetNextMutationBatch(\n localStore: LocalStore,\n afterBatchId?: BatchId\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get next mutation batch',\n 'readonly',\n txn => {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return localStoreImpl.mutationQueue.getNextMutationBatchAfterBatchId(\n txn,\n afterBatchId\n );\n }\n );\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\nexport function localStoreReadDocument(\n localStore: LocalStore,\n key: DocumentKey\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'read document',\n 'readonly',\n txn => localStoreImpl.localDocuments.getDocument(txn, key)\n );\n}\n\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nexport function localStoreAllocateTarget(\n localStore: LocalStore,\n target: Target\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence\n .runTransaction('Allocate target', 'readwrite', txn => {\n let targetData: TargetData;\n return localStoreImpl.targetCache\n .getTargetData(txn, target)\n .next((cached: TargetData | null) => {\n if (cached) {\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n targetData = cached;\n return PersistencePromise.resolve(targetData);\n } else {\n return localStoreImpl.targetCache\n .allocateTargetId(txn)\n .next(targetId => {\n targetData = new TargetData(\n target,\n targetId,\n TargetPurpose.Listen,\n txn.currentSequenceNumber\n );\n return localStoreImpl.targetCache\n .addTargetData(txn, targetData)\n .next(() => targetData);\n });\n }\n });\n })\n .then(targetData => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(\n targetData.targetId\n );\n if (\n cachedTargetData === null ||\n targetData.snapshotVersion.compareTo(cachedTargetData.snapshotVersion) >\n 0\n ) {\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n targetData.targetId,\n targetData\n );\n localStoreImpl.targetIdByTarget.set(target, targetData.targetId);\n }\n return targetData;\n });\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\nexport function localStoreGetTargetData(\n localStore: LocalStore,\n transaction: PersistenceTransaction,\n target: Target\n): PersistencePromise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetId = localStoreImpl.targetIdByTarget.get(target);\n if (targetId !== undefined) {\n return PersistencePromise.resolve(\n localStoreImpl.targetDataByTarget.get(targetId)\n );\n } else {\n return localStoreImpl.targetCache.getTargetData(transaction, target);\n }\n}\n\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nexport async function localStoreReleaseTarget(\n localStore: LocalStore,\n targetId: number,\n keepPersistedTargetData: boolean\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Tried to release nonexistent target: ${targetId}`\n );\n\n const mode = keepPersistedTargetData ? 'readwrite' : 'readwrite-primary';\n\n try {\n if (!keepPersistedTargetData) {\n await localStoreImpl.persistence.runTransaction(\n 'Release target',\n mode,\n txn => {\n return localStoreImpl.persistence.referenceDelegate.removeTarget(\n txn,\n targetData!\n );\n }\n );\n }\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n logDebug(\n LOG_TAG,\n `Failed to update sequence numbers for target ${targetId}: ${e}`\n );\n } else {\n throw e;\n }\n }\n\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.remove(targetId);\n localStoreImpl.targetIdByTarget.delete(targetData!.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */\nexport function localStoreExecuteQuery(\n localStore: LocalStore,\n query: Query,\n usePreviousResults: boolean\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let lastLimboFreeSnapshotVersion = SnapshotVersion.min();\n let remoteKeys = documentKeySet();\n\n return localStoreImpl.persistence.runTransaction(\n 'Execute query',\n 'readwrite', // Use readwrite instead of readonly so indexes can be created\n txn => {\n return localStoreGetTargetData(localStoreImpl, txn, queryToTarget(query))\n .next(targetData => {\n if (targetData) {\n lastLimboFreeSnapshotVersion =\n targetData.lastLimboFreeSnapshotVersion;\n return localStoreImpl.targetCache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(result => {\n remoteKeys = result;\n });\n }\n })\n .next(() =>\n localStoreImpl.queryEngine.getDocumentsMatchingQuery(\n txn,\n query,\n usePreviousResults\n ? lastLimboFreeSnapshotVersion\n : SnapshotVersion.min(),\n usePreviousResults ? remoteKeys : documentKeySet()\n )\n )\n .next(documents => {\n setMaxReadTime(\n localStoreImpl,\n queryCollectionGroup(query),\n documents\n );\n return { documents, remoteKeys };\n });\n }\n );\n}\n\nfunction applyWriteToRemoteDocuments(\n localStoreImpl: LocalStoreImpl,\n txn: PersistenceTransaction,\n batchResult: MutationBatchResult,\n documentBuffer: RemoteDocumentChangeBuffer\n): PersistencePromise {\n const batch = batchResult.batch;\n const docKeys = batch.keys();\n let promiseChain = PersistencePromise.resolve();\n docKeys.forEach(docKey => {\n promiseChain = promiseChain\n .next(() => documentBuffer.getEntry(txn, docKey))\n .next(doc => {\n const ackVersion = batchResult.docVersions.get(docKey);\n hardAssert(\n ackVersion !== null,\n 'ackVersions should contain every doc in the write.'\n );\n if (doc.version.compareTo(ackVersion!) < 0) {\n batch.applyToRemoteDocument(doc, batchResult);\n if (doc.isValidDocument()) {\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n doc.setReadTime(batchResult.commitVersion);\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain.next(() =>\n localStoreImpl.mutationQueue.removeMutationBatch(txn, batch)\n );\n}\n\n/** Returns the local view of the documents affected by a mutation batch. */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreLookupMutationDocuments(\n localStore: LocalStore,\n batchId: BatchId\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const mutationQueueImpl = debugCast(\n localStoreImpl.mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n return localStoreImpl.persistence.runTransaction(\n 'Lookup mutation documents',\n 'readonly',\n txn => {\n return mutationQueueImpl.lookupMutationKeys(txn, batchId).next(keys => {\n if (keys) {\n return localStoreImpl.localDocuments.getDocuments(\n txn,\n keys\n ) as PersistencePromise;\n } else {\n return PersistencePromise.resolve(null);\n }\n });\n }\n );\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreRemoveCachedMutationBatchMetadata(\n localStore: LocalStore,\n batchId: BatchId\n): void {\n const mutationQueueImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n mutationQueueImpl.removeCachedMutationKeys(batchId);\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetActiveClients(\n localStore: LocalStore\n): Promise {\n const persistenceImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).persistence,\n IndexedDbPersistence // We only support IndexedDb in multi-tab mode.\n );\n return persistenceImpl.getActiveClients();\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetCachedTarget(\n localStore: LocalStore,\n targetId: TargetId\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetCacheImpl = debugCast(\n localStoreImpl.targetCache,\n IndexedDbTargetCache // We only support IndexedDb in multi-tab mode.\n );\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetId);\n if (cachedTargetData) {\n return Promise.resolve(cachedTargetData.target);\n } else {\n return localStoreImpl.persistence.runTransaction(\n 'Get target data',\n 'readonly',\n txn => {\n return targetCacheImpl\n .getTargetDataForTarget(txn, targetId)\n .next(targetData => (targetData ? targetData.target : null));\n }\n );\n }\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetNewDocumentChanges(\n localStore: LocalStore,\n collectionGroup: string\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n const readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n\n return localStoreImpl.persistence\n .runTransaction('Get new document changes', 'readonly', txn =>\n localStoreImpl.remoteDocuments.getAllFromCollectionGroup(\n txn,\n collectionGroup,\n newIndexOffsetSuccessorFromReadTime(readTime, INITIAL_LARGEST_BATCH_ID),\n /* limit= */ Number.MAX_SAFE_INTEGER\n )\n )\n .then(changedDocs => {\n setMaxReadTime(localStoreImpl, collectionGroup, changedDocs);\n return changedDocs;\n });\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction setMaxReadTime(\n localStoreImpl: LocalStoreImpl,\n collectionGroup: string,\n changedDocs: SortedMap\n): void {\n let readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n changedDocs.forEach((_, doc) => {\n if (doc.readTime.compareTo(readTime) > 0) {\n readTime = doc.readTime;\n }\n });\n localStoreImpl.collectionGroupReadTime.set(collectionGroup, readTime);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\nfunction umbrellaTarget(bundleName: string): Target {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return queryToTarget(\n newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${bundleName}`))\n );\n}\n\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport async function localStoreApplyBundledDocuments(\n localStore: LocalStore,\n bundleConverter: BundleConverter,\n documents: BundledDocuments,\n bundleName: string\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let documentKeys = documentKeySet();\n let documentMap = mutableDocumentMap();\n for (const bundleDoc of documents) {\n const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name!);\n if (bundleDoc.document) {\n documentKeys = documentKeys.add(documentKey);\n }\n const doc = bundleConverter.toMutableDocument(bundleDoc);\n doc.setReadTime(\n bundleConverter.toSnapshotVersion(bundleDoc.metadata.readTime!)\n );\n documentMap = documentMap.insert(documentKey, doc);\n }\n\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n const umbrellaTargetData = await localStoreAllocateTarget(\n localStoreImpl,\n umbrellaTarget(bundleName)\n );\n return localStoreImpl.persistence.runTransaction(\n 'Apply bundle documents',\n 'readwrite',\n txn => {\n return populateDocumentChangeBuffer(txn, documentBuffer, documentMap)\n .next(documentChangeResult => {\n documentBuffer.apply(txn);\n return documentChangeResult;\n })\n .next(documentChangeResult => {\n return localStoreImpl.targetCache\n .removeMatchingKeysForTargetId(txn, umbrellaTargetData.targetId)\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n txn,\n documentKeys,\n umbrellaTargetData.targetId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n documentChangeResult.changedDocuments,\n documentChangeResult.existenceChangedKeys\n )\n )\n .next(() => documentChangeResult.changedDocuments);\n });\n }\n );\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\nexport function localStoreHasNewerBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const currentReadTime = fromVersion(bundleMetadata.createTime!);\n return localStoreImpl.persistence\n .runTransaction('hasNewerBundle', 'readonly', transaction => {\n return localStoreImpl.bundleCache.getBundleMetadata(\n transaction,\n bundleMetadata.id!\n );\n })\n .then(cached => {\n return !!cached && cached.createTime!.compareTo(currentReadTime) >= 0;\n });\n}\n\n/**\n * Saves the given `BundleMetadata` to local persistence.\n */\nexport function localStoreSaveBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save bundle',\n 'readwrite',\n transaction => {\n return localStoreImpl.bundleCache.saveBundleMetadata(\n transaction,\n bundleMetadata\n );\n }\n );\n}\n\n/**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */\nexport function localStoreGetNamedQuery(\n localStore: LocalStore,\n queryName: string\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get named query',\n 'readonly',\n transaction =>\n localStoreImpl.bundleCache.getNamedQuery(transaction, queryName)\n );\n}\n\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nexport async function localStoreSaveNamedQuery(\n localStore: LocalStore,\n query: ProtoNamedQuery,\n documents: DocumentKeySet = documentKeySet()\n): Promise {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const allocated = await localStoreAllocateTarget(\n localStore,\n queryToTarget(fromBundledQuery(query.bundledQuery!))\n );\n\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save named query',\n 'readwrite',\n transaction => {\n const readTime = fromVersion(query.readTime!);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (allocated.snapshotVersion.compareTo(readTime) >= 0) {\n return localStoreImpl.bundleCache.saveNamedQuery(transaction, query);\n }\n\n // Update existing target data because the query from the bundle is newer.\n const newTargetData = allocated.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n readTime\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n newTargetData.targetId,\n newTargetData\n );\n return localStoreImpl.targetCache\n .updateTargetData(transaction, newTargetData)\n .next(() =>\n localStoreImpl.targetCache.removeMatchingKeysForTargetId(\n transaction,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n transaction,\n documents,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.bundleCache.saveNamedQuery(transaction, query)\n );\n }\n );\n}\n\nexport async function localStoreConfigureFieldIndexes(\n localStore: LocalStore,\n newFieldIndexes: FieldIndex[]\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n const promises: Array> = [];\n return localStoreImpl.persistence.runTransaction(\n 'Configure indexes',\n 'readwrite',\n transaction =>\n indexManager\n .getFieldIndexes(transaction)\n .next(oldFieldIndexes =>\n diffArrays(\n oldFieldIndexes,\n newFieldIndexes,\n fieldIndexSemanticComparator,\n fieldIndex => {\n promises.push(\n indexManager.addFieldIndex(transaction, fieldIndex)\n );\n },\n fieldIndex => {\n promises.push(\n indexManager.deleteFieldIndex(transaction, fieldIndex)\n );\n }\n )\n )\n .next(() => PersistencePromise.waitFor(promises))\n );\n}\n\nexport function localStoreSetIndexAutoCreationEnabled(\n localStore: LocalStore,\n isEnabled: boolean\n): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n localStoreImpl.queryEngine.indexAutoCreationEnabled = isEnabled;\n}\n\nexport function localStoreDeleteAllFieldIndexes(\n localStore: LocalStore\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n return localStoreImpl.persistence.runTransaction(\n 'Delete All Indexes',\n 'readwrite',\n transaction => indexManager.deleteAllFieldIndexes(transaction)\n );\n}\n\n/**\n * Test-only hooks into the SDK for use exclusively by tests.\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('creating instances is not supported');\n }\n\n static setIndexAutoCreationSettings(\n localStore: LocalStore,\n settings: {\n indexAutoCreationMinCollectionSize?: number;\n relativeIndexReadCostPerDocument?: number;\n }\n ): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n if (settings.indexAutoCreationMinCollectionSize !== undefined) {\n localStoreImpl.queryEngine.indexAutoCreationMinCollectionSize =\n settings.indexAutoCreationMinCollectionSize;\n }\n if (settings.relativeIndexReadCostPerDocument !== undefined) {\n localStoreImpl.queryEngine.relativeIndexReadCostPerDocument =\n settings.relativeIndexReadCostPerDocument;\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\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n debugAssert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n// firestore_bundle_loaded_v2_\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(targetId: TargetId): QueryTargetState;\n\n /** Removes the Query Target ID association from the local client. */\n removeLocalQueryTarget(targetId: TargetId): void;\n\n /** Checks whether the target is associated with the local client. */\n isLocalQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Processes an update to a query target.\n *\n * Called by the primary client to notify secondary clients of document\n * changes or state transitions that affect the provided query target.\n */\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void;\n\n /**\n * Removes the target's metadata entry.\n *\n * Called by the primary client when all clients stopped listening to a query\n * target.\n */\n clearQueryState(targetId: TargetId): void;\n\n /**\n * Gets the active Query Targets IDs for all active clients.\n *\n * The implementation for this may require O(n) runtime, where 'n' is the size\n * of the result set.\n */\n // Visible for testing\n getAllActiveQueryTargets(): SortedSet;\n\n /**\n * Checks whether the provided target ID is currently being listened to by\n * any of the active clients.\n *\n * The implementation may require O(n*log m) runtime, where 'n' is the number\n * of clients and 'm' the number of targets.\n */\n isActiveQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Starts the SharedClientState, reads existing client data and registers\n * listeners for updates to new and existing clients.\n */\n start(): Promise;\n\n /** Shuts down the `SharedClientState` and its listeners. */\n shutdown(): void;\n\n /**\n * Changes the active user and removes all existing user-specific data. The\n * user change does not call back into SyncEngine (for example, no mutations\n * will be marked as removed).\n */\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void;\n\n /** Changes the shared online state of all clients. */\n setOnlineState(onlineState: OnlineState): void;\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n\n /**\n * Notifies other clients when remote documents have changed due to loading\n * a bundle.\n *\n * @param collectionGroups The collection groups affected by this bundle.\n */\n notifyBundleLoaded(collectionGroups: Set): void;\n}\n\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nexport class MutationMetadata {\n constructor(\n readonly user: User,\n readonly batchId: BatchId,\n readonly state: MutationBatchState,\n readonly error?: FirestoreError\n ) {\n debugAssert(\n (error !== undefined) === (state === 'rejected'),\n `MutationMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n user: User,\n batchId: BatchId,\n value: string\n ): MutationMetadata | null {\n const mutationBatch = JSON.parse(value) as MutationMetadataSchema;\n\n let validData =\n typeof mutationBatch === 'object' &&\n ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !==\n -1 &&\n (mutationBatch.error === undefined ||\n typeof mutationBatch.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && mutationBatch.error) {\n validData =\n typeof mutationBatch.error.message === 'string' &&\n typeof mutationBatch.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n mutationBatch.error.code as Code,\n mutationBatch.error.message\n );\n }\n }\n\n if (validData) {\n return new MutationMetadata(\n user,\n batchId,\n mutationBatch.state,\n firestoreError\n );\n } else {\n logError(\n LOG_TAG,\n `Failed to parse mutation state for ID '${batchId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const batchMetadata: MutationMetadataSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n batchMetadata.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(batchMetadata);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nexport class QueryTargetMetadata {\n constructor(\n readonly targetId: TargetId,\n readonly state: QueryTargetState,\n readonly error?: FirestoreError\n ) {\n debugAssert(\n (error !== undefined) === (state === 'rejected'),\n `QueryTargetMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n targetId: TargetId,\n value: string\n ): QueryTargetMetadata | null {\n const targetState = JSON.parse(value) as QueryTargetStateSchema;\n\n let validData =\n typeof targetState === 'object' &&\n ['not-current', 'current', 'rejected'].indexOf(targetState.state) !==\n -1 &&\n (targetState.error === undefined ||\n typeof targetState.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && targetState.error) {\n validData =\n typeof targetState.error.message === 'string' &&\n typeof targetState.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n targetState.error.code as Code,\n targetState.error.message\n );\n }\n }\n\n if (validData) {\n return new QueryTargetMetadata(\n targetId,\n targetState.state,\n firestoreError\n );\n } else {\n logError(\n LOG_TAG,\n `Failed to parse target state for ID '${targetId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const targetState: QueryTargetStateSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n targetState.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(targetState);\n }\n}\n\n/**\n * Metadata state of a single client denoting the query targets it is actively\n * listening to the watch.\n */\n// Visible for testing.\nexport interface ClientState {\n readonly activeTargetIds: TargetIdSet;\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */\nclass RemoteClientState implements ClientState {\n private constructor(\n readonly clientId: ClientId,\n readonly activeTargetIds: TargetIdSet\n ) {}\n\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n clientId: ClientId,\n value: string\n ): RemoteClientState | null {\n const clientState = JSON.parse(value) as ClientStateSchema;\n\n let validData =\n typeof clientState === 'object' &&\n clientState.activeTargetIds instanceof Array;\n\n let activeTargetIdsSet = targetIdSet();\n\n for (let i = 0; validData && i < clientState.activeTargetIds.length; ++i) {\n validData = isSafeInteger(clientState.activeTargetIds[i]);\n activeTargetIdsSet = activeTargetIdsSet.add(\n clientState.activeTargetIds[i]\n );\n }\n\n if (validData) {\n return new RemoteClientState(clientId, activeTargetIdsSet);\n } else {\n logError(\n LOG_TAG,\n `Failed to parse client data for instance '${clientId}': ${value}`\n );\n return null;\n }\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */\nexport class SharedOnlineState {\n constructor(readonly clientId: string, readonly onlineState: OnlineState) {}\n\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(value: string): SharedOnlineState | null {\n const onlineState = JSON.parse(value) as SharedOnlineStateSchema;\n\n const validData =\n typeof onlineState === 'object' &&\n ['Unknown', 'Online', 'Offline'].indexOf(onlineState.onlineState) !==\n -1 &&\n typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(\n onlineState.clientId,\n onlineState.onlineState as OnlineState\n );\n } else {\n logError(LOG_TAG, `Failed to parse online state: ${value}`);\n return null;\n }\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nexport class LocalClientState implements ClientState {\n activeTargetIds = targetIdSet();\n\n addQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.add(targetId);\n }\n\n removeQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.delete(targetId);\n }\n\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */\n toWebStorageJSON(): string {\n const data: ClientStateSchema = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n return JSON.stringify(data);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */\nexport class WebStorageSharedClientState implements SharedClientState {\n syncEngine: SharedClientStateSyncer | null = null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n private readonly storage: Storage;\n private readonly localClientStorageKey: string;\n private readonly sequenceNumberKey: string;\n private readonly storageListener = this.handleWebStorageEvent.bind(this);\n private readonly onlineStateKey: string;\n private readonly bundleLoadedKey: string;\n private readonly clientStateKeyRe: RegExp;\n private readonly mutationBatchKeyRe: RegExp;\n private readonly queryTargetKeyRe: RegExp;\n private activeClients = new SortedMap(\n primitiveComparator\n );\n private started = false;\n private currentUser: User;\n\n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n private earlyEvents: StorageEvent[] = [];\n\n constructor(\n private readonly window: WindowLike,\n private readonly queue: AsyncQueue,\n private readonly persistenceKey: string,\n private readonly localClientId: ClientId,\n initialUser: User\n ) {\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const escapedPersistenceKey = persistenceKey.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&'\n );\n\n this.storage = this.window.localStorage;\n this.currentUser = initialUser;\n this.localClientStorageKey = createWebStorageClientStateKey(\n this.persistenceKey,\n this.localClientId\n );\n this.sequenceNumberKey = createWebStorageSequenceNumberKey(\n this.persistenceKey\n );\n this.activeClients = this.activeClients.insert(\n this.localClientId,\n new LocalClientState()\n );\n\n this.clientStateKeyRe = new RegExp(\n `^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`\n );\n this.mutationBatchKeyRe = new RegExp(\n `^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)(?:_(.*))?$`\n );\n this.queryTargetKeyRe = new RegExp(\n `^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)$`\n );\n\n this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey);\n\n this.bundleLoadedKey = createBundleLoadedKey(this.persistenceKey);\n\n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener('storage', this.storageListener);\n }\n\n /** Returns 'true' if WebStorage is available in the current environment. */\n static isAvailable(window: WindowLike | null): window is WindowLike {\n return !!(window && window.localStorage);\n }\n\n async start(): Promise {\n debugAssert(!this.started, 'WebStorageSharedClientState already started');\n debugAssert(\n this.syncEngine !== null,\n 'syncEngine property must be set before calling start()'\n );\n debugAssert(\n this.onlineStateHandler !== null,\n 'onlineStateHandler property must be set before calling start()'\n );\n\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const existingClients = await this.syncEngine!.getActiveClients();\n\n for (const clientId of existingClients) {\n if (clientId === this.localClientId) {\n continue;\n }\n\n const storageItem = this.getItem(\n createWebStorageClientStateKey(this.persistenceKey, clientId)\n );\n if (storageItem) {\n const clientState = RemoteClientState.fromWebStorageEntry(\n clientId,\n storageItem\n );\n if (clientState) {\n this.activeClients = this.activeClients.insert(\n clientState.clientId,\n clientState\n );\n }\n }\n }\n\n this.persistClientState();\n\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const onlineStateJSON = this.storage.getItem(this.onlineStateKey);\n if (onlineStateJSON) {\n const onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\n if (onlineState) {\n this.handleOnlineStateEvent(onlineState);\n }\n }\n\n for (const event of this.earlyEvents) {\n this.handleWebStorageEvent(event);\n }\n\n this.earlyEvents = [];\n\n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener('pagehide', () => this.shutdown());\n\n this.started = true;\n }\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {\n this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.extractActiveQueryTargets(this.activeClients);\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n let found = false;\n this.activeClients.forEach((key, value) => {\n if (value.activeTargetIds.has(targetId)) {\n found = true;\n }\n });\n return found;\n }\n\n addPendingMutation(batchId: BatchId): void {\n this.persistMutationState(batchId, 'pending');\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n this.persistMutationState(batchId, state, error);\n\n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.removeMutationState(batchId);\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n let queryState: QueryTargetState = 'not-current';\n\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(targetId)) {\n const storageItem = this.storage.getItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n\n if (storageItem) {\n const metadata = QueryTargetMetadata.fromWebStorageEntry(\n targetId,\n storageItem\n );\n if (metadata) {\n queryState = metadata.state;\n }\n }\n }\n\n this.localClientState.addQueryTarget(targetId);\n this.persistClientState();\n\n return queryState;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localClientState.removeQueryTarget(targetId);\n this.persistClientState();\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localClientState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n this.removeItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.persistQueryTargetState(targetId, state, error);\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n removedBatchIds.forEach(batchId => {\n this.removeMutationState(batchId);\n });\n this.currentUser = user;\n addedBatchIds.forEach(batchId => {\n this.addPendingMutation(batchId);\n });\n }\n\n setOnlineState(onlineState: OnlineState): void {\n this.persistOnlineState(onlineState);\n }\n\n notifyBundleLoaded(collectionGroups: Set): void {\n this.persistBundleLoadedState(collectionGroups);\n }\n\n shutdown(): void {\n if (this.started) {\n this.window.removeEventListener('storage', this.storageListener);\n this.removeItem(this.localClientStorageKey);\n this.started = false;\n }\n }\n\n private getItem(key: string): string | null {\n const value = this.storage.getItem(key);\n logDebug(LOG_TAG, 'READ', key, value);\n return value;\n }\n\n private setItem(key: string, value: string): void {\n logDebug(LOG_TAG, 'SET', key, value);\n this.storage.setItem(key, value);\n }\n\n private removeItem(key: string): void {\n logDebug(LOG_TAG, 'REMOVE', key);\n this.storage.removeItem(key);\n }\n\n private handleWebStorageEvent(event: Event): void {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const storageEvent = event as StorageEvent;\n if (storageEvent.storageArea === this.storage) {\n logDebug(LOG_TAG, 'EVENT', storageEvent.key, storageEvent.newValue);\n\n if (storageEvent.key === this.localClientStorageKey) {\n logError(\n 'Received WebStorage notification for local change. Another client might have ' +\n 'garbage-collected our state'\n );\n return;\n }\n\n this.queue.enqueueRetryable(async () => {\n if (!this.started) {\n this.earlyEvents.push(storageEvent);\n return;\n }\n\n if (storageEvent.key === null) {\n return;\n }\n\n if (this.clientStateKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue != null) {\n const clientState = this.fromWebStorageClientState(\n storageEvent.key,\n storageEvent.newValue\n );\n if (clientState) {\n return this.handleClientStateEvent(\n clientState.clientId,\n clientState\n );\n }\n } else {\n const clientId = this.fromWebStorageClientStateKey(\n storageEvent.key\n )!;\n return this.handleClientStateEvent(clientId, null);\n }\n } else if (this.mutationBatchKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const mutationMetadata = this.fromWebStorageMutationMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (mutationMetadata) {\n return this.handleMutationBatchEvent(mutationMetadata);\n }\n }\n } else if (this.queryTargetKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (queryTargetMetadata) {\n return this.handleQueryTargetEvent(queryTargetMetadata);\n }\n }\n } else if (storageEvent.key === this.onlineStateKey) {\n if (storageEvent.newValue !== null) {\n const onlineState = this.fromWebStorageOnlineState(\n storageEvent.newValue\n );\n if (onlineState) {\n return this.handleOnlineStateEvent(onlineState);\n }\n }\n } else if (storageEvent.key === this.sequenceNumberKey) {\n debugAssert(\n !!this.sequenceNumberHandler,\n 'Missing sequenceNumberHandler'\n );\n const sequenceNumber = fromWebStorageSequenceNumber(\n storageEvent.newValue\n );\n if (sequenceNumber !== ListenSequence.INVALID) {\n this.sequenceNumberHandler!(sequenceNumber);\n }\n } else if (storageEvent.key === this.bundleLoadedKey) {\n const collectionGroups = this.fromWebStoreBundleLoadedState(\n storageEvent.newValue!\n );\n await Promise.all(\n collectionGroups.map(cg =>\n this.syncEngine!.synchronizeWithChangedDocuments(cg)\n )\n );\n }\n });\n }\n }\n\n private get localClientState(): LocalClientState {\n return this.activeClients.get(this.localClientId) as LocalClientState;\n }\n\n private persistClientState(): void {\n this.setItem(\n this.localClientStorageKey,\n this.localClientState.toWebStorageJSON()\n );\n }\n\n private persistMutationState(\n batchId: BatchId,\n state: MutationBatchState,\n error?: FirestoreError\n ): void {\n const mutationState = new MutationMetadata(\n this.currentUser,\n batchId,\n state,\n error\n );\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\n }\n\n private removeMutationState(batchId: BatchId): void {\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.removeItem(mutationKey);\n }\n\n private persistOnlineState(onlineState: OnlineState): void {\n const entry: SharedOnlineStateSchema = {\n clientId: this.localClientId,\n onlineState\n };\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n }\n\n private persistQueryTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n const targetKey = createWebStorageQueryTargetMetadataKey(\n this.persistenceKey,\n targetId\n );\n const targetMetadata = new QueryTargetMetadata(targetId, state, error);\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n }\n\n private persistBundleLoadedState(collectionGroups: Set): void {\n const json = JSON.stringify(Array.from(collectionGroups));\n this.setItem(this.bundleLoadedKey, json);\n }\n\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */\n private fromWebStorageClientStateKey(key: string): ClientId | null {\n const match = this.clientStateKeyRe.exec(key);\n return match ? match[1] : null;\n }\n\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */\n private fromWebStorageClientState(\n key: string,\n value: string\n ): RemoteClientState | null {\n const clientId = this.fromWebStorageClientStateKey(key);\n debugAssert(clientId !== null, `Cannot parse client state key '${key}'`);\n return RemoteClientState.fromWebStorageEntry(clientId, value);\n }\n\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageMutationMetadata(\n key: string,\n value: string\n ): MutationMetadata | null {\n const match = this.mutationBatchKeyRe.exec(key);\n debugAssert(match !== null, `Cannot parse mutation batch key '${key}'`);\n\n const batchId = Number(match[1]);\n const userId = match[2] !== undefined ? match[2] : null;\n return MutationMetadata.fromWebStorageEntry(\n new User(userId),\n batchId,\n value\n );\n }\n\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageQueryTargetMetadata(\n key: string,\n value: string\n ): QueryTargetMetadata | null {\n const match = this.queryTargetKeyRe.exec(key);\n debugAssert(match !== null, `Cannot parse query target key '${key}'`);\n\n const targetId = Number(match[1]);\n return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\n }\n\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageOnlineState(value: string): SharedOnlineState | null {\n return SharedOnlineState.fromWebStorageEntry(value);\n }\n\n private fromWebStoreBundleLoadedState(value: string): string[] {\n return JSON.parse(value) as string[];\n }\n\n private async handleMutationBatchEvent(\n mutationBatch: MutationMetadata\n ): Promise {\n if (mutationBatch.user.uid !== this.currentUser.uid) {\n logDebug(\n LOG_TAG,\n `Ignoring mutation for non-active user ${mutationBatch.user.uid}`\n );\n return;\n }\n\n return this.syncEngine!.applyBatchState(\n mutationBatch.batchId,\n mutationBatch.state,\n mutationBatch.error\n );\n }\n\n private handleQueryTargetEvent(\n targetMetadata: QueryTargetMetadata\n ): Promise {\n return this.syncEngine!.applyTargetState(\n targetMetadata.targetId,\n targetMetadata.state,\n targetMetadata.error\n );\n }\n\n private handleClientStateEvent(\n clientId: ClientId,\n clientState: RemoteClientState | null\n ): Promise {\n const updatedClients = clientState\n ? this.activeClients.insert(clientId, clientState)\n : this.activeClients.remove(clientId);\n\n const existingTargets = this.extractActiveQueryTargets(this.activeClients);\n const newTargets = this.extractActiveQueryTargets(updatedClients);\n\n const addedTargets: TargetId[] = [];\n const removedTargets: TargetId[] = [];\n\n newTargets.forEach(targetId => {\n if (!existingTargets.has(targetId)) {\n addedTargets.push(targetId);\n }\n });\n\n existingTargets.forEach(targetId => {\n if (!newTargets.has(targetId)) {\n removedTargets.push(targetId);\n }\n });\n\n return this.syncEngine!.applyActiveTargetsChange(\n addedTargets,\n removedTargets\n ).then(() => {\n this.activeClients = updatedClients;\n });\n }\n\n private handleOnlineStateEvent(onlineState: SharedOnlineState): void {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n if (this.activeClients.get(onlineState.clientId)) {\n this.onlineStateHandler!(onlineState.onlineState);\n }\n }\n\n private extractActiveQueryTargets(\n clients: SortedMap\n ): SortedSet {\n let activeTargets = targetIdSet();\n clients.forEach((kev, value) => {\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\n });\n return activeTargets;\n }\n}\n\nfunction fromWebStorageSequenceNumber(\n seqString: string | null\n): ListenSequenceNumber {\n let sequenceNumber = ListenSequence.INVALID;\n if (seqString != null) {\n try {\n const parsed = JSON.parse(seqString);\n hardAssert(\n typeof parsed === 'number',\n 'Found non-numeric sequence number'\n );\n sequenceNumber = parsed;\n } catch (e) {\n logError(LOG_TAG, 'Failed to read sequence number from WebStorage', e);\n }\n }\n return sequenceNumber;\n}\n\n/**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */\nexport class MemorySharedClientState implements SharedClientState {\n private localState = new LocalClientState();\n private queryState: { [targetId: number]: QueryTargetState } = {};\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n addPendingMutation(batchId: BatchId): void {\n // No op.\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n // No op.\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n this.localState.addQueryTarget(targetId);\n return this.queryState[targetId] || 'not-current';\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.queryState[targetId] = state;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localState.removeQueryTarget(targetId);\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n delete this.queryState[targetId];\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.localState.activeTargetIds;\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n start(): Promise {\n this.localState = new LocalClientState();\n return Promise.resolve();\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n // No op.\n }\n\n setOnlineState(onlineState: OnlineState): void {\n // No op.\n }\n\n shutdown(): void {}\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {}\n\n notifyBundleLoaded(collectionGroups: Set): void {\n // No op.\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\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\n\nexport class NoopConnectivityMonitor implements ConnectivityMonitor {\n addCallback(callback: (status: NetworkStatus) => void): void {\n // No-op.\n }\n\n shutdown(): void {\n // No-op.\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\nimport {\n ConnectivityMonitor,\n ConnectivityMonitorCallback,\n NetworkStatus\n} from '../../remote/connectivity_monitor';\nimport { logDebug } from '../../util/log';\n\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'ConnectivityMonitor';\n\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nexport class BrowserConnectivityMonitor implements ConnectivityMonitor {\n private readonly networkAvailableListener = (): void =>\n this.onNetworkAvailable();\n private readonly networkUnavailableListener = (): void =>\n this.onNetworkUnavailable();\n private callbacks: ConnectivityMonitorCallback[] = [];\n\n constructor() {\n this.configureNetworkMonitoring();\n }\n\n addCallback(callback: (status: NetworkStatus) => void): void {\n this.callbacks.push(callback);\n }\n\n shutdown(): void {\n window.removeEventListener('online', this.networkAvailableListener);\n window.removeEventListener('offline', this.networkUnavailableListener);\n }\n\n private configureNetworkMonitoring(): void {\n window.addEventListener('online', this.networkAvailableListener);\n window.addEventListener('offline', this.networkUnavailableListener);\n }\n\n private onNetworkAvailable(): void {\n logDebug(LOG_TAG, 'Network connectivity changed: AVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.AVAILABLE);\n }\n }\n\n private onNetworkUnavailable(): void {\n logDebug(LOG_TAG, 'Network connectivity changed: UNAVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.UNAVAILABLE);\n }\n }\n\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static isAvailable(): boolean {\n return (\n typeof window !== 'undefined' &&\n window.addEventListener !== undefined &&\n window.removeEventListener !== undefined\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\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\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 { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n return this.performRPCRequest(rpcName, url, headers, req).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\n\nimport { Stream } from './connection';\n\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nexport class StreamBridge implements Stream {\n private wrappedOnConnected: (() => void) | undefined;\n private wrappedOnOpen: (() => void) | undefined;\n private wrappedOnClose: ((err?: FirestoreError) => void) | undefined;\n private wrappedOnMessage: ((msg: O) => void) | undefined;\n\n private sendFn: (msg: I) => void;\n private closeFn: () => void;\n\n constructor(args: { sendFn: (msg: I) => void; closeFn: () => void }) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n\n onConnected(callback: () => void): void {\n debugAssert(\n !this.wrappedOnConnected,\n 'Called onConnected on stream twice!'\n );\n this.wrappedOnConnected = callback;\n }\n\n onOpen(callback: () => void): void {\n debugAssert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n }\n\n onClose(callback: (err?: FirestoreError) => void): void {\n debugAssert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n }\n\n onMessage(callback: (msg: O) => void): void {\n debugAssert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n }\n\n close(): void {\n this.closeFn();\n }\n\n send(msg: I): void {\n this.sendFn(msg);\n }\n\n callOnConnected(): void {\n debugAssert(\n this.wrappedOnConnected !== undefined,\n 'Cannot call onConnected because no callback was set'\n );\n this.wrappedOnConnected();\n }\n\n callOnOpen(): void {\n debugAssert(\n this.wrappedOnOpen !== undefined,\n 'Cannot call onOpen because no callback was set'\n );\n this.wrappedOnOpen();\n }\n\n callOnClose(err?: FirestoreError): void {\n debugAssert(\n this.wrappedOnClose !== undefined,\n 'Cannot call onClose because no callback was set'\n );\n this.wrappedOnClose(err);\n }\n\n callOnMessage(msg: O): void {\n debugAssert(\n this.wrappedOnMessage !== undefined,\n 'Cannot call onMessage because no callback was set'\n );\n this.wrappedOnMessage(msg);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 createWebChannelTransport,\n ErrorCode,\n EventType,\n WebChannel,\n WebChannelError,\n WebChannelOptions,\n XhrIo,\n getStatEventTarget,\n EventTarget,\n StatEvent,\n Event,\n FetchXmlHttpFactory,\n Stat\n} from '@firebase/webchannel-wrapper/webchannel-blob';\n\nimport { Token } from '../../api/credentials';\nimport { ExperimentalLongPollingOptions } from '../../api/long_polling_options';\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport {\n mapCodeFromRpcStatus,\n mapCodeFromHttpResponseErrorStatus\n} from '../../remote/rpc_error';\nimport { StreamBridge } from '../../remote/stream_bridge';\nimport { fail, hardAssert } from '../../util/assert';\nimport { generateUniqueDebugId } from '../../util/debug_uid';\nimport { Code, FirestoreError } from '../../util/error';\nimport { logDebug, logWarn } from '../../util/log';\nimport { Rejecter, Resolver } from '../../util/promise';\nimport { StringMap } from '../../util/types';\n\nconst LOG_TAG = 'WebChannelConnection';\n\nconst RPC_STREAM_SERVICE = 'google.firestore.v1.Firestore';\n\nconst XHR_TIMEOUT_SECS = 15;\n\nexport class WebChannelConnection extends RestConnection {\n private readonly forceLongPolling: boolean;\n private readonly autoDetectLongPolling: boolean;\n private readonly useFetchStreams: boolean;\n private readonly longPollingOptions: ExperimentalLongPollingOptions;\n\n constructor(info: DatabaseInfo) {\n super(info);\n this.forceLongPolling = info.forceLongPolling;\n this.autoDetectLongPolling = info.autoDetectLongPolling;\n this.useFetchStreams = info.useFetchStreams;\n this.longPollingOptions = info.longPollingOptions;\n }\n\n protected performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise {\n const streamId = generateUniqueDebugId();\n return new Promise((resolve: Resolver, reject: Rejecter) => {\n const xhr = new XhrIo();\n xhr.setWithCredentials(true);\n xhr.listenOnce(EventType.COMPLETE, () => {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const json = xhr.getResponseJson() as Resp;\n logDebug(\n LOG_TAG,\n `XHR for RPC '${rpcName}' ${streamId} received:`,\n JSON.stringify(json)\n );\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} timed out`);\n reject(\n new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out')\n );\n break;\n case ErrorCode.HTTP_ERROR:\n const status = xhr.getStatus();\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with status:`,\n status,\n 'response text:',\n xhr.getResponseText()\n );\n if (status > 0) {\n let response = xhr.getResponseJson();\n if (Array.isArray(response)) {\n response = response[0];\n }\n const responseError = (response as WebChannelError)?.error;\n if (\n !!responseError &&\n !!responseError.status &&\n !!responseError.message\n ) {\n const firestoreErrorCode = mapCodeFromHttpResponseErrorStatus(\n responseError.status\n );\n reject(\n new FirestoreError(\n firestoreErrorCode,\n responseError.message\n )\n );\n } else {\n reject(\n new FirestoreError(\n Code.UNKNOWN,\n 'Server responded with status ' + xhr.getStatus()\n )\n );\n }\n } else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n reject(\n new FirestoreError(Code.UNAVAILABLE, 'Connection failed.')\n );\n }\n break;\n default:\n fail(\n `RPC '${rpcName}' ${streamId} ` +\n 'failed with unanticipated webchannel error: ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.'\n );\n }\n } finally {\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} completed.`);\n }\n });\n\n const requestString = JSON.stringify(body);\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} sending request:`, body);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n }\n\n openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\n const streamId = generateUniqueDebugId();\n const urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n const webchannelTransport = createWebChannelTransport();\n const requestStats = getStatEventTarget();\n const request: WebChannelOptions = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: true,\n supportsCrossDomainXhr: true,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 10 * 60 * 1000\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n };\n\n const longPollingTimeoutSeconds = this.longPollingOptions.timeoutSeconds;\n if (longPollingTimeoutSeconds !== undefined) {\n request.longPollingTimeout = Math.round(longPollingTimeoutSeconds * 1000);\n }\n\n if (this.useFetchStreams) {\n request.xmlHttpFactory = new FetchXmlHttpFactory({});\n }\n\n this.modifyHeadersForRequest(\n request.initMessageHeaders!,\n authToken,\n appCheckToken\n );\n\n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n //\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n request.encodeInitMessageHeaders = true;\n\n const url = urlParts.join('');\n logDebug(\n LOG_TAG,\n `Creating RPC '${rpcName}' stream ${streamId}: ${url}`,\n request\n );\n const channel = webchannelTransport.createWebChannel(url, request);\n\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let opened = false;\n\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n let closed = false;\n\n const streamBridge = new StreamBridge({\n sendFn: (msg: Req) => {\n if (!closed) {\n if (!opened) {\n logDebug(\n LOG_TAG,\n `Opening RPC '${rpcName}' stream ${streamId} transport.`\n );\n channel.open();\n opened = true;\n }\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} sending:`,\n msg\n );\n channel.send(msg);\n } else {\n logDebug(\n LOG_TAG,\n `Not sending because RPC '${rpcName}' stream ${streamId} ` +\n 'is closed:',\n msg\n );\n }\n },\n closeFn: () => channel.close()\n });\n\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n const unguardedEventListen = (\n target: EventTarget,\n type: string | number,\n fn: (param: T) => void\n ): void => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n target.listen(type, (param: unknown) => {\n try {\n fn(param as T);\n } catch (e) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n });\n };\n\n unguardedEventListen(channel, WebChannel.EventType.OPEN, () => {\n if (!closed) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport opened.`\n );\n streamBridge.callOnConnected();\n }\n });\n\n unguardedEventListen(channel, WebChannel.EventType.CLOSE, () => {\n if (!closed) {\n closed = true;\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport closed`\n );\n streamBridge.callOnClose();\n }\n });\n\n unguardedEventListen(channel, WebChannel.EventType.ERROR, err => {\n if (!closed) {\n closed = true;\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport errored:`,\n err\n );\n streamBridge.callOnClose(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'The operation could not be completed'\n )\n );\n }\n });\n\n // WebChannel delivers message events as array. If batching is not enabled\n // (it's off by default) each message will be delivered alone, resulting in\n // a single element array.\n interface WebChannelResponse {\n data: Resp[];\n }\n\n unguardedEventListen(\n channel,\n WebChannel.EventType.MESSAGE,\n msg => {\n if (!closed) {\n const msgData = msg.data[0];\n hardAssert(!!msgData, 'Got a webchannel message without data.');\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const msgDataOrError: WebChannelError | object = msgData;\n const error =\n msgDataOrError.error ||\n (msgDataOrError as WebChannelError[])[0]?.error;\n if (error) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received error:`,\n error\n );\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const status: string = error.status;\n let code = mapCodeFromRpcStatus(status);\n let message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n } else {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received:`,\n msgData\n );\n streamBridge.callOnMessage(msgData);\n }\n }\n }\n );\n\n unguardedEventListen(requestStats, Event.STAT_EVENT, event => {\n if (event.stat === Stat.PROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected buffering proxy`\n );\n } else if (event.stat === Stat.NOPROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected no buffering proxy`\n );\n }\n });\n\n setTimeout(() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\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/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\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/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ 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 { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider, Token } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetData } from '../local/target_data';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport {\n ListenRequest as ProtoListenRequest,\n ListenResponse as ProtoListenResponse,\n WriteRequest as ProtoWriteRequest,\n WriteResponse as ProtoWriteResponse\n} from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExponentialBackoff } from './backoff';\nimport { Connection, Stream } from './connection';\nimport {\n fromVersion,\n fromWatchChange,\n fromWriteResults,\n getEncodedDatabaseId,\n JsonProtoSerializer,\n toListenRequestLabels,\n toMutation,\n toTarget,\n versionFromListenResponse\n} from './serializer';\nimport { WatchChange } from './watch_change';\n\nconst LOG_TAG = 'PersistentStream';\n\n// The generated proto interfaces for these class are missing the database\n// field. So we add it here.\n// TODO(b/36015800): Remove this once the api generator is fixed.\ninterface ListenRequest extends ProtoListenRequest {\n database?: string;\n}\nexport interface WriteRequest extends ProtoWriteRequest {\n database?: string;\n}\n/**\n * PersistentStream can be in one of 5 states (each described in detail below)\n * based on the following state transition diagram:\n *\n * start() called auth & connection succeeded\n * INITIAL ----------------> STARTING -----------------------------> OPEN\n * ^ | |\n * | | error occurred |\n * | \\-----------------------------v-----/\n * | |\n * backoff | |\n * elapsed | start() called |\n * \\--- BACKOFF <---------------- ERROR\n *\n * [any state] --------------------------> INITIAL\n * stop() called or\n * idle timer expired\n */\nconst enum PersistentStreamState {\n /**\n * The streaming RPC is not yet running and there's no error condition.\n * Calling start() will start the stream immediately without backoff.\n * While in this state isStarted() will return false.\n */\n Initial,\n\n /**\n * The stream is starting, either waiting for an auth token or for the stream\n * to successfully open. While in this state, isStarted() will return true but\n * isOpen() will return false.\n */\n Starting,\n\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted() and isOpen() will return true.\n */\n Open,\n\n /**\n * The stream is healthy and has been connected for more than 10 seconds. We\n * therefore assume that the credentials we passed were valid. Both\n * isStarted() and isOpen() will return true.\n */\n Healthy,\n\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n */\n Error,\n\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After waiting is complete, the stream will try to open.\n * While in this state isStarted() will return true but isOpen() will return\n * false.\n */\n Backoff\n}\n\n/**\n * Provides a common interface that is shared by the listeners for stream\n * events by the concrete implementation classes.\n */\nexport interface PersistentStreamListener {\n /**\n * Called after receiving an acknowledgement from the server, confirming that\n * we are able to connect to it.\n */\n onConnected: () => Promise;\n /**\n * Called after the stream was established and can accept outgoing\n * messages\n */\n onOpen: () => Promise;\n /**\n * Called after the stream has closed. If there was an error, the\n * FirestoreError will be set.\n */\n onClose: (err?: FirestoreError) => Promise;\n}\n\n/** The time a stream stays open after it is marked idle. */\nconst IDLE_TIMEOUT_MS = 60 * 1000;\n\n/** The time a stream stays open until we consider it healthy. */\nconst HEALTHY_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nexport abstract class PersistentStream<\n SendType,\n ReceiveType,\n ListenerType extends PersistentStreamListener\n> {\n private state = PersistentStreamState.Initial;\n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n private closeCount = 0;\n\n private idleTimer: DelayedOperation | null = null;\n private healthCheck: DelayedOperation | null = null;\n private stream: Stream | null = null;\n\n protected backoff: ExponentialBackoff;\n\n constructor(\n private queue: AsyncQueue,\n connectionTimerId: TimerId,\n private idleTimerId: TimerId,\n private healthTimerId: TimerId,\n protected connection: Connection,\n private authCredentialsProvider: CredentialsProvider,\n private appCheckCredentialsProvider: CredentialsProvider,\n protected listener: ListenerType\n ) {\n this.backoff = new ExponentialBackoff(queue, connectionTimerId);\n }\n\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */\n isStarted(): boolean {\n return (\n this.state === PersistentStreamState.Starting ||\n this.state === PersistentStreamState.Backoff ||\n this.isOpen()\n );\n }\n\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */\n isOpen(): boolean {\n return (\n this.state === PersistentStreamState.Open ||\n this.state === PersistentStreamState.Healthy\n );\n }\n\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */\n start(): void {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n\n debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Already started'\n );\n this.auth();\n }\n\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */\n async stop(): Promise {\n if (this.isStarted()) {\n await this.close(PersistentStreamState.Initial);\n }\n }\n\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */\n inhibitBackoff(): void {\n debugAssert(\n !this.isStarted(),\n 'Can only inhibit backoff in a stopped state'\n );\n\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n }\n\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */\n markIdle(): void {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n if (this.isOpen() && this.idleTimer === null) {\n this.idleTimer = this.queue.enqueueAfterDelay(\n this.idleTimerId,\n IDLE_TIMEOUT_MS,\n () => this.handleIdleCloseTimer()\n );\n }\n }\n\n /** Sends a message to the underlying stream. */\n protected sendRequest(msg: SendType): void {\n this.cancelIdleCheck();\n this.stream!.send(msg);\n }\n\n /** Called by the idle timer when the stream should close due to inactivity. */\n private async handleIdleCloseTimer(): Promise {\n if (this.isOpen()) {\n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(PersistentStreamState.Initial);\n }\n }\n\n /** Marks the stream as active again. */\n private cancelIdleCheck(): void {\n if (this.idleTimer) {\n this.idleTimer.cancel();\n this.idleTimer = null;\n }\n }\n\n /** Cancels the health check delayed operation. */\n private cancelHealthCheck(): void {\n if (this.healthCheck) {\n this.healthCheck.cancel();\n this.healthCheck = null;\n }\n }\n\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */\n private async close(\n finalState: PersistentStreamState,\n error?: FirestoreError\n ): Promise {\n debugAssert(this.isStarted(), 'Only started streams should be closed.');\n debugAssert(\n finalState === PersistentStreamState.Error || isNullOrUndefined(error),\n \"Can't provide an error when not in an error state.\"\n );\n\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.cancelIdleCheck();\n this.cancelHealthCheck();\n this.backoff.cancel();\n\n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.closeCount++;\n\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n } else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n logError(error.toString());\n logError(\n 'Using maximum backoff delay to prevent overloading the backend.'\n );\n this.backoff.resetToMax();\n } else if (\n error &&\n error.code === Code.UNAUTHENTICATED &&\n this.state !== PersistentStreamState.Healthy\n ) {\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken();\n this.appCheckCredentialsProvider.invalidateToken();\n }\n\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\n\n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = finalState;\n\n // Notify the listener that the stream closed.\n await this.listener.onClose(error);\n }\n\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n protected tearDown(): void {}\n\n /**\n * Used by subclasses to start the concrete RPC and return the underlying\n * connection stream.\n */\n protected abstract startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Called after the stream has received a message. The function will be\n * called on the right queue and must return a Promise.\n * @param message - The message received from the stream.\n */\n protected abstract onMessage(message: ReceiveType): Promise;\n\n private auth(): void {\n debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Must be in initial state to auth'\n );\n\n this.state = PersistentStreamState.Starting;\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n const closeCount = this.closeCount;\n\n Promise.all([\n this.authCredentialsProvider.getToken(),\n this.appCheckCredentialsProvider.getToken()\n ]).then(\n ([authToken, appCheckToken]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n if (this.closeCount === closeCount) {\n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.startStream(authToken, appCheckToken);\n }\n },\n (error: Error) => {\n dispatchIfNotClosed(() => {\n const rpcError = new FirestoreError(\n Code.UNKNOWN,\n 'Fetching auth token failed: ' + error.message\n );\n return this.handleStreamClose(rpcError);\n });\n }\n );\n }\n\n private startStream(\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Trying to start stream in a non-starting state'\n );\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n this.stream = this.startRpc(authToken, appCheckToken);\n this.stream.onConnected(() => {\n dispatchIfNotClosed(() => this.listener!.onConnected());\n });\n this.stream.onOpen(() => {\n dispatchIfNotClosed(() => {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Expected stream to be in state Starting, but was ' + this.state\n );\n this.state = PersistentStreamState.Open;\n debugAssert(\n this.healthCheck === null,\n 'Expected healthCheck to be null'\n );\n this.healthCheck = this.queue.enqueueAfterDelay(\n this.healthTimerId,\n HEALTHY_TIMEOUT_MS,\n () => {\n if (this.isOpen()) {\n this.state = PersistentStreamState.Healthy;\n }\n return Promise.resolve();\n }\n );\n return this.listener!.onOpen();\n });\n });\n this.stream.onClose((error?: FirestoreError) => {\n dispatchIfNotClosed(() => {\n return this.handleStreamClose(error);\n });\n });\n this.stream.onMessage((msg: ReceiveType) => {\n dispatchIfNotClosed(() => {\n return this.onMessage(msg);\n });\n });\n }\n\n private performBackoff(): void {\n debugAssert(\n this.state === PersistentStreamState.Error,\n 'Should only perform backoff when in Error state'\n );\n this.state = PersistentStreamState.Backoff;\n\n this.backoff.backoffAndRun(async () => {\n debugAssert(\n this.state === PersistentStreamState.Backoff,\n 'Backoff elapsed but state is now: ' + this.state\n );\n\n this.state = PersistentStreamState.Initial;\n this.start();\n debugAssert(this.isStarted(), 'PersistentStream should have started');\n });\n }\n\n // Visible for tests\n handleStreamClose(error?: FirestoreError): Promise {\n debugAssert(\n this.isStarted(),\n \"Can't handle server close on non-started stream\"\n );\n logDebug(LOG_TAG, `close with error: ${error}`);\n\n this.stream = null;\n\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return this.close(PersistentStreamState.Error, error);\n }\n\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */\n private getCloseGuardedDispatcher(\n startCloseCount: number\n ): (fn: () => Promise) => void {\n return (fn: () => Promise): void => {\n this.queue.enqueueAndForget(() => {\n if (this.closeCount === startCloseCount) {\n return fn();\n } else {\n logDebug(\n LOG_TAG,\n 'stream callback skipped by getCloseGuardedDispatcher.'\n );\n return Promise.resolve();\n }\n });\n };\n }\n}\n\n/** Listener for the PersistentWatchStream */\nexport interface WatchStreamListener extends PersistentStreamListener {\n /**\n * Called on a watchChange. The snapshot parameter will be MIN if the watch\n * change did not have a snapshot associated with it.\n */\n onWatchChange: (\n watchChange: WatchChange,\n snapshot: SnapshotVersion\n ) => Promise;\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */\nexport class PersistentListenStream extends PersistentStream<\n ProtoListenRequest,\n ProtoListenResponse,\n WatchStreamListener\n> {\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n private serializer: JsonProtoSerializer,\n listener: WatchStreamListener\n ) {\n super(\n queue,\n TimerId.ListenStreamConnectionBackoff,\n TimerId.ListenStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\n return this.connection.openStream(\n 'Listen',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(watchChangeProto: ProtoListenResponse): Promise {\n // A successful response means the stream is healthy\n this.backoff.reset();\n\n const watchChange = fromWatchChange(this.serializer, watchChangeProto);\n const snapshot = versionFromListenResponse(watchChangeProto);\n return this.listener!.onWatchChange(watchChange, snapshot);\n }\n\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n watch(targetData: TargetData): void {\n const request: ListenRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n request.addTarget = toTarget(this.serializer, targetData);\n\n const labels = toListenRequestLabels(this.serializer, targetData);\n if (labels) {\n request.labels = labels;\n }\n\n this.sendRequest(request);\n }\n\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */\n unwatch(targetId: TargetId): void {\n const request: ListenRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n request.removeTarget = targetId;\n this.sendRequest(request);\n }\n}\n\n/** Listener for the PersistentWriteStream */\nexport interface WriteStreamListener extends PersistentStreamListener {\n /**\n * Called by the PersistentWriteStream upon a successful handshake response\n * from the server, which is the receiver's cue to send any pending writes.\n */\n onHandshakeComplete: () => Promise;\n\n /**\n * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse\n * from the server that contains a mutation result.\n */\n onMutationResult: (\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ) => Promise;\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */\nexport class PersistentWriteStream extends PersistentStream<\n ProtoWriteRequest,\n ProtoWriteResponse,\n WriteStreamListener\n> {\n private handshakeComplete_ = false;\n\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n private serializer: JsonProtoSerializer,\n listener: WriteStreamListener\n ) {\n super(\n queue,\n TimerId.WriteStreamConnectionBackoff,\n TimerId.WriteStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n /**\n * The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n *\n * PersistentWriteStream manages propagating this value from responses to the\n * next request.\n */\n private lastStreamToken: string | Uint8Array | undefined;\n\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get handshakeComplete(): boolean {\n return this.handshakeComplete_;\n }\n\n // Override of PersistentStream.start\n start(): void {\n this.handshakeComplete_ = false;\n this.lastStreamToken = undefined;\n super.start();\n }\n\n protected tearDown(): void {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\n return this.connection.openStream(\n 'Write',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(responseProto: ProtoWriteResponse): Promise {\n // Always capture the last stream token.\n hardAssert(\n !!responseProto.streamToken,\n 'Got a write response without a stream token'\n );\n this.lastStreamToken = responseProto.streamToken;\n\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n hardAssert(\n !responseProto.writeResults || responseProto.writeResults.length === 0,\n 'Got mutation results for handshake'\n );\n this.handshakeComplete_ = true;\n return this.listener!.onHandshakeComplete();\n } else {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.backoff.reset();\n\n const results = fromWriteResults(\n responseProto.writeResults,\n responseProto.commitTime\n );\n const commitVersion = fromVersion(responseProto.commitTime!);\n return this.listener!.onMutationResult(commitVersion, results);\n }\n }\n\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */\n writeHandshake(): void {\n debugAssert(this.isOpen(), 'Writing handshake requires an opened stream');\n debugAssert(!this.handshakeComplete_, 'Handshake already completed');\n debugAssert(\n !this.lastStreamToken,\n 'Stream token should be empty during handshake'\n );\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const request: WriteRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n this.sendRequest(request);\n }\n\n /** Sends a group of mutations to the Firestore backend to apply. */\n writeMutations(mutations: Mutation[]): void {\n debugAssert(this.isOpen(), 'Writing mutations requires an opened stream');\n debugAssert(\n this.handshakeComplete_,\n 'Handshake must be complete before writing mutations'\n );\n debugAssert(\n !!this.lastStreamToken,\n 'Trying to write mutation without a token'\n );\n\n const request: WriteRequest = {\n streamToken: this.lastStreamToken,\n writes: mutations.map(mutation => toMutation(this.serializer, mutation))\n };\n\n this.sendRequest(request);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider,\n readonly appCheckCredentials: CredentialsProvider,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnlineState } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\n\nconst LOG_TAG = 'OnlineStateTracker';\n\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\n// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394.\n// @jdimond thinks that bug is sufficiently fixed so that we can set this back\n// to 1. If that works okay, we could potentially remove this logic entirely.\nconst MAX_WATCH_STREAM_FAILURES = 1;\n\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nconst ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nexport class OnlineStateTracker {\n /** The current OnlineState. */\n private state = OnlineState.Unknown;\n\n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n private watchStreamFailures = 0;\n\n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n private onlineStateTimer: DelayedOperation | null = null;\n\n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n private shouldWarnClientIsOffline = true;\n\n constructor(\n private asyncQueue: AsyncQueue,\n private onlineStateHandler: (onlineState: OnlineState) => void\n ) {}\n\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */\n handleWatchStreamStart(): void {\n if (this.watchStreamFailures === 0) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n debugAssert(\n this.onlineStateTimer === null,\n `onlineStateTimer shouldn't be started yet`\n );\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(\n TimerId.OnlineStateTimeout,\n ONLINE_STATE_TIMEOUT_MS,\n () => {\n this.onlineStateTimer = null;\n debugAssert(\n this.state === OnlineState.Unknown,\n 'Timer should be canceled if we transitioned to a different state.'\n );\n this.logClientOfflineWarningIfNecessary(\n `Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` +\n `seconds.`\n );\n this.setAndBroadcast(OnlineState.Offline);\n\n // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n\n return Promise.resolve();\n }\n );\n }\n }\n\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */\n handleWatchStreamFailure(error: FirestoreError): void {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n // To get to OnlineState.Online, set() must have been called which would\n // have reset our heuristics.\n debugAssert(\n this.watchStreamFailures === 0,\n 'watchStreamFailures must be 0'\n );\n debugAssert(\n this.onlineStateTimer === null,\n 'onlineStateTimer must be null'\n );\n } else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n\n this.logClientOfflineWarningIfNecessary(\n `Connection failed ${MAX_WATCH_STREAM_FAILURES} ` +\n `times. Most recent error: ${error.toString()}`\n );\n\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\n }\n\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */\n set(newState: OnlineState): void {\n this.clearOnlineStateTimer();\n this.watchStreamFailures = 0;\n\n if (newState === OnlineState.Online) {\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.shouldWarnClientIsOffline = false;\n }\n\n this.setAndBroadcast(newState);\n }\n\n private setAndBroadcast(newState: OnlineState): void {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n }\n\n private logClientOfflineWarningIfNecessary(details: string): void {\n const message =\n `Could not reach Cloud Firestore backend. ${details}\\n` +\n `This typically indicates that your device does not have a healthy ` +\n `Internet connection at the moment. The client will operate in offline ` +\n `mode until it is able to successfully connect to the backend.`;\n if (this.shouldWarnClientIsOffline) {\n logError(message);\n this.shouldWarnClientIsOffline = false;\n } else {\n logDebug(LOG_TAG, message);\n }\n }\n\n private clearOnlineStateTimer(): void {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = 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 { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { OnlineState, TargetId } from '../core/types';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreGetLastRemoteSnapshotVersion,\n localStoreGetNextMutationBatch\n} from '../local/local_store_impl';\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { TargetData } from '../local/target_data';\nimport { MutationResult } from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { debugAssert, debugCast } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\nimport {\n Datastore,\n newPersistentWatchStream,\n newPersistentWriteStream\n} from './datastore';\nimport { OnlineStateTracker } from './online_state_tracker';\nimport {\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\nimport { RemoteSyncer } from './remote_syncer';\nimport { isPermanentWriteError } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchChangeAggregator,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst LOG_TAG = 'RemoteStore';\n\n// TODO(b/35853402): Negotiate this with the stream.\nconst MAX_PENDING_WRITES = 10;\n\n/** Reasons for why the RemoteStore may be offline. */\nconst enum OfflineCause {\n /** The user has explicitly disabled the network (via `disableNetwork()`). */\n UserDisabled,\n /** An IndexedDb failure occurred while persisting a stream update. */\n IndexedDbFailed,\n /** The tab is not the primary tab (only relevant with multi-tab). */\n IsSecondary,\n /** We are restarting the streams due to an Auth credential change. */\n CredentialChange,\n /** The connectivity state of the environment has changed. */\n ConnectivityChange,\n /** The RemoteStore has been shut down. */\n Shutdown\n}\n\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nexport interface RemoteStore {\n /**\n * SyncEngine to notify of watch and write events. This must be set\n * immediately after construction.\n */\n remoteSyncer: RemoteSyncer;\n}\n\nclass RemoteStoreImpl implements RemoteStore {\n remoteSyncer: RemoteSyncer = {};\n\n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n writePipeline: MutationBatch[] = [];\n\n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n listenTargets = new Map();\n\n connectivityMonitor: ConnectivityMonitor;\n watchStream?: PersistentListenStream;\n writeStream?: PersistentWriteStream;\n watchChangeAggregator?: WatchChangeAggregator;\n\n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n offlineCauses = new Set();\n\n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n onNetworkStatusChange: Array<(enabled: boolean) => Promise> = [];\n\n onlineStateTracker: OnlineStateTracker;\n\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n readonly localStore: LocalStore,\n /** The client-side proxy for interacting with the backend. */\n readonly datastore: Datastore,\n readonly asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n ) {\n this.connectivityMonitor = connectivityMonitor;\n this.connectivityMonitor.addCallback((_: NetworkStatus) => {\n asyncQueue.enqueueAndForget(async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n if (canUseNetwork(this)) {\n logDebug(\n LOG_TAG,\n 'Restarting streams for network reachability change.'\n );\n await restartNetwork(this);\n }\n });\n });\n\n this.onlineStateTracker = new OnlineStateTracker(\n asyncQueue,\n onlineStateHandler\n );\n }\n}\n\nexport function newRemoteStore(\n localStore: LocalStore,\n datastore: Datastore,\n asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n): RemoteStore {\n return new RemoteStoreImpl(\n localStore,\n datastore,\n asyncQueue,\n onlineStateHandler,\n connectivityMonitor\n );\n}\n\n/** Re-enables the network. Idempotent. */\nexport function remoteStoreEnableNetwork(\n remoteStore: RemoteStore\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.UserDisabled);\n return enableNetworkInternal(remoteStoreImpl);\n}\n\nasync function enableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n if (canUseNetwork(remoteStoreImpl)) {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ true);\n }\n }\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\nexport async function remoteStoreDisableNetwork(\n remoteStore: RemoteStore\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.UserDisabled);\n await disableNetworkInternal(remoteStoreImpl);\n\n // Set the OnlineState to Offline so get()s return from cache, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n}\n\nasync function disableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ false);\n }\n}\n\nexport async function remoteStoreShutdown(\n remoteStore: RemoteStore\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n logDebug(LOG_TAG, 'RemoteStore shutting down.');\n remoteStoreImpl.offlineCauses.add(OfflineCause.Shutdown);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.connectivityMonitor.shutdown();\n\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nexport function remoteStoreListen(\n remoteStore: RemoteStore,\n targetData: TargetData\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n\n if (remoteStoreImpl.listenTargets.has(targetData.targetId)) {\n return;\n }\n\n // Mark this as something the client is currently listening for.\n remoteStoreImpl.listenTargets.set(targetData.targetId, targetData);\n\n if (shouldStartWatchStream(remoteStoreImpl)) {\n // The listen will be sent in onWatchStreamOpen\n startWatchStream(remoteStoreImpl);\n } else if (ensureWatchStream(remoteStoreImpl).isOpen()) {\n sendWatchRequest(remoteStoreImpl, targetData);\n }\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */\nexport function remoteStoreUnlisten(\n remoteStore: RemoteStore,\n targetId: TargetId\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const watchStream = ensureWatchStream(remoteStoreImpl);\n\n debugAssert(\n remoteStoreImpl.listenTargets.has(targetId),\n `unlisten called on target no currently watched: ${targetId}`\n );\n\n remoteStoreImpl.listenTargets.delete(targetId);\n if (watchStream.isOpen()) {\n sendUnwatchRequest(remoteStoreImpl, targetId);\n }\n\n if (remoteStoreImpl.listenTargets.size === 0) {\n if (watchStream.isOpen()) {\n watchStream.markIdle();\n } else if (canUseNetwork(remoteStoreImpl)) {\n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */\nfunction sendWatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetData: TargetData\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(\n targetData.targetId\n );\n\n if (\n targetData.resumeToken.approximateByteSize() > 0 ||\n targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0\n ) {\n const expectedCount = remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(\n targetData.targetId\n ).size;\n targetData = targetData.withExpectedCount(expectedCount);\n }\n\n ensureWatchStream(remoteStoreImpl).watch(targetData);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */\nfunction sendUnwatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetId: TargetId\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(targetId);\n ensureWatchStream(remoteStoreImpl).unwatch(targetId);\n}\n\nfunction startWatchStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWatchStream(remoteStoreImpl),\n 'startWatchStream() called when shouldStartWatchStream() is false.'\n );\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget,\n 'getRemoteKeysForTarget() not set'\n );\n\n remoteStoreImpl.watchChangeAggregator = new WatchChangeAggregator({\n getRemoteKeysForTarget: targetId =>\n remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(targetId),\n getTargetDataForTarget: targetId =>\n remoteStoreImpl.listenTargets.get(targetId) || null,\n getDatabaseId: () => remoteStoreImpl.datastore.serializer.databaseId\n });\n ensureWatchStream(remoteStoreImpl).start();\n remoteStoreImpl.onlineStateTracker.handleWatchStreamStart();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */\nfunction shouldStartWatchStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWatchStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.listenTargets.size > 0\n );\n}\n\nexport function canUseNetwork(remoteStore: RemoteStore): boolean {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.offlineCauses.size === 0;\n}\n\nfunction cleanUpWatchStreamState(remoteStoreImpl: RemoteStoreImpl): void {\n remoteStoreImpl.watchChangeAggregator = undefined;\n}\n\nasync function onWatchStreamConnected(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n // Mark the client as online since we got a \"connected\" notification.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Online);\n}\n\nasync function onWatchStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n remoteStoreImpl.listenTargets.forEach((targetData, targetId) => {\n sendWatchRequest(remoteStoreImpl, targetData);\n });\n}\n\nasync function onWatchStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWatchStream(remoteStoreImpl),\n 'Watch stream was stopped gracefully while still needed.'\n );\n }\n\n cleanUpWatchStreamState(remoteStoreImpl);\n\n // If we still need the watch stream, retry the connection.\n if (shouldStartWatchStream(remoteStoreImpl)) {\n remoteStoreImpl.onlineStateTracker.handleWatchStreamFailure(error!);\n\n startWatchStream(remoteStoreImpl);\n } else {\n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\nasync function onWatchStreamChange(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchChange,\n snapshotVersion: SnapshotVersion\n): Promise {\n // Mark the client as online since we got a message from the server\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Online);\n\n if (\n watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause\n ) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await handleTargetError(remoteStoreImpl, watchChange);\n } catch (e) {\n logDebug(\n LOG_TAG,\n 'Failed to remove targets %s: %s ',\n watchChange.targetIds.join(','),\n e\n );\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n return;\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n remoteStoreImpl.watchChangeAggregator!.handleDocumentChange(watchChange);\n } else if (watchChange instanceof ExistenceFilterChange) {\n remoteStoreImpl.watchChangeAggregator!.handleExistenceFilter(watchChange);\n } else {\n debugAssert(\n watchChange instanceof WatchTargetChange,\n 'Expected watchChange to be an instance of WatchTargetChange'\n );\n remoteStoreImpl.watchChangeAggregator!.handleTargetChange(watchChange);\n }\n\n if (!snapshotVersion.isEqual(SnapshotVersion.min())) {\n try {\n const lastRemoteSnapshotVersion =\n await localStoreGetLastRemoteSnapshotVersion(\n remoteStoreImpl.localStore\n );\n if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0) {\n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await raiseWatchSnapshot(remoteStoreImpl, snapshotVersion);\n }\n } catch (e) {\n logDebug(LOG_TAG, 'Failed to raise snapshot:', e);\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */\nasync function disableNetworkUntilRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n e: FirestoreError,\n op?: () => Promise\n): Promise {\n if (isIndexedDbTransactionError(e)) {\n debugAssert(\n !remoteStoreImpl.offlineCauses.has(OfflineCause.IndexedDbFailed),\n 'Unexpected network event when IndexedDB was marked failed.'\n );\n remoteStoreImpl.offlineCauses.add(OfflineCause.IndexedDbFailed);\n\n // Disable network and raise offline snapshots\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n\n if (!op) {\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n op = () =>\n localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore);\n }\n\n // Probe IndexedDB periodically and re-enable network\n remoteStoreImpl.asyncQueue.enqueueRetryable(async () => {\n logDebug(LOG_TAG, 'Retrying IndexedDB access');\n await op!();\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IndexedDbFailed);\n await enableNetworkInternal(remoteStoreImpl);\n });\n } else {\n throw e;\n }\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */\nfunction executeWithRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n op: () => Promise\n): Promise {\n return op().catch(e => disableNetworkUntilRecovery(remoteStoreImpl, e, op));\n}\n\n/**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\nfunction raiseWatchSnapshot(\n remoteStoreImpl: RemoteStoreImpl,\n snapshotVersion: SnapshotVersion\n): Promise {\n debugAssert(\n !snapshotVersion.isEqual(SnapshotVersion.min()),\n \"Can't raise event for unknown SnapshotVersion\"\n );\n const remoteEvent =\n remoteStoreImpl.watchChangeAggregator!.createRemoteEvent(snapshotVersion);\n\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n remoteEvent.targetChanges.forEach((change, targetId) => {\n if (change.resumeToken.approximateByteSize() > 0) {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n // A watched target might have been removed already.\n if (targetData) {\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(change.resumeToken, snapshotVersion)\n );\n }\n }\n });\n\n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n remoteEvent.targetMismatches.forEach((targetId, targetPurpose) => {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n if (!targetData) {\n // A watched target might have been removed already.\n return;\n }\n\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n targetData.snapshotVersion\n )\n );\n\n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n sendUnwatchRequest(remoteStoreImpl, targetId);\n\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const requestTargetData = new TargetData(\n targetData.target,\n targetId,\n targetPurpose,\n targetData.sequenceNumber\n );\n sendWatchRequest(remoteStoreImpl, requestTargetData);\n });\n\n // Finally raise remote event\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applyRemoteEvent,\n 'applyRemoteEvent() not set'\n );\n return remoteStoreImpl.remoteSyncer.applyRemoteEvent(remoteEvent);\n}\n\n/** Handles an error on a target */\nasync function handleTargetError(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchTargetChange\n): Promise {\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectListen,\n 'rejectListen() not set'\n );\n debugAssert(!!watchChange.cause, 'Handling target error without a cause');\n const error = watchChange.cause!;\n for (const targetId of watchChange.targetIds) {\n // A watched target might have been removed already.\n if (remoteStoreImpl.listenTargets.has(targetId)) {\n await remoteStoreImpl.remoteSyncer.rejectListen(targetId, error);\n remoteStoreImpl.listenTargets.delete(targetId);\n remoteStoreImpl.watchChangeAggregator!.removeTarget(targetId);\n }\n }\n}\n\n/**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */\nexport async function fillWritePipeline(\n remoteStore: RemoteStore\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const writeStream = ensureWriteStream(remoteStoreImpl);\n\n let lastBatchIdRetrieved =\n remoteStoreImpl.writePipeline.length > 0\n ? remoteStoreImpl.writePipeline[remoteStoreImpl.writePipeline.length - 1]\n .batchId\n : BATCHID_UNKNOWN;\n\n while (canAddToWritePipeline(remoteStoreImpl)) {\n try {\n const batch = await localStoreGetNextMutationBatch(\n remoteStoreImpl.localStore,\n lastBatchIdRetrieved\n );\n\n if (batch === null) {\n if (remoteStoreImpl.writePipeline.length === 0) {\n writeStream.markIdle();\n }\n break;\n } else {\n lastBatchIdRetrieved = batch.batchId;\n addToWritePipeline(remoteStoreImpl, batch);\n }\n } catch (e) {\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */\nfunction canAddToWritePipeline(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n remoteStoreImpl.writePipeline.length < MAX_PENDING_WRITES\n );\n}\n\n// For testing\nexport function outstandingWrites(remoteStore: RemoteStore): number {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.writePipeline.length;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */\nfunction addToWritePipeline(\n remoteStoreImpl: RemoteStoreImpl,\n batch: MutationBatch\n): void {\n debugAssert(\n canAddToWritePipeline(remoteStoreImpl),\n 'addToWritePipeline called when pipeline is full'\n );\n remoteStoreImpl.writePipeline.push(batch);\n\n const writeStream = ensureWriteStream(remoteStoreImpl);\n if (writeStream.isOpen() && writeStream.handshakeComplete) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nfunction shouldStartWriteStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWriteStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.writePipeline.length > 0\n );\n}\n\nfunction startWriteStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWriteStream(remoteStoreImpl),\n 'startWriteStream() called when shouldStartWriteStream() is false.'\n );\n ensureWriteStream(remoteStoreImpl).start();\n}\n\nasync function onWriteStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n ensureWriteStream(remoteStoreImpl).writeHandshake();\n}\n\nasync function onWriteHandshakeComplete(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n const writeStream = ensureWriteStream(remoteStoreImpl);\n // Send the write pipeline now that the stream is established.\n for (const batch of remoteStoreImpl.writePipeline) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nasync function onMutationResult(\n remoteStoreImpl: RemoteStoreImpl,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n): Promise {\n // This is a response to a write containing mutations and should be\n // correlated to the first write in our write pipeline.\n debugAssert(\n remoteStoreImpl.writePipeline.length > 0,\n 'Got result for empty write pipeline'\n );\n const batch = remoteStoreImpl.writePipeline.shift()!;\n const success = MutationBatchResult.from(batch, commitVersion, results);\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applySuccessfulWrite,\n 'applySuccessfulWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.applySuccessfulWrite!(success)\n );\n\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n}\n\nasync function onWriteStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWriteStream(remoteStoreImpl),\n 'Write stream was stopped gracefully while still needed.'\n );\n }\n\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n if (error && ensureWriteStream(remoteStoreImpl).handshakeComplete) {\n // This error affects the actual write.\n await handleWriteError(remoteStoreImpl, error!);\n }\n\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\nasync function handleWriteError(\n remoteStoreImpl: RemoteStoreImpl,\n error: FirestoreError\n): Promise {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (isPermanentWriteError(error.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const batch = remoteStoreImpl.writePipeline.shift()!;\n\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n ensureWriteStream(remoteStoreImpl).inhibitBackoff();\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectFailedWrite,\n 'rejectFailedWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.rejectFailedWrite!(batch.batchId, error)\n );\n\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n // Transient error, just let the retry logic kick in.\n }\n}\n\nasync function restartNetwork(remoteStore: RemoteStore): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.ConnectivityChange);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.ConnectivityChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\nexport async function remoteStoreHandleCredentialChange(\n remoteStore: RemoteStore,\n user: User\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.asyncQueue.verifyOperationInProgress();\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.handleCredentialChange,\n 'handleCredentialChange() not set'\n );\n\n logDebug(LOG_TAG, 'RemoteStore received new credentials');\n const usesNetwork = canUseNetwork(remoteStoreImpl);\n\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n remoteStoreImpl.offlineCauses.add(OfflineCause.CredentialChange);\n await disableNetworkInternal(remoteStoreImpl);\n if (usesNetwork) {\n // Don't set the network status to Unknown if we are offline.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n await remoteStoreImpl.remoteSyncer.handleCredentialChange(user);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.CredentialChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */\nexport async function remoteStoreApplyPrimaryState(\n remoteStore: RemoteStore,\n isPrimary: boolean\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n if (isPrimary) {\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IsSecondary);\n await enableNetworkInternal(remoteStoreImpl);\n } else if (!isPrimary) {\n remoteStoreImpl.offlineCauses.add(OfflineCause.IsSecondary);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWatchStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentListenStream {\n if (!remoteStoreImpl.watchStream) {\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.watchStream = newPersistentWatchStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onConnected: onWatchStreamConnected.bind(null, remoteStoreImpl),\n onOpen: onWatchStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWatchStreamClose.bind(null, remoteStoreImpl),\n onWatchChange: onWatchStreamChange.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.watchStream!.inhibitBackoff();\n if (shouldStartWatchStream(remoteStoreImpl)) {\n startWatchStream(remoteStoreImpl);\n } else {\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n } else {\n await remoteStoreImpl.watchStream!.stop();\n cleanUpWatchStreamState(remoteStoreImpl);\n }\n });\n }\n\n return remoteStoreImpl.watchStream;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWriteStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentWriteStream {\n if (!remoteStoreImpl.writeStream) {\n debugAssert(\n remoteStoreImpl.writePipeline.length === 0,\n 'Should not issue writes before WriteStream is enabled'\n );\n\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.writeStream = newPersistentWriteStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onConnected: () => Promise.resolve(),\n onOpen: onWriteStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWriteStreamClose.bind(null, remoteStoreImpl),\n onHandshakeComplete: onWriteHandshakeComplete.bind(\n null,\n remoteStoreImpl\n ),\n onMutationResult: onMutationResult.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.writeStream!.inhibitBackoff();\n\n // This will start the write stream if necessary.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n await remoteStoreImpl.writeStream!.stop();\n\n if (remoteStoreImpl.writePipeline.length > 0) {\n logDebug(\n LOG_TAG,\n `Stopping write stream with ${remoteStoreImpl.writePipeline.length} pending writes`\n );\n remoteStoreImpl.writePipeline = [];\n }\n }\n });\n }\n\n return remoteStoreImpl.writeStream;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation implements PromiseLike {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue(op: () => Promise): Promise;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap } from '../util/sorted_map';\n\nimport { documentMap } from './collections';\nimport { Document } from './document';\nimport { DocumentComparator } from './document_comparator';\nimport { DocumentKey } from './document_key';\n\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */\n\nexport class DocumentSet {\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n static emptySet(oldSet: DocumentSet): DocumentSet {\n return new DocumentSet(oldSet.comparator);\n }\n\n private comparator: DocumentComparator;\n private keyedMap: SortedMap;\n private sortedSet: SortedMap;\n\n /** The default ordering is by key if the comparator is omitted */\n constructor(comp?: DocumentComparator) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = (d1: Document, d2: Document) =>\n comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n } else {\n this.comparator = (d1: Document, d2: Document) =>\n DocumentKey.comparator(d1.key, d2.key);\n }\n\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap(this.comparator);\n }\n\n has(key: DocumentKey): boolean {\n return this.keyedMap.get(key) != null;\n }\n\n get(key: DocumentKey): Document | null {\n return this.keyedMap.get(key);\n }\n\n first(): Document | null {\n return this.sortedSet.minKey();\n }\n\n last(): Document | null {\n return this.sortedSet.maxKey();\n }\n\n isEmpty(): boolean {\n return this.sortedSet.isEmpty();\n }\n\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */\n indexOf(key: DocumentKey): number {\n const doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n }\n\n get size(): number {\n return this.sortedSet.size;\n }\n\n /** Iterates documents in order defined by \"comparator\" */\n forEach(cb: (doc: Document) => void): void {\n this.sortedSet.inorderTraversal((k, v) => {\n cb(k);\n return false;\n });\n }\n\n /** Inserts or updates a document with the same key */\n add(doc: Document): DocumentSet {\n // First remove the element if we have it.\n const set = this.delete(doc.key);\n return set.copy(\n set.keyedMap.insert(doc.key, doc),\n set.sortedSet.insert(doc, null)\n );\n }\n\n /** Deletes a document with a given key */\n delete(key: DocumentKey): DocumentSet {\n const doc = this.get(key);\n if (!doc) {\n return this;\n }\n\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n }\n\n isEqual(other: DocumentSet | null | undefined): boolean {\n if (!(other instanceof DocumentSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.sortedSet.getIterator();\n const otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n const thisDoc = thisIt.getNext().key;\n const otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc)) {\n return false;\n }\n }\n return true;\n }\n\n toString(): string {\n const docStrings: string[] = [];\n this.forEach(doc => {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n } else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n }\n\n private copy(\n keyedMap: SortedMap,\n sortedSet: SortedMap\n ): DocumentSet {\n const newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { Query, queryEquals } from './query';\n\nexport const enum ChangeType {\n Added,\n Removed,\n Modified,\n Metadata\n}\n\nexport interface DocumentViewChange {\n type: ChangeType;\n doc: Document;\n}\n\nexport const enum SyncState {\n Local,\n Synced\n}\n\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nexport class DocumentChangeSet {\n private changeMap = new SortedMap(\n DocumentKey.comparator\n );\n\n track(change: DocumentViewChange): void {\n const key = change.doc.key;\n const oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n\n // Merge the new change with the existing change.\n if (\n change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata\n ) {\n this.changeMap = this.changeMap.insert(key, change);\n } else if (\n change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.remove(key);\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n } else if (\n change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else {\n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail(\n 'unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange)\n );\n }\n }\n\n getChanges(): DocumentViewChange[] {\n const changes: DocumentViewChange[] = [];\n this.changeMap.inorderTraversal(\n (key: DocumentKey, change: DocumentViewChange) => {\n changes.push(change);\n }\n );\n return changes;\n }\n}\n\nexport class ViewSnapshot {\n constructor(\n readonly query: Query,\n readonly docs: DocumentSet,\n readonly oldDocs: DocumentSet,\n readonly docChanges: DocumentViewChange[],\n readonly mutatedKeys: DocumentKeySet,\n readonly fromCache: boolean,\n readonly syncStateChanged: boolean,\n readonly excludesMetadataChanges: boolean,\n readonly hasCachedResults: boolean\n ) {}\n\n /** Returns a view snapshot as if all documents in the snapshot were added. */\n static fromInitialDocuments(\n query: Query,\n documents: DocumentSet,\n mutatedKeys: DocumentKeySet,\n fromCache: boolean,\n hasCachedResults: boolean\n ): ViewSnapshot {\n const changes: DocumentViewChange[] = [];\n documents.forEach(doc => {\n changes.push({ type: ChangeType.Added, doc });\n });\n\n return new ViewSnapshot(\n query,\n documents,\n DocumentSet.emptySet(documents),\n changes,\n mutatedKeys,\n fromCache,\n /* syncStateChanged= */ true,\n /* excludesMetadataChanges= */ false,\n hasCachedResults\n );\n }\n\n get hasPendingWrites(): boolean {\n return !this.mutatedKeys.isEmpty();\n }\n\n isEqual(other: ViewSnapshot): boolean {\n if (\n this.fromCache !== other.fromCache ||\n this.hasCachedResults !== other.hasCachedResults ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.mutatedKeys.isEqual(other.mutatedKeys) ||\n !queryEquals(this.query, other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)\n ) {\n return false;\n }\n const changes: DocumentViewChange[] = this.docChanges;\n const otherChanges: DocumentViewChange[] = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (let i = 0; i < changes.length; i++) {\n if (\n changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)\n ) {\n return false;\n }\n }\n return 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 { debugAssert, debugCast } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { EventHandler } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { canonifyQuery, Query, queryEquals, stringifyQuery } from './query';\nimport { OnlineState } from './types';\nimport { ChangeType, DocumentViewChange, ViewSnapshot } from './view_snapshot';\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nclass QueryListenersInfo {\n viewSnap: ViewSnapshot | undefined = undefined;\n listeners: QueryListener[] = [];\n\n // Helper methods that checks if the query has listeners that listening to remote store\n hasRemoteListeners(): boolean {\n return this.listeners.some(listener => listener.listensToRemoteStore());\n }\n}\n\n/**\n * Interface for handling events from the EventManager.\n */\nexport interface Observer {\n next: EventHandler;\n error: EventHandler;\n}\n\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n *\n * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be\n * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This\n * allows users to tree-shake the Watch logic.\n */\nexport interface EventManager {\n onListen?: (\n query: Query,\n enableRemoteListen: boolean\n ) => Promise;\n onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise;\n onFirstRemoteStoreListen?: (query: Query) => Promise;\n onLastRemoteStoreUnlisten?: (query: Query) => Promise;\n}\n\nexport function newEventManager(): EventManager {\n return new EventManagerImpl();\n}\n\nexport class EventManagerImpl implements EventManager {\n queries = new ObjectMap(\n q => canonifyQuery(q),\n queryEquals\n );\n\n onlineState = OnlineState.Unknown;\n\n snapshotsInSyncListeners: Set> = new Set();\n\n /** Callback invoked when a Query is first listen to. */\n onListen?: (\n query: Query,\n enableRemoteListen: boolean\n ) => Promise;\n /** Callback invoked once all listeners to a Query are removed. */\n onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise;\n\n /**\n * Callback invoked when a Query starts listening to the remote store, while\n * already listening to the cache.\n */\n onFirstRemoteStoreListen?: (query: Query) => Promise;\n /**\n * Callback invoked when a Query stops listening to the remote store, while\n * still listening to the cache.\n */\n onLastRemoteStoreUnlisten?: (query: Query) => Promise;\n}\n\nfunction validateEventManager(eventManagerImpl: EventManagerImpl): void {\n debugAssert(!!eventManagerImpl.onListen, 'onListen not set');\n debugAssert(\n !!eventManagerImpl.onFirstRemoteStoreListen,\n 'onFirstRemoteStoreListen not set'\n );\n debugAssert(!!eventManagerImpl.onUnlisten, 'onUnlisten not set');\n debugAssert(\n !!eventManagerImpl.onLastRemoteStoreUnlisten,\n 'onLastRemoteStoreUnlisten not set'\n );\n}\n\nconst enum ListenerSetupAction {\n InitializeLocalListenAndRequireWatchConnection,\n InitializeLocalListenOnly,\n RequireWatchConnectionOnly,\n NoActionRequired\n}\n\nconst enum ListenerRemovalAction {\n TerminateLocalListenAndRequireWatchDisconnection,\n TerminateLocalListenOnly,\n RequireWatchDisconnectionOnly,\n NoActionRequired\n}\n\nexport async function eventManagerListen(\n eventManager: EventManager,\n listener: QueryListener\n): Promise {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n validateEventManager(eventManagerImpl);\n\n let listenerAction = ListenerSetupAction.NoActionRequired;\n\n const query = listener.query;\n\n let queryInfo = eventManagerImpl.queries.get(query);\n if (!queryInfo) {\n queryInfo = new QueryListenersInfo();\n listenerAction = listener.listensToRemoteStore()\n ? ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection\n : ListenerSetupAction.InitializeLocalListenOnly;\n } else if (\n !queryInfo.hasRemoteListeners() &&\n listener.listensToRemoteStore()\n ) {\n // Query has been listening to local cache, and tries to add a new listener sourced from watch.\n listenerAction = ListenerSetupAction.RequireWatchConnectionOnly;\n }\n\n try {\n switch (listenerAction) {\n case ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection:\n queryInfo.viewSnap = await eventManagerImpl.onListen!(\n query,\n /** enableRemoteListen= */ true\n );\n break;\n case ListenerSetupAction.InitializeLocalListenOnly:\n queryInfo.viewSnap = await eventManagerImpl.onListen!(\n query,\n /** enableRemoteListen= */ false\n );\n break;\n case ListenerSetupAction.RequireWatchConnectionOnly:\n await eventManagerImpl.onFirstRemoteStoreListen!(query);\n break;\n default:\n break;\n }\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Initialization of query '${stringifyQuery(listener.query)}' failed`\n );\n listener.onError(firestoreError);\n return;\n }\n\n eventManagerImpl.queries.set(query, queryInfo);\n queryInfo.listeners.push(listener);\n\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n const raisedEvent = listener.applyOnlineStateChange(\n eventManagerImpl.onlineState\n );\n debugAssert(\n !raisedEvent,\n \"applyOnlineStateChange() shouldn't raise an event for brand-new listeners.\"\n );\n\n if (queryInfo.viewSnap) {\n const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap);\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n }\n}\n\nexport async function eventManagerUnlisten(\n eventManager: EventManager,\n listener: QueryListener\n): Promise {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n validateEventManager(eventManagerImpl);\n\n const query = listener.query;\n let listenerAction = ListenerRemovalAction.NoActionRequired;\n\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n const i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n\n if (queryInfo.listeners.length === 0) {\n listenerAction = listener.listensToRemoteStore()\n ? ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection\n : ListenerRemovalAction.TerminateLocalListenOnly;\n } else if (\n !queryInfo.hasRemoteListeners() &&\n listener.listensToRemoteStore()\n ) {\n // The removed listener is the last one that sourced from watch.\n listenerAction = ListenerRemovalAction.RequireWatchDisconnectionOnly;\n }\n }\n }\n switch (listenerAction) {\n case ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection:\n eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten!(\n query,\n /** disableRemoteListen= */ true\n );\n case ListenerRemovalAction.TerminateLocalListenOnly:\n eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten!(\n query,\n /** disableRemoteListen= */ false\n );\n case ListenerRemovalAction.RequireWatchDisconnectionOnly:\n return eventManagerImpl.onLastRemoteStoreUnlisten!(query);\n default:\n return;\n }\n}\n\nexport function eventManagerOnWatchChange(\n eventManager: EventManager,\n viewSnaps: ViewSnapshot[]\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n let raisedEvent = false;\n for (const viewSnap of viewSnaps) {\n const query = viewSnap.query;\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n if (listener.onViewSnapshot(viewSnap)) {\n raisedEvent = true;\n }\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function eventManagerOnWatchError(\n eventManager: EventManager,\n query: Query,\n error: FirestoreError\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n listener.onError(error);\n }\n }\n\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n eventManagerImpl.queries.delete(query);\n}\n\nexport function eventManagerOnOnlineStateChange(\n eventManager: EventManager,\n onlineState: OnlineState\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.onlineState = onlineState;\n let raisedEvent = false;\n eventManagerImpl.queries.forEach((_, queryInfo) => {\n for (const listener of queryInfo.listeners) {\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n if (listener.applyOnlineStateChange(onlineState)) {\n raisedEvent = true;\n }\n }\n });\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function addSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.snapshotsInSyncListeners.add(observer);\n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n observer.next();\n}\n\nexport function removeSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n eventManagerImpl.snapshotsInSyncListeners.delete(observer);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction raiseSnapshotsInSyncEvent(eventManagerImpl: EventManagerImpl): void {\n eventManagerImpl.snapshotsInSyncListeners.forEach(observer => {\n observer.next();\n });\n}\n\nexport enum ListenerDataSource {\n /** Listen to both cache and server changes */\n Default = 'default',\n\n /** Listen to changes in cache only */\n Cache = 'cache'\n}\n\nexport interface ListenOptions {\n /** Raise events even when only the metadata changes */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Wait for a sync with the server when online, but still raise events while\n * offline.\n */\n readonly waitForSyncWhenOnline?: boolean;\n\n /** Set the source events raised from. */\n readonly source?: ListenerDataSource;\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nexport class QueryListener {\n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n private raisedInitialEvent = false;\n\n private options: ListenOptions;\n\n private snap: ViewSnapshot | null = null;\n\n private onlineState = OnlineState.Unknown;\n\n constructor(\n readonly query: Query,\n private queryObserver: Observer,\n options?: ListenOptions\n ) {\n this.options = options || {};\n }\n\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */\n onViewSnapshot(snap: ViewSnapshot): boolean {\n debugAssert(\n snap.docChanges.length > 0 || snap.syncStateChanged,\n 'We got a new snapshot with no changes?'\n );\n\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const docChanges: DocumentViewChange[] = [];\n for (const docChange of snap.docChanges) {\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(\n snap.query,\n snap.docs,\n snap.oldDocs,\n docChanges,\n snap.mutatedKeys,\n snap.fromCache,\n snap.syncStateChanged,\n /* excludesMetadataChanges= */ true,\n snap.hasCachedResults\n );\n }\n let raisedEvent = false;\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n raisedEvent = true;\n }\n } else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n raisedEvent = true;\n }\n\n this.snap = snap;\n return raisedEvent;\n }\n\n onError(error: FirestoreError): void {\n this.queryObserver.error(error);\n }\n\n /** Returns whether a snapshot was raised. */\n applyOnlineStateChange(onlineState: OnlineState): boolean {\n this.onlineState = onlineState;\n let raisedEvent = false;\n if (\n this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)\n ) {\n this.raiseInitialEvent(this.snap);\n raisedEvent = true;\n }\n return raisedEvent;\n }\n\n private shouldRaiseInitialEvent(\n snap: ViewSnapshot,\n onlineState: OnlineState\n ): boolean {\n debugAssert(\n !this.raisedInitialEvent,\n 'Determining whether to raise first event but already had first event'\n );\n\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n\n // Always raise event if listening to cache\n if (!this.listensToRemoteStore()) {\n return true;\n }\n\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const maybeOnline = onlineState !== OnlineState.Offline;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n debugAssert(\n snap.fromCache,\n 'Waiting for sync, but snapshot is not from cache'\n );\n return false;\n }\n\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n return (\n !snap.docs.isEmpty() ||\n snap.hasCachedResults ||\n onlineState === OnlineState.Offline\n );\n }\n\n private shouldRaiseEvent(snap: ViewSnapshot): boolean {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (snap.docChanges.length > 0) {\n return true;\n }\n\n const hasPendingWritesChanged =\n this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeMetadataChanges === true;\n }\n\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n return false;\n }\n\n private raiseInitialEvent(snap: ViewSnapshot): void {\n debugAssert(\n !this.raisedInitialEvent,\n 'Trying to raise initial events for second time'\n );\n snap = ViewSnapshot.fromInitialDocuments(\n snap.query,\n snap.docs,\n snap.mutatedKeys,\n snap.fromCache,\n snap.hasCachedResults\n );\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n }\n\n listensToRemoteStore(): boolean {\n return this.options.source !== ListenerDataSource.Cache;\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 {\n BundleElement,\n BundleMetadata\n} from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */\nexport class SizedBundleElement {\n constructor(\n public readonly payload: BundleElement,\n // How many bytes this element takes to store in the bundle.\n public readonly byteLength: number\n ) {}\n\n isBundleMetadata(): boolean {\n return 'metadata' in this.payload;\n }\n}\n\nexport type BundleSource =\n | ReadableStream\n | ArrayBuffer\n | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n serializer: JsonProtoSerializer;\n\n close(): Promise;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): Promise;\n\n /**\n * Returns the next BundleElement (together with its byte size in the bundle)\n * that has not been read from underlying ReadableStream. Returns null if we\n * have reached the end of the stream.\n */\n nextElement(): Promise;\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 { LoadBundleTaskProgress } from '@firebase/firestore-types';\n\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreApplyBundledDocuments,\n localStoreSaveNamedQuery\n} from '../local/local_store_impl';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api';\nimport {\n fromDocument,\n fromName,\n fromVersion,\n JsonProtoSerializer\n} from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { SizedBundleElement } from '../util/bundle_reader';\n\nimport {\n BundleConverter,\n BundledDocument,\n BundledDocuments,\n BundleLoadResult\n} from './bundle';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */\nexport class BundleConverterImpl implements BundleConverter {\n constructor(private readonly serializer: JsonProtoSerializer) {}\n\n toDocumentKey(name: string): DocumentKey {\n return fromName(this.serializer, name);\n }\n\n /**\n * Converts a BundleDocument to a MutableDocument.\n */\n toMutableDocument(bundledDoc: BundledDocument): MutableDocument {\n if (bundledDoc.metadata.exists) {\n debugAssert(\n !!bundledDoc.document,\n 'Document is undefined when metadata.exist is true.'\n );\n return fromDocument(this.serializer, bundledDoc.document!, false);\n } else {\n return MutableDocument.newNoDocument(\n this.toDocumentKey(bundledDoc.metadata.name!),\n this.toSnapshotVersion(bundledDoc.metadata.readTime!)\n );\n }\n }\n\n toSnapshotVersion(time: ApiTimestamp): SnapshotVersion {\n return fromVersion(time);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */\nexport class BundleLoader {\n /** The current progress of loading */\n private progress: LoadBundleTaskProgress;\n /** Batched queries to be saved into storage */\n private queries: ProtoNamedQuery[] = [];\n /** Batched documents to be saved into storage */\n private documents: BundledDocuments = [];\n /** The collection groups affected by this bundle. */\n private collectionGroups = new Set();\n\n constructor(\n private bundleMetadata: ProtoBundleMetadata,\n private localStore: LocalStore,\n private serializer: JsonProtoSerializer\n ) {\n this.progress = bundleInitialProgress(bundleMetadata);\n }\n\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */\n addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null {\n debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');\n\n this.progress.bytesLoaded += element.byteLength;\n\n let documentsLoaded = this.progress.documentsLoaded;\n\n if (element.payload.namedQuery) {\n this.queries.push(element.payload.namedQuery);\n } else if (element.payload.documentMetadata) {\n this.documents.push({ metadata: element.payload.documentMetadata });\n if (!element.payload.documentMetadata.exists) {\n ++documentsLoaded;\n }\n const path = ResourcePath.fromString(\n element.payload.documentMetadata.name!\n );\n debugAssert(\n path.length >= 2,\n 'The document name does not point to a document.'\n );\n this.collectionGroups.add(path.get(path.length - 2));\n } else if (element.payload.document) {\n debugAssert(\n this.documents.length > 0 &&\n this.documents[this.documents.length - 1].metadata.name ===\n element.payload.document.name,\n 'The document being added does not match the stored metadata.'\n );\n this.documents[this.documents.length - 1].document =\n element.payload.document;\n ++documentsLoaded;\n }\n\n if (documentsLoaded !== this.progress.documentsLoaded) {\n this.progress.documentsLoaded = documentsLoaded;\n return { ...this.progress };\n }\n\n return null;\n }\n\n private getQueryDocumentMapping(\n documents: BundledDocuments\n ): Map {\n const queryDocumentMap = new Map();\n const bundleConverter = new BundleConverterImpl(this.serializer);\n for (const bundleDoc of documents) {\n if (bundleDoc.metadata.queries) {\n const documentKey = bundleConverter.toDocumentKey(\n bundleDoc.metadata.name!\n );\n for (const queryName of bundleDoc.metadata.queries) {\n const documentKeys = (\n queryDocumentMap.get(queryName) || documentKeySet()\n ).add(documentKey);\n queryDocumentMap.set(queryName, documentKeys);\n }\n }\n }\n\n return queryDocumentMap;\n }\n\n /**\n * Update the progress to 'Success' and return the updated progress.\n */\n async complete(): Promise {\n debugAssert(\n this.documents[this.documents.length - 1]?.metadata.exists !== true ||\n !!this.documents[this.documents.length - 1].document,\n 'Bundled documents end with a document metadata element instead of a document.'\n );\n debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n const changedDocs = await localStoreApplyBundledDocuments(\n this.localStore,\n new BundleConverterImpl(this.serializer),\n this.documents,\n this.bundleMetadata.id!\n );\n\n const queryDocumentMap = this.getQueryDocumentMapping(this.documents);\n\n for (const q of this.queries) {\n await localStoreSaveNamedQuery(\n this.localStore,\n q,\n queryDocumentMap.get(q.name!)\n );\n }\n\n this.progress.taskState = 'Success';\n return {\n progress: this.progress,\n changedCollectionGroups: this.collectionGroups,\n changedDocs\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */\nexport function bundleInitialProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Running',\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\nexport function bundleSuccessProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Success',\n documentsLoaded: metadata.totalDocuments!,\n bytesLoaded: metadata.totalBytes!,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n limboResolutionEnabled: boolean,\n targetChange?: TargetChange,\n targetIsPendingReset?: boolean\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n\n targetIsPendingReset = targetIsPendingReset ?? false;\n const limboChanges =\n limboResolutionEnabled && !targetIsPendingReset\n ? this.updateLimboDocuments()\n : [];\n\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n const synced =\n this.limboDocuments.size === 0 && this.current && !targetIsPendingReset;\n\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* limboResolutionEnabled= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n\n return order(c1) - order(c2);\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 { LoadBundleTask } from '../api/bundle';\nimport { User } from '../auth/user';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport {\n localStoreAcknowledgeBatch,\n localStoreAllocateTarget,\n localStoreApplyRemoteEventToLocalCache,\n localStoreExecuteQuery,\n localStoreGetActiveClients,\n localStoreGetCachedTarget,\n localStoreGetHighestUnacknowledgedBatchId,\n localStoreGetNewDocumentChanges,\n localStoreHandleUserChange,\n localStoreHasNewerBundle,\n localStoreLookupMutationDocuments,\n localStoreNotifyLocalViewChanges,\n localStoreRejectBatch,\n localStoreReleaseTarget,\n localStoreRemoveCachedMutationBatchMetadata,\n localStoreSaveBundle,\n localStoreWriteLocally\n} from '../local/local_store_impl';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { ReferenceSet } from '../local/reference_set';\nimport { ClientId, SharedClientState } from '../local/shared_client_state';\nimport { QueryTargetState } from '../local/shared_client_state_syncer';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatchResult } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport {\n canUseNetwork,\n fillWritePipeline,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreListen,\n remoteStoreUnlisten\n} from '../remote/remote_store';\nimport { debugAssert, debugCast, fail, hardAssert } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { Deferred } from '../util/promise';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n bundleInitialProgress,\n BundleLoader,\n bundleSuccessProgress\n} from './bundle_impl';\nimport {\n EventManager,\n eventManagerOnOnlineStateChange,\n eventManagerOnWatchChange,\n eventManagerOnWatchError\n} from './event_manager';\nimport { ListenSequence } from './listen_sequence';\nimport {\n canonifyQuery,\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryEquals,\n queryCollectionGroup,\n queryToTarget,\n stringifyQuery\n} from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { SyncEngine } from './sync_engine';\nimport { Target } from './target';\nimport { TargetIdGenerator } from './target_id_generator';\nimport {\n BatchId,\n MutationBatchState,\n OnlineState,\n OnlineStateSource,\n TargetId\n} from './types';\nimport {\n AddedLimboDocument,\n LimboDocumentChange,\n RemovedLimboDocument,\n View,\n ViewChange\n} from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'SyncEngine';\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass QueryView {\n constructor(\n /**\n * The query itself.\n */\n public query: Query,\n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n public targetId: TargetId,\n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n public view: View\n ) {}\n}\n\n/** Tracks a limbo resolution. */\nclass LimboResolution {\n constructor(public key: DocumentKey) {}\n\n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n receivedDocument: boolean = false;\n}\n\n/**\n * A function that updates a QueryView with a set of document changes (and a\n * remote event if applicable).\n */\ntype ApplyDocChangesHandler = (\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n) => Promise;\n\n/**\n * Callbacks implemented by EventManager to handle notifications from\n * SyncEngine.\n */\ninterface SyncEngineListener {\n /** Handles new view snapshots. */\n onWatchChange?(snapshots: ViewSnapshot[]): void;\n\n /** Handles the failure of a query. */\n onWatchError?(query: Query, error: FirestoreError): void;\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass SyncEngineImpl implements SyncEngine {\n syncEngineListener: SyncEngineListener = {};\n\n /**\n * A callback that updates the QueryView based on the provided change.\n *\n * PORTING NOTE: On other platforms, this logic lives in\n * `emitNewSnapshotsAndNotifyLocalStore()`, but on Web it is extracted to\n * ensure that all view logic only exists in bundles that include views.\n */\n applyDocChanges?: ApplyDocChangesHandler;\n\n queryViewsByQuery = new ObjectMap(\n q => canonifyQuery(q),\n queryEquals\n );\n queriesByTarget = new Map();\n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n enqueuedLimboResolutions = new Set();\n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n activeLimboTargetsByKey = new SortedMap(\n DocumentKey.comparator\n );\n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n activeLimboResolutionsByTarget = new Map();\n limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n mutationUserCallbacks = {} as {\n [uidKey: string]: SortedMap>;\n };\n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n pendingWritesCallbacks = new Map>>();\n limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\n\n onlineState = OnlineState.Unknown;\n\n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n _isPrimaryClient: undefined | boolean = undefined;\n\n constructor(\n readonly localStore: LocalStore,\n readonly remoteStore: RemoteStore,\n readonly eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n readonly sharedClientState: SharedClientState,\n public currentUser: User,\n readonly maxConcurrentLimboResolutions: number\n ) {}\n\n get isPrimaryClient(): boolean {\n return this._isPrimaryClient === true;\n }\n}\n\nexport function newSyncEngine(\n localStore: LocalStore,\n remoteStore: RemoteStore,\n eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n sharedClientState: SharedClientState,\n currentUser: User,\n maxConcurrentLimboResolutions: number,\n isPrimary: boolean\n): SyncEngine {\n const syncEngine = new SyncEngineImpl(\n localStore,\n remoteStore,\n eventManager,\n sharedClientState,\n currentUser,\n maxConcurrentLimboResolutions\n );\n if (isPrimary) {\n syncEngine._isPrimaryClient = true;\n }\n return syncEngine;\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nexport async function syncEngineListen(\n syncEngine: SyncEngine,\n query: Query,\n shouldListenToRemote: boolean = true\n): Promise {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n\n let viewSnapshot;\n\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n if (queryView) {\n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n syncEngineImpl.sharedClientState.addLocalQueryTarget(queryView.targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n } else {\n viewSnapshot = await allocateTargetAndMaybeListen(\n syncEngineImpl,\n query,\n shouldListenToRemote,\n /** shouldInitializeView= */ true\n );\n debugAssert(!!viewSnapshot, 'viewSnapshot is not initialized');\n }\n\n return viewSnapshot;\n}\n\n/** Query has been listening to the cache, and tries to initiate the remote store listen */\nexport async function triggerRemoteStoreListen(\n syncEngine: SyncEngine,\n query: Query\n): Promise {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n await allocateTargetAndMaybeListen(\n syncEngineImpl,\n query,\n /** shouldListenToRemote= */ true,\n /** shouldInitializeView= */ false\n );\n}\n\nasync function allocateTargetAndMaybeListen(\n syncEngineImpl: SyncEngineImpl,\n query: Query,\n shouldListenToRemote: boolean,\n shouldInitializeView: boolean\n): Promise {\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(query)\n );\n\n const targetId = targetData.targetId;\n\n // PORTING NOTE: When the query is listening to cache only, we skip sending it over to Watch by\n // not registering it in shared client state, and directly calculate initial snapshots and\n // subsequent updates from cache. Otherwise, register the target ID with local Firestore client\n // as active watch target.\n const status: QueryTargetState = shouldListenToRemote\n ? syncEngineImpl.sharedClientState.addLocalQueryTarget(targetId)\n : 'not-current';\n\n let viewSnapshot;\n if (shouldInitializeView) {\n viewSnapshot = await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n query,\n targetId,\n status === 'current',\n targetData.resumeToken\n );\n }\n\n if (syncEngineImpl.isPrimaryClient && shouldListenToRemote) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n\n return viewSnapshot;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */\nasync function initializeViewAndComputeSnapshot(\n syncEngineImpl: SyncEngineImpl,\n query: Query,\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n): Promise {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n syncEngineImpl.applyDocChanges = (queryView, changes, remoteEvent) =>\n applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent);\n\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const synthesizedTargetChange =\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current && syncEngineImpl.onlineState !== OnlineState.Offline,\n resumeToken\n );\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient,\n synthesizedTargetChange\n );\n updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges);\n\n debugAssert(\n !!viewChange.snapshot,\n 'applyChanges for new view should always return a snapshot'\n );\n\n const data = new QueryView(query, targetId, view);\n\n syncEngineImpl.queryViewsByQuery.set(query, data);\n if (syncEngineImpl.queriesByTarget.has(targetId)) {\n syncEngineImpl.queriesByTarget.get(targetId)!.push(query);\n } else {\n syncEngineImpl.queriesByTarget.set(targetId, [query]);\n }\n\n return viewChange.snapshot;\n}\n\n/** Stops listening to the query. */\nexport async function syncEngineUnlisten(\n syncEngine: SyncEngine,\n query: Query,\n shouldUnlistenToRemote: boolean\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n debugAssert(\n !!queryView,\n 'Trying to unlisten on query not found:' + stringifyQuery(query)\n );\n\n // Only clean up the query view and target if this is the only query mapped\n // to the target.\n const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId)!;\n if (queries.length > 1) {\n syncEngineImpl.queriesByTarget.set(\n queryView.targetId,\n queries.filter(q => !queryEquals(q, query))\n );\n syncEngineImpl.queryViewsByQuery.delete(query);\n return;\n }\n\n // No other queries are mapped to the target, clean up the query and the target.\n if (syncEngineImpl.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n const targetRemainsActive =\n syncEngineImpl.sharedClientState.isActiveQueryTarget(queryView.targetId);\n\n if (!targetRemainsActive) {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ false\n )\n .then(() => {\n syncEngineImpl.sharedClientState.clearQueryState(queryView.targetId);\n if (shouldUnlistenToRemote) {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\n }\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n } else {\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ true\n );\n }\n}\n\n/** Unlistens to the remote store while still listening to the cache. */\nexport async function triggerRemoteStoreUnlisten(\n syncEngine: SyncEngine,\n query: Query\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n debugAssert(\n !!queryView,\n 'Trying to unlisten on query not found:' + stringifyQuery(query)\n );\n const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId)!;\n\n if (syncEngineImpl.isPrimaryClient && queries.length === 1) {\n // PORTING NOTE: Unregister the target ID with local Firestore client as\n // watch target.\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\n }\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */\nexport async function syncEngineWrite(\n syncEngine: SyncEngine,\n batch: Mutation[],\n userCallback: Deferred\n): Promise {\n const syncEngineImpl = syncEngineEnsureWriteCallbacks(syncEngine);\n\n try {\n const result = await localStoreWriteLocally(\n syncEngineImpl.localStore,\n batch\n );\n syncEngineImpl.sharedClientState.addPendingMutation(result.batchId);\n addMutationCallback(syncEngineImpl, result.batchId, userCallback);\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.changes\n );\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } catch (e) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const error = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to persist write`\n );\n userCallback.reject(error);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */\nexport async function syncEngineApplyRemoteEvent(\n syncEngine: SyncEngine,\n remoteEvent: RemoteEvent\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreApplyRemoteEventToLocalCache(\n syncEngineImpl.localStore,\n remoteEvent\n );\n // Update `receivedDocument` as appropriate for any limbo targets.\n remoteEvent.targetChanges.forEach((targetChange, targetId) => {\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution) {\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n hardAssert(\n targetChange.addedDocuments.size +\n targetChange.modifiedDocuments.size +\n targetChange.removedDocuments.size <=\n 1,\n 'Limbo resolution for single document contains multiple changes.'\n );\n if (targetChange.addedDocuments.size > 0) {\n limboResolution.receivedDocument = true;\n } else if (targetChange.modifiedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 'Received remove for limbo target document without add.'\n );\n limboResolution.receivedDocument = false;\n } else {\n // This was probably just a CURRENT targetChange or similar.\n }\n }\n });\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n remoteEvent\n );\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\nexport function syncEngineApplyOnlineStateChange(\n syncEngine: SyncEngine,\n onlineState: OnlineState,\n source: OnlineStateSource\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (\n (syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.RemoteStore) ||\n (!syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.SharedClientState)\n ) {\n const newViewSnapshots = [] as ViewSnapshot[];\n syncEngineImpl.queryViewsByQuery.forEach((query, queryView) => {\n const viewChange = queryView.view.applyOnlineStateChange(onlineState);\n debugAssert(\n viewChange.limboChanges.length === 0,\n 'OnlineState should not affect limbo documents.'\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n\n eventManagerOnOnlineStateChange(syncEngineImpl.eventManager, onlineState);\n\n if (newViewSnapshots.length) {\n debugAssert(\n !!syncEngineImpl.syncEngineListener.onWatchChange,\n 'Active views but EventManager callbacks are not assigned'\n );\n syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots);\n }\n\n syncEngineImpl.onlineState = onlineState;\n if (syncEngineImpl.isPrimaryClient) {\n syncEngineImpl.sharedClientState.setOnlineState(onlineState);\n }\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */\nexport async function syncEngineRejectListen(\n syncEngine: SyncEngine,\n targetId: TargetId,\n err: FirestoreError\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // PORTING NOTE: Multi-tab only.\n syncEngineImpl.sharedClientState.updateQueryState(targetId, 'rejected', err);\n\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n const limboKey = limboResolution && limboResolution.key;\n if (limboKey) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let documentUpdates = new SortedMap(\n DocumentKey.comparator\n );\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n documentUpdates = documentUpdates.insert(\n limboKey,\n MutableDocument.newNoDocument(limboKey, SnapshotVersion.min())\n );\n const resolvedLimboDocuments = documentKeySet().add(limboKey);\n const event = new RemoteEvent(\n SnapshotVersion.min(),\n /* targetChanges= */ new Map(),\n /* targetMismatches= */ new SortedMap(\n primitiveComparator\n ),\n documentUpdates,\n resolvedLimboDocuments\n );\n\n await syncEngineApplyRemoteEvent(syncEngineImpl, event);\n\n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(limboKey);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(targetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n } else {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => removeAndCleanupTarget(syncEngineImpl, targetId, err))\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nexport async function syncEngineApplySuccessfulWrite(\n syncEngine: SyncEngine,\n mutationBatchResult: MutationBatchResult\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const batchId = mutationBatchResult.batch.batchId;\n\n try {\n const changes = await localStoreAcknowledgeBatch(\n syncEngineImpl.localStore,\n mutationBatchResult\n );\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n processUserCallback(syncEngineImpl, batchId, /*error=*/ null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'acknowledged'\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\nexport async function syncEngineRejectFailedWrite(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreRejectBatch(\n syncEngineImpl.localStore,\n batchId\n );\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n processUserCallback(syncEngineImpl, batchId, error);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'rejected',\n error\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */\nexport async function syncEngineRegisterPendingWritesCallback(\n syncEngine: SyncEngine,\n callback: Deferred\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (!canUseNetwork(syncEngineImpl.remoteStore)) {\n logDebug(\n LOG_TAG,\n 'The network is disabled. The task returned by ' +\n \"'awaitPendingWrites()' will not complete until the network is enabled.\"\n );\n }\n\n try {\n const highestBatchId = await localStoreGetHighestUnacknowledgedBatchId(\n syncEngineImpl.localStore\n );\n if (highestBatchId === BATCHID_UNKNOWN) {\n // Trigger the callback right away if there is no pending writes at the moment.\n callback.resolve();\n return;\n }\n\n const callbacks =\n syncEngineImpl.pendingWritesCallbacks.get(highestBatchId) || [];\n callbacks.push(callback);\n syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n 'Initialization of waitForPendingWrites() operation failed'\n );\n callback.reject(firestoreError);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */\nfunction triggerPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId\n): void {\n (syncEngineImpl.pendingWritesCallbacks.get(batchId) || []).forEach(\n callback => {\n callback.resolve();\n }\n );\n\n syncEngineImpl.pendingWritesCallbacks.delete(batchId);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */\nfunction rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n errorMessage: string\n): void {\n syncEngineImpl.pendingWritesCallbacks.forEach(callbacks => {\n callbacks.forEach(callback => {\n callback.reject(new FirestoreError(Code.CANCELLED, errorMessage));\n });\n });\n\n syncEngineImpl.pendingWritesCallbacks.clear();\n}\n\nfunction addMutationCallback(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId,\n callback: Deferred\n): void {\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap>(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n}\n\n/**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\nfunction processUserCallback(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError | null\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (newCallbacks) {\n const callback = newCallbacks.get(batchId);\n if (callback) {\n debugAssert(\n batchId === newCallbacks.minKey(),\n 'Mutation callbacks processed out-of-order?'\n );\n if (error) {\n callback.reject(error);\n } else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n }\n}\n\nfunction removeAndCleanupTarget(\n syncEngineImpl: SyncEngineImpl,\n targetId: number,\n error: FirestoreError | null = null\n): void {\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(targetId);\n\n debugAssert(\n syncEngineImpl.queriesByTarget.has(targetId) &&\n syncEngineImpl.queriesByTarget.get(targetId)!.length !== 0,\n `There are no queries mapped to target id ${targetId}`\n );\n\n for (const query of syncEngineImpl.queriesByTarget.get(targetId)!) {\n syncEngineImpl.queryViewsByQuery.delete(query);\n if (error) {\n syncEngineImpl.syncEngineListener.onWatchError!(query, error);\n }\n }\n\n syncEngineImpl.queriesByTarget.delete(targetId);\n\n if (syncEngineImpl.isPrimaryClient) {\n const limboKeys =\n syncEngineImpl.limboDocumentRefs.removeReferencesForId(targetId);\n limboKeys.forEach(limboKey => {\n const isReferenced =\n syncEngineImpl.limboDocumentRefs.containsKey(limboKey);\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboKey);\n }\n });\n }\n}\n\nfunction removeLimboTarget(\n syncEngineImpl: SyncEngineImpl,\n key: DocumentKey\n): void {\n syncEngineImpl.enqueuedLimboResolutions.delete(key.path.canonicalString());\n\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const limboTargetId = syncEngineImpl.activeLimboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n\n remoteStoreUnlisten(syncEngineImpl.remoteStore, limboTargetId);\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(key);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(limboTargetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n}\n\nfunction updateTrackedLimbos(\n syncEngineImpl: SyncEngineImpl,\n targetId: TargetId,\n limboChanges: LimboDocumentChange[]\n): void {\n for (const limboChange of limboChanges) {\n if (limboChange instanceof AddedLimboDocument) {\n syncEngineImpl.limboDocumentRefs.addReference(limboChange.key, targetId);\n trackLimboChange(syncEngineImpl, limboChange);\n } else if (limboChange instanceof RemovedLimboDocument) {\n logDebug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n syncEngineImpl.limboDocumentRefs.removeReference(\n limboChange.key,\n targetId\n );\n const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(\n limboChange.key\n );\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboChange.key);\n }\n } else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n}\n\nfunction trackLimboChange(\n syncEngineImpl: SyncEngineImpl,\n limboChange: AddedLimboDocument\n): void {\n const key = limboChange.key;\n const keyString = key.path.canonicalString();\n if (\n !syncEngineImpl.activeLimboTargetsByKey.get(key) &&\n !syncEngineImpl.enqueuedLimboResolutions.has(keyString)\n ) {\n logDebug(LOG_TAG, 'New document in limbo: ' + key);\n syncEngineImpl.enqueuedLimboResolutions.add(keyString);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n }\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */\nfunction pumpEnqueuedLimboResolutions(syncEngineImpl: SyncEngineImpl): void {\n while (\n syncEngineImpl.enqueuedLimboResolutions.size > 0 &&\n syncEngineImpl.activeLimboTargetsByKey.size <\n syncEngineImpl.maxConcurrentLimboResolutions\n ) {\n const keyString = syncEngineImpl.enqueuedLimboResolutions\n .values()\n .next().value;\n syncEngineImpl.enqueuedLimboResolutions.delete(keyString);\n const key = new DocumentKey(ResourcePath.fromString(keyString));\n const limboTargetId = syncEngineImpl.limboTargetIdGenerator.next();\n syncEngineImpl.activeLimboResolutionsByTarget.set(\n limboTargetId,\n new LimboResolution(key)\n );\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.insert(key, limboTargetId);\n remoteStoreListen(\n syncEngineImpl.remoteStore,\n new TargetData(\n queryToTarget(newQueryForPath(key.path)),\n limboTargetId,\n TargetPurpose.LimboResolution,\n ListenSequence.INVALID\n )\n );\n }\n}\n\n// Visible for testing\nexport function syncEngineGetActiveLimboDocumentResolutions(\n syncEngine: SyncEngine\n): SortedMap {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.activeLimboTargetsByKey;\n}\n\n// Visible for testing\nexport function syncEngineGetEnqueuedLimboDocumentResolutions(\n syncEngine: SyncEngine\n): Set {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.enqueuedLimboResolutions;\n}\n\nexport async function syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine: SyncEngine,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const newSnaps: ViewSnapshot[] = [];\n const docChangesInAllViews: LocalViewChanges[] = [];\n const queriesProcessed: Array> = [];\n\n if (syncEngineImpl.queryViewsByQuery.isEmpty()) {\n // Return early since `onWatchChange()` might not have been assigned yet.\n return;\n }\n\n syncEngineImpl.queryViewsByQuery.forEach((_, queryView) => {\n debugAssert(\n !!syncEngineImpl.applyDocChanges,\n 'ApplyDocChangesHandler not set'\n );\n queriesProcessed.push(\n syncEngineImpl\n .applyDocChanges(queryView, changes, remoteEvent)\n .then(viewSnapshot => {\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n if (viewSnapshot || remoteEvent) {\n if (syncEngineImpl.isPrimaryClient) {\n const isCurrent = viewSnapshot && !viewSnapshot.fromCache;\n syncEngineImpl.sharedClientState.updateQueryState(\n queryView.targetId,\n isCurrent ? 'current' : 'not-current'\n );\n }\n }\n\n // Update views if there are actual changes.\n if (!!viewSnapshot) {\n newSnaps.push(viewSnapshot);\n const docChanges = LocalViewChanges.fromSnapshot(\n queryView.targetId,\n viewSnapshot\n );\n docChangesInAllViews.push(docChanges);\n }\n })\n );\n });\n\n await Promise.all(queriesProcessed);\n syncEngineImpl.syncEngineListener.onWatchChange!(newSnaps);\n await localStoreNotifyLocalViewChanges(\n syncEngineImpl.localStore,\n docChangesInAllViews\n );\n}\n\nasync function applyDocChanges(\n syncEngineImpl: SyncEngineImpl,\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise {\n let viewDocChanges = queryView.view.computeDocChanges(changes);\n if (viewDocChanges.needsRefill) {\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n viewDocChanges = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ false\n ).then(({ documents }) => {\n return queryView.view.computeDocChanges(documents, viewDocChanges);\n });\n }\n\n const targetChange =\n remoteEvent && remoteEvent.targetChanges.get(queryView.targetId);\n const targetIsPendingReset =\n remoteEvent && remoteEvent.targetMismatches.get(queryView.targetId) != null;\n const viewChange = queryView.view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient,\n targetChange,\n targetIsPendingReset\n );\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewChange.limboChanges\n );\n return viewChange.snapshot;\n}\n\nexport async function syncEngineHandleCredentialChange(\n syncEngine: SyncEngine,\n user: User\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const userChanged = !syncEngineImpl.currentUser.isEqual(user);\n\n if (userChanged) {\n logDebug(LOG_TAG, 'User change. New user:', user.toKey());\n\n const result = await localStoreHandleUserChange(\n syncEngineImpl.localStore,\n user\n );\n syncEngineImpl.currentUser = user;\n\n // Fails tasks waiting for pending writes requested by previous user.\n rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl,\n \"'waitForPendingWrites' promise is rejected due to a user change.\"\n );\n // TODO(b/114226417): Consider calling this only in the primary tab.\n syncEngineImpl.sharedClientState.handleUserChange(\n user,\n result.removedBatchIds,\n result.addedBatchIds\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.affectedDocuments\n );\n }\n}\n\nexport function syncEngineGetRemoteKeysForTarget(\n syncEngine: SyncEngine,\n targetId: TargetId\n): DocumentKeySet {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution && limboResolution.receivedDocument) {\n return documentKeySet().add(limboResolution.key);\n } else {\n let keySet = documentKeySet();\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n if (!queries) {\n return keySet;\n }\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n keySet = keySet.unionWith(queryView.view.syncedDocuments);\n }\n return keySet;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */\nasync function synchronizeViewAndComputeSnapshot(\n syncEngine: SyncEngine,\n queryView: QueryView\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ true\n );\n const viewSnapshot =\n queryView.view.synchronizeWithPersistedState(queryResult);\n if (syncEngineImpl.isPrimaryClient) {\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewSnapshot.limboChanges\n );\n }\n return viewSnapshot;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineSynchronizeWithChangedDocuments(\n syncEngine: SyncEngine,\n collectionGroup: string\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n return localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n collectionGroup\n ).then(changes =>\n syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes)\n );\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyBatchState(\n syncEngine: SyncEngine,\n batchId: BatchId,\n batchState: MutationBatchState,\n error?: FirestoreError\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const documents = await localStoreLookupMutationDocuments(\n syncEngineImpl.localStore,\n batchId\n );\n\n if (documents === null) {\n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n logDebug(LOG_TAG, 'Cannot apply mutation batch with id: ' + batchId);\n return;\n }\n\n if (batchState === 'pending') {\n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } else if (batchState === 'acknowledged' || batchState === 'rejected') {\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n processUserCallback(syncEngineImpl, batchId, error ? error : null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n localStoreRemoveCachedMutationBatchMetadata(\n syncEngineImpl.localStore,\n batchId\n );\n } else {\n fail(`Unknown batchState: ${batchState}`);\n }\n\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, documents);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyPrimaryState(\n syncEngine: SyncEngine,\n isPrimary: boolean\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n ensureWatchCallbacks(syncEngineImpl);\n syncEngineEnsureWriteCallbacks(syncEngineImpl);\n if (isPrimary === true && syncEngineImpl._isPrimaryClient !== true) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const activeTargets =\n syncEngineImpl.sharedClientState.getAllActiveQueryTargets();\n const activeQueries = await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets.toArray(),\n /*transitionToPrimary=*/ true\n );\n syncEngineImpl._isPrimaryClient = true;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, true);\n for (const targetData of activeQueries) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n } else if (isPrimary === false && syncEngineImpl._isPrimaryClient !== false) {\n const activeTargets: TargetId[] = [];\n\n let p = Promise.resolve();\n syncEngineImpl.queriesByTarget.forEach((_, targetId) => {\n if (syncEngineImpl.sharedClientState.isLocalQueryTarget(targetId)) {\n activeTargets.push(targetId);\n } else {\n p = p.then(() => {\n removeAndCleanupTarget(syncEngineImpl, targetId);\n return localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n });\n }\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n await p;\n\n await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets,\n /*transitionToPrimary=*/ false\n );\n resetLimboDocuments(syncEngineImpl);\n syncEngineImpl._isPrimaryClient = false;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, false);\n }\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction resetLimboDocuments(syncEngine: SyncEngine): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.activeLimboResolutionsByTarget.forEach((_, targetId) => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n syncEngineImpl.limboDocumentRefs.removeAllReferences();\n syncEngineImpl.activeLimboResolutionsByTarget = new Map<\n TargetId,\n LimboResolution\n >();\n syncEngineImpl.activeLimboTargetsByKey = new SortedMap(\n DocumentKey.comparator\n );\n}\n\n/**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n// PORTING NOTE: Multi-Tab only.\nasync function synchronizeQueryViewsAndRaiseSnapshots(\n syncEngine: SyncEngine,\n targets: TargetId[],\n transitionToPrimary: boolean\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const activeQueries: TargetData[] = [];\n const newViewSnapshots: ViewSnapshot[] = [];\n for (const targetId of targets) {\n let targetData: TargetData;\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n\n if (queries && queries.length !== 0) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(queries[0])\n );\n\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n\n const viewChange = await synchronizeViewAndComputeSnapshot(\n syncEngineImpl,\n queryView\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n }\n } else {\n debugAssert(\n transitionToPrimary,\n 'A secondary tab should never have an active view without an active target.'\n );\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Target for id ${targetId} not found`);\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target!),\n targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n }\n\n activeQueries.push(targetData!);\n }\n\n syncEngineImpl.syncEngineListener.onWatchChange!(newViewSnapshots);\n return activeQueries;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction synthesizeTargetToQuery(target: Target): Query {\n return newQuery(\n target.path,\n target.collectionGroup,\n target.orderBy,\n target.filters,\n target.limit,\n LimitType.First,\n target.startAt,\n target.endAt\n );\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nexport function syncEngineGetActiveClients(\n syncEngine: SyncEngine\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return localStoreGetActiveClients(syncEngineImpl.localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyTargetState(\n syncEngine: SyncEngine,\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (syncEngineImpl._isPrimaryClient) {\n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n logDebug(LOG_TAG, 'Ignoring unexpected query state notification.');\n return;\n }\n\n const query = syncEngineImpl.queriesByTarget.get(targetId);\n if (query && query.length > 0) {\n switch (state) {\n case 'current':\n case 'not-current': {\n const changes = await localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n queryCollectionGroup(query[0])\n );\n const synthesizedRemoteEvent =\n RemoteEvent.createSynthesizedRemoteEventForCurrentChange(\n targetId,\n state === 'current',\n ByteString.EMPTY_BYTE_STRING\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n synthesizedRemoteEvent\n );\n break;\n }\n case 'rejected': {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ true\n );\n removeAndCleanupTarget(syncEngineImpl, targetId, error);\n break;\n }\n default:\n fail('Unexpected target state: ' + state);\n }\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */\nexport async function syncEngineApplyActiveTargetsChange(\n syncEngine: SyncEngine,\n added: TargetId[],\n removed: TargetId[]\n): Promise {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n if (!syncEngineImpl._isPrimaryClient) {\n return;\n }\n\n for (const targetId of added) {\n // A target is already listening to remote store if it is already registered to\n // sharedClientState.\n const targetAlreadyListeningToRemoteStore =\n syncEngineImpl.queriesByTarget.has(targetId) &&\n syncEngineImpl.sharedClientState.isActiveQueryTarget(targetId);\n if (targetAlreadyListeningToRemoteStore) {\n logDebug(LOG_TAG, 'Adding an already active target ' + targetId);\n continue;\n }\n\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Query data for active target ${targetId} not found`);\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target),\n targetData.targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n\n for (const targetId of removed) {\n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n if (!syncEngineImpl.queriesByTarget.has(targetId)) {\n continue;\n }\n\n // Release queries that are still active.\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n removeAndCleanupTarget(syncEngineImpl, targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nfunction ensureWatchCallbacks(syncEngine: SyncEngine): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applyRemoteEvent =\n syncEngineApplyRemoteEvent.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.getRemoteKeysForTarget =\n syncEngineGetRemoteKeysForTarget.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectListen =\n syncEngineRejectListen.bind(null, syncEngineImpl);\n syncEngineImpl.syncEngineListener.onWatchChange =\n eventManagerOnWatchChange.bind(null, syncEngineImpl.eventManager);\n syncEngineImpl.syncEngineListener.onWatchError =\n eventManagerOnWatchError.bind(null, syncEngineImpl.eventManager);\n return syncEngineImpl;\n}\n\nexport function syncEngineEnsureWriteCallbacks(\n syncEngine: SyncEngine\n): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applySuccessfulWrite =\n syncEngineApplySuccessfulWrite.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectFailedWrite =\n syncEngineRejectFailedWrite.bind(null, syncEngineImpl);\n return syncEngineImpl;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */\nexport function syncEngineLoadBundle(\n syncEngine: SyncEngine,\n bundleReader: BundleReader,\n task: LoadBundleTask\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n loadBundleImpl(syncEngineImpl, bundleReader, task).then(collectionGroups => {\n syncEngineImpl.sharedClientState.notifyBundleLoaded(collectionGroups);\n });\n}\n\n/** Loads a bundle and returns the list of affected collection groups. */\nasync function loadBundleImpl(\n syncEngine: SyncEngineImpl,\n reader: BundleReader,\n task: LoadBundleTask\n): Promise> {\n try {\n const metadata = await reader.getMetadata();\n const skip = await localStoreHasNewerBundle(\n syncEngine.localStore,\n metadata\n );\n if (skip) {\n await reader.close();\n task._completeWith(bundleSuccessProgress(metadata));\n return Promise.resolve(new Set());\n }\n\n task._updateProgress(bundleInitialProgress(metadata));\n\n const loader = new BundleLoader(\n metadata,\n syncEngine.localStore,\n reader.serializer\n );\n let element = await reader.nextElement();\n while (element) {\n debugAssert(\n !element.payload.metadata,\n 'Unexpected BundleMetadata element.'\n );\n const progress = await loader.addSizedElement(element);\n if (progress) {\n task._updateProgress(progress);\n }\n\n element = await reader.nextElement();\n }\n\n const result = await loader.complete();\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine,\n result.changedDocs,\n /* remoteEvent */ undefined\n );\n\n // Save metadata, so loading the same bundle will skip.\n await localStoreSaveBundle(syncEngine.localStore, metadata);\n task._completeWith(result.progress);\n return Promise.resolve(result.changedCollectionGroups);\n } catch (e) {\n logWarn(LOG_TAG, `Loading bundle failed with ${e}`);\n task._failWith(e as FirestoreError);\n return Promise.resolve(new Set());\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 { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport {\n IndexBackfiller,\n IndexBackfillerScheduler\n} from '../local/index_backfiller';\nimport {\n indexedDbStoragePrefix,\n IndexedDbPersistence\n} from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { newLocalStore } from '../local/local_store_impl';\nimport { LruParams } from '../local/lru_garbage_collector';\nimport { LruScheduler } from '../local/lru_garbage_collector_impl';\nimport {\n MemoryEagerDelegate,\n MemoryLruDelegate,\n MemoryPersistence\n} from '../local/memory_persistence';\nimport { Scheduler, Persistence } from '../local/persistence';\nimport { QueryEngine } from '../local/query_engine';\nimport {\n ClientId,\n MemorySharedClientState,\n SharedClientState,\n WebStorageSharedClientState\n} from '../local/shared_client_state';\nimport { newConnection, newConnectivityMonitor } from '../platform/connection';\nimport { getDocument, getWindow } from '../platform/dom';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport {\n fillWritePipeline,\n newRemoteStore,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreShutdown\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { DatabaseInfo } from './database_info';\nimport { EventManager, newEventManager } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport {\n newSyncEngine,\n syncEngineApplyActiveTargetsChange,\n syncEngineApplyBatchState,\n syncEngineApplyOnlineStateChange,\n syncEngineApplyPrimaryState,\n syncEngineApplyTargetState,\n syncEngineEnsureWriteCallbacks,\n syncEngineGetActiveClients,\n syncEngineHandleCredentialChange,\n syncEngineSynchronizeWithChangedDocuments\n} from './sync_engine_impl';\nimport { OnlineStateSource } from './types';\n\nexport interface ComponentConfiguration {\n asyncQueue: AsyncQueue;\n databaseInfo: DatabaseInfo;\n authCredentials: CredentialsProvider;\n appCheckCredentials: CredentialsProvider;\n clientId: ClientId;\n initialUser: User;\n maxConcurrentLimboResolutions: number;\n}\n\n/**\n * Initializes and wires components that are needed to interface with the local\n * cache. Implementations override `initialize()` to provide all components.\n */\nexport interface OfflineComponentProvider {\n persistence: Persistence;\n sharedClientState: SharedClientState;\n localStore: LocalStore;\n gcScheduler: Scheduler | null;\n indexBackfillerScheduler: Scheduler | null;\n synchronizeTabs: boolean;\n\n initialize(cfg: ComponentConfiguration): Promise;\n\n terminate(): Promise;\n}\n\n/**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */\nexport class MemoryOfflineComponentProvider\n implements OfflineComponentProvider\n{\n persistence!: Persistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n serializer!: JsonProtoSerializer;\n\n async initialize(cfg: ComponentConfiguration): Promise {\n this.serializer = newSerializer(cfg.databaseInfo.databaseId);\n this.sharedClientState = this.createSharedClientState(cfg);\n this.persistence = this.createPersistence(cfg);\n await this.persistence.start();\n this.localStore = this.createLocalStore(cfg);\n this.gcScheduler = this.createGarbageCollectionScheduler(\n cfg,\n this.localStore\n );\n this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(\n cfg,\n this.localStore\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n return new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer);\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n\n async terminate(): Promise {\n this.gcScheduler?.stop();\n this.indexBackfillerScheduler?.stop();\n this.sharedClientState.shutdown();\n await this.persistence.shutdown();\n }\n}\n\nexport class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider {\n constructor(protected readonly cacheSizeBytes: number | undefined) {\n super();\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n hardAssert(\n this.persistence.referenceDelegate instanceof MemoryLruDelegate,\n 'referenceDelegate is expected to be an instance of MemoryLruDelegate.'\n );\n\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n return new MemoryPersistence(\n p => MemoryLruDelegate.factory(p, lruParams),\n this.serializer\n );\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */\nexport class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider {\n persistence!: IndexedDbPersistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined,\n protected readonly forceOwnership: boolean | undefined\n ) {\n super();\n }\n\n async initialize(cfg: ComponentConfiguration): Promise {\n await super.initialize(cfg);\n\n await this.onlineComponentProvider.initialize(this, cfg);\n\n // Enqueue writes from a previous session\n await syncEngineEnsureWriteCallbacks(\n this.onlineComponentProvider.syncEngine\n );\n await fillWritePipeline(this.onlineComponentProvider.remoteStore);\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(() => {\n if (this.gcScheduler && !this.gcScheduler.started) {\n this.gcScheduler.start();\n }\n if (\n this.indexBackfillerScheduler &&\n !this.indexBackfillerScheduler.started\n ) {\n this.indexBackfillerScheduler.start();\n }\n return Promise.resolve();\n });\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const indexBackfiller = new IndexBackfiller(localStore, this.persistence);\n return new IndexBackfillerScheduler(cfg.asyncQueue, indexBackfiller);\n }\n\n createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence {\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n\n return new IndexedDbPersistence(\n this.synchronizeTabs,\n persistenceKey,\n cfg.clientId,\n lruParams,\n cfg.asyncQueue,\n getWindow(),\n getDocument(),\n this.serializer,\n this.sharedClientState,\n !!this.forceOwnership\n );\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */\nexport class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider {\n synchronizeTabs = true;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined\n ) {\n super(onlineComponentProvider, cacheSizeBytes, /* forceOwnership= */ false);\n }\n\n async initialize(cfg: ComponentConfiguration): Promise {\n await super.initialize(cfg);\n\n const syncEngine = this.onlineComponentProvider.syncEngine;\n\n if (this.sharedClientState instanceof WebStorageSharedClientState) {\n this.sharedClientState.syncEngine = {\n applyBatchState: syncEngineApplyBatchState.bind(null, syncEngine),\n applyTargetState: syncEngineApplyTargetState.bind(null, syncEngine),\n applyActiveTargetsChange: syncEngineApplyActiveTargetsChange.bind(\n null,\n syncEngine\n ),\n getActiveClients: syncEngineGetActiveClients.bind(null, syncEngine),\n synchronizeWithChangedDocuments:\n syncEngineSynchronizeWithChangedDocuments.bind(null, syncEngine)\n };\n await this.sharedClientState.start();\n }\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(async isPrimary => {\n await syncEngineApplyPrimaryState(\n this.onlineComponentProvider.syncEngine,\n isPrimary\n );\n if (this.gcScheduler) {\n if (isPrimary && !this.gcScheduler.started) {\n this.gcScheduler.start();\n } else if (!isPrimary) {\n this.gcScheduler.stop();\n }\n }\n if (this.indexBackfillerScheduler) {\n if (isPrimary && !this.indexBackfillerScheduler.started) {\n this.indexBackfillerScheduler.start();\n } else if (!isPrimary) {\n this.indexBackfillerScheduler.stop();\n }\n }\n });\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n const window = getWindow();\n if (!WebStorageSharedClientState.isAvailable(window)) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n return new WebStorageSharedClientState(\n window,\n cfg.asyncQueue,\n persistenceKey,\n cfg.clientId,\n cfg.initialUser\n );\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */\nexport class OnlineComponentProvider {\n protected localStore!: LocalStore;\n protected sharedClientState!: SharedClientState;\n datastore!: Datastore;\n eventManager!: EventManager;\n remoteStore!: RemoteStore;\n syncEngine!: SyncEngine;\n\n async initialize(\n offlineComponentProvider: OfflineComponentProvider,\n cfg: ComponentConfiguration\n ): Promise {\n if (this.localStore) {\n // OnlineComponentProvider may get initialized multiple times if\n // multi-tab persistence is used.\n return;\n }\n\n this.localStore = offlineComponentProvider.localStore;\n this.sharedClientState = offlineComponentProvider.sharedClientState;\n this.datastore = this.createDatastore(cfg);\n this.remoteStore = this.createRemoteStore(cfg);\n this.eventManager = this.createEventManager(cfg);\n this.syncEngine = this.createSyncEngine(\n cfg,\n /* startAsPrimary=*/ !offlineComponentProvider.synchronizeTabs\n );\n\n this.sharedClientState.onlineStateHandler = onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.SharedClientState\n );\n\n this.remoteStore.remoteSyncer.handleCredentialChange =\n syncEngineHandleCredentialChange.bind(null, this.syncEngine);\n\n await remoteStoreApplyPrimaryState(\n this.remoteStore,\n this.syncEngine.isPrimaryClient\n );\n }\n\n createEventManager(cfg: ComponentConfiguration): EventManager {\n return newEventManager();\n }\n\n createDatastore(cfg: ComponentConfiguration): Datastore {\n const serializer = newSerializer(cfg.databaseInfo.databaseId);\n const connection = newConnection(cfg.databaseInfo);\n return newDatastore(\n cfg.authCredentials,\n cfg.appCheckCredentials,\n connection,\n serializer\n );\n }\n\n createRemoteStore(cfg: ComponentConfiguration): RemoteStore {\n return newRemoteStore(\n this.localStore,\n this.datastore,\n cfg.asyncQueue,\n onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.RemoteStore\n ),\n newConnectivityMonitor()\n );\n }\n\n createSyncEngine(\n cfg: ComponentConfiguration,\n startAsPrimary: boolean\n ): SyncEngine {\n return newSyncEngine(\n this.localStore,\n this.remoteStore,\n this.eventManager,\n this.sharedClientState,\n cfg.initialUser,\n cfg.maxConcurrentLimboResolutions,\n startAsPrimary\n );\n }\n\n async terminate(): Promise {\n await remoteStoreShutdown(this.remoteStore);\n this.datastore?.terminate();\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 { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\nimport { ConnectivityMonitor } from '../../remote/connectivity_monitor';\nimport { NoopConnectivityMonitor } from '../../remote/connectivity_monitor_noop';\n\nimport { BrowserConnectivityMonitor } from './connectivity_monitor';\nimport { WebChannelConnection } from './webchannel_connection';\n\n/** Initializes the WebChannelConnection for the browser. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new WebChannelConnection(databaseInfo);\n}\n\n/** Return the Platform-specific connectivity monitor. */\nexport function newConnectivityMonitor(): ConnectivityMonitor {\n if (BrowserConnectivityMonitor.isAvailable()) {\n return new BrowserConnectivityMonitor();\n } else {\n return new NoopConnectivityMonitor();\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 { debugAssert } from './assert';\n\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\nexport const DEFAULT_BYTES_PER_READ = 10240;\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nexport function toByteStreamReaderHelper(\n source: Uint8Array,\n bytesPerRead: number = DEFAULT_BYTES_PER_READ\n): ReadableStreamReader {\n debugAssert(\n bytesPerRead > 0,\n `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n );\n let readFrom = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reader: any = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read(): Promise {\n if (readFrom < source.byteLength) {\n const result = {\n value: source.slice(readFrom, readFrom + bytesPerRead),\n done: false\n } as const;\n readFrom += bytesPerRead;\n return result;\n }\n\n return { done: true };\n },\n async cancel(): Promise {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n return reader;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Observer } from '../core/event_manager';\n\nimport { FirestoreError } from './error';\nimport { logError } from './log';\nimport { EventHandler } from './misc';\n\n/*\n * A wrapper implementation of Observer that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nexport class AsyncObserver implements Observer {\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n private muted = false;\n\n constructor(private observer: Partial>) {}\n\n next(value: T): void {\n if (this.observer.next) {\n this.scheduleEvent(this.observer.next, value);\n }\n }\n\n error(error: FirestoreError): void {\n if (this.observer.error) {\n this.scheduleEvent(this.observer.error, error);\n } else {\n logError('Uncaught Error in snapshot listener:', error.toString());\n }\n }\n\n mute(): void {\n this.muted = true;\n }\n\n private scheduleEvent(eventHandler: EventHandler, event: E): void {\n if (!this.muted) {\n setTimeout(() => {\n if (!this.muted) {\n eventHandler(event);\n }\n }, 0);\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 { newTextDecoder } from '../platform/text_serializer';\nimport { BundleMetadata } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\nimport { debugAssert } from './assert';\nimport { BundleReader, SizedBundleElement } from './bundle_reader';\nimport { Deferred } from './promise';\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nclass BundleReaderImpl implements BundleReader {\n /** Cached bundle metadata. */\n private metadata: Deferred = new Deferred();\n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n private buffer: Uint8Array = new Uint8Array();\n /** The decoder used to parse binary data into strings. */\n private textDecoder: TextDecoder;\n\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n private reader: ReadableStreamReader,\n readonly serializer: JsonProtoSerializer\n ) {\n this.textDecoder = newTextDecoder();\n // Read the metadata (which is the first element).\n this.nextElementImpl().then(\n element => {\n if (element && element.isBundleMetadata()) {\n this.metadata.resolve(element.payload.metadata!);\n } else {\n this.metadata.reject(\n new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(element?.payload)}`)\n );\n }\n },\n error => this.metadata.reject(error)\n );\n }\n\n close(): Promise {\n return this.reader.cancel();\n }\n\n async getMetadata(): Promise {\n return this.metadata.promise;\n }\n\n async nextElement(): Promise {\n // Makes sure metadata is read before proceeding.\n await this.getMetadata();\n return this.nextElementImpl();\n }\n\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */\n private async nextElementImpl(): Promise {\n const lengthBuffer = await this.readLength();\n if (lengthBuffer === null) {\n return null;\n }\n\n const lengthString = this.textDecoder.decode(lengthBuffer);\n const length = Number(lengthString);\n if (isNaN(length)) {\n this.raiseError(`length string (${lengthString}) is not valid number`);\n }\n\n const jsonString = await this.readJsonString(length);\n\n return new SizedBundleElement(\n JSON.parse(jsonString),\n lengthBuffer.length + length\n );\n }\n\n /** First index of '{' from the underlying buffer. */\n private indexOfOpenBracket(): number {\n return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n }\n\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */\n private async readLength(): Promise {\n while (this.indexOfOpenBracket() < 0) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n break;\n }\n }\n\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (this.buffer.length === 0) {\n return null;\n }\n\n const position = this.indexOfOpenBracket();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n if (position < 0) {\n this.raiseError(\n 'Reached the end of bundle when a length string is expected.'\n );\n }\n\n const result = this.buffer.slice(0, position);\n // Update the internal buffer to drop the read length.\n this.buffer = this.buffer.slice(position);\n return result;\n }\n\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */\n private async readJsonString(length: number): Promise {\n while (this.buffer.length < length) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n this.raiseError('Reached the end of bundle when more is expected.');\n }\n }\n\n const result = this.textDecoder.decode(this.buffer.slice(0, length));\n // Update the internal buffer to drop the read json string.\n this.buffer = this.buffer.slice(length);\n return result;\n }\n\n private raiseError(message: string): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.reader.cancel();\n throw new Error(`Invalid bundle format: ${message}`);\n }\n\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */\n private async pullMoreDataToBuffer(): Promise {\n const result = await this.reader.read();\n if (!result.done) {\n debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n const newBuffer = new Uint8Array(\n this.buffer.length + result.value!.length\n );\n newBuffer.set(this.buffer);\n newBuffer.set(result.value!, this.buffer.length);\n this.buffer = newBuffer;\n }\n return result.done;\n }\n}\n\nexport function newBundleReader(\n reader: ReadableStreamReader,\n serializer: JsonProtoSerializer\n): BundleReader {\n return new BundleReaderImpl(reader, serializer);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail('Document in a transaction was a ' + doc.constructor.name);\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\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\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error): boolean {\n if (error.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport { Deferred } from '../util/promise';\n\nimport { Aggregate } from './aggregate';\nimport { NamedQuery } from './bundle';\nimport {\n ComponentConfiguration,\n MemoryOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from './component_provider';\nimport { DatabaseId, DatabaseInfo } from './database_info';\nimport {\n addSnapshotsInSyncListener,\n EventManager,\n eventManagerListen,\n eventManagerUnlisten,\n ListenOptions,\n Observer,\n QueryListener,\n removeSnapshotsInSyncListener\n} from './event_manager';\nimport { newQueryForPath, Query } from './query';\nimport { SyncEngine } from './sync_engine';\nimport {\n syncEngineListen,\n syncEngineLoadBundle,\n syncEngineRegisterPendingWritesCallback,\n syncEngineUnlisten,\n syncEngineWrite,\n triggerRemoteStoreListen,\n triggerRemoteStoreUnlisten\n} from './sync_engine_impl';\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\nimport { TransactionRunner } from './transaction_runner';\nimport { View } from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'FirestoreClient';\nexport const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100;\n\n/** DOMException error code constants. */\nconst DOM_EXCEPTION_INVALID_STATE = 11;\nconst DOM_EXCEPTION_ABORTED = 20;\nconst DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\n\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the //\n * pieces of the client SDK architecture. It is responsible for creating the //\n * async queue that is shared by all of the other components in the system. //\n */\nexport class FirestoreClient {\n private user = User.UNAUTHENTICATED;\n private readonly clientId = AutoId.newId();\n private authCredentialListener: CredentialChangeListener = () =>\n Promise.resolve();\n private appCheckCredentialListener: (\n appCheckToken: string,\n user: User\n ) => Promise = () => Promise.resolve();\n _uninitializedComponentsProvider?: {\n _offline: OfflineComponentProvider;\n _offlineKind: 'memory' | 'persistent';\n _online: OnlineComponentProvider;\n };\n\n _offlineComponents?: OfflineComponentProvider;\n _onlineComponents?: OnlineComponentProvider;\n\n constructor(\n private authCredentials: CredentialsProvider,\n private appCheckCredentials: CredentialsProvider,\n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n public asyncQueue: AsyncQueue,\n private databaseInfo: DatabaseInfo\n ) {\n this.authCredentials.start(asyncQueue, async user => {\n logDebug(LOG_TAG, 'Received user=', user.uid);\n await this.authCredentialListener(user);\n this.user = user;\n });\n this.appCheckCredentials.start(asyncQueue, newAppCheckToken => {\n logDebug(LOG_TAG, 'Received new app check token=', newAppCheckToken);\n return this.appCheckCredentialListener(newAppCheckToken, this.user);\n });\n }\n\n get configuration(): ComponentConfiguration {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: MAX_CONCURRENT_LIMBO_RESOLUTIONS\n };\n }\n\n setCredentialChangeListener(listener: (user: User) => Promise): void {\n this.authCredentialListener = listener;\n }\n\n setAppCheckTokenChangeListener(\n listener: (appCheckToken: string, user: User) => Promise\n ): void {\n this.appCheckCredentialListener = listener;\n }\n\n /**\n * Checks that the client has not been terminated. Ensures that other methods on //\n * this class cannot be called after the client is terminated. //\n */\n verifyNotTerminated(): void {\n if (this.asyncQueue.isShuttingDown) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n terminate(): Promise {\n this.asyncQueue.enterRestrictedMode();\n const deferred = new Deferred();\n this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n if (this._onlineComponents) {\n await this._onlineComponents.terminate();\n }\n if (this._offlineComponents) {\n await this._offlineComponents.terminate();\n }\n\n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown();\n this.appCheckCredentials.shutdown();\n deferred.resolve();\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to shutdown persistence`\n );\n deferred.reject(firestoreError);\n }\n });\n return deferred.promise;\n }\n}\n\nexport async function setOfflineComponentProvider(\n client: FirestoreClient,\n offlineComponentProvider: OfflineComponentProvider\n): Promise {\n client.asyncQueue.verifyOperationInProgress();\n\n logDebug(LOG_TAG, 'Initializing OfflineComponentProvider');\n const configuration = client.configuration;\n await offlineComponentProvider.initialize(configuration);\n\n let currentUser = configuration.initialUser;\n client.setCredentialChangeListener(async user => {\n if (!currentUser.isEqual(user)) {\n await localStoreHandleUserChange(\n offlineComponentProvider.localStore,\n user\n );\n currentUser = user;\n }\n });\n\n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n offlineComponentProvider.persistence.setDatabaseDeletedListener(() =>\n client.terminate()\n );\n\n client._offlineComponents = offlineComponentProvider;\n}\n\nexport async function setOnlineComponentProvider(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider\n): Promise {\n client.asyncQueue.verifyOperationInProgress();\n\n const offlineComponentProvider = await ensureOfflineComponents(client);\n\n logDebug(LOG_TAG, 'Initializing OnlineComponentProvider');\n await onlineComponentProvider.initialize(\n offlineComponentProvider,\n client.configuration\n );\n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n client.setCredentialChangeListener(user =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client.setAppCheckTokenChangeListener((_, user) =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client._onlineComponents = onlineComponentProvider;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\nexport function canFallbackFromIndexedDbError(\n error: FirestoreError | DOMException\n): boolean {\n if (error.name === 'FirebaseError') {\n return (\n error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED\n );\n } else if (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException\n ) {\n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n return (\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n error.code === DOM_EXCEPTION_QUOTA_EXCEEDED ||\n error.code === DOM_EXCEPTION_ABORTED ||\n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n error.code === DOM_EXCEPTION_INVALID_STATE\n );\n }\n\n return true;\n}\n\nasync function ensureOfflineComponents(\n client: FirestoreClient\n): Promise {\n if (!client._offlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OfflineComponentProvider');\n try {\n await setOfflineComponentProvider(\n client,\n client._uninitializedComponentsProvider._offline\n );\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error using user provided cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n } else {\n logDebug(LOG_TAG, 'Using default OfflineComponentProvider');\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nasync function ensureOnlineComponents(\n client: FirestoreClient\n): Promise {\n if (!client._onlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OnlineComponentProvider');\n await setOnlineComponentProvider(\n client,\n client._uninitializedComponentsProvider._online\n );\n } else {\n logDebug(LOG_TAG, 'Using default OnlineComponentProvider');\n await setOnlineComponentProvider(client, new OnlineComponentProvider());\n }\n }\n\n return client._onlineComponents!;\n}\n\nfunction getPersistence(client: FirestoreClient): Promise {\n return ensureOfflineComponents(client).then(c => c.persistence);\n}\n\nexport function getLocalStore(client: FirestoreClient): Promise {\n return ensureOfflineComponents(client).then(c => c.localStore);\n}\n\nfunction getRemoteStore(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.remoteStore);\n}\n\nexport function getSyncEngine(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.syncEngine);\n}\n\nfunction getDatastore(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.datastore);\n}\n\nexport async function getEventManager(\n client: FirestoreClient\n): Promise {\n const onlineComponentProvider = await ensureOnlineComponents(client);\n const eventManager = onlineComponentProvider.eventManager;\n eventManager.onListen = syncEngineListen.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onUnlisten = syncEngineUnlisten.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onFirstRemoteStoreListen = triggerRemoteStoreListen.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onLastRemoteStoreUnlisten = triggerRemoteStoreUnlisten.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n return eventManager;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */\nexport function firestoreClientEnableNetwork(\n client: FirestoreClient\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(true);\n return remoteStoreEnableNetwork(remoteStore);\n });\n}\n\n/** Disables the network connection. Pending operations will not complete. */\nexport function firestoreClientDisableNetwork(\n client: FirestoreClient\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(false);\n return remoteStoreDisableNetwork(remoteStore);\n });\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */\nexport function firestoreClientWaitForPendingWrites(\n client: FirestoreClient\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineRegisterPendingWritesCallback(syncEngine, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientListen(\n client: FirestoreClient,\n query: Query,\n options: ListenOptions,\n observer: Partial>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n const listener = new QueryListener(query, wrappedObserver, options);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerListen(eventManager, listener);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerUnlisten(eventManager, listener);\n });\n };\n}\n\nexport function firestoreClientGetDocumentFromLocalCache(\n client: FirestoreClient,\n docKey: DocumentKey\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return readDocumentFromCache(localStore, docKey, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentViaSnapshotListener(\n client: FirestoreClient,\n key: DocumentKey,\n options: GetOptions = {}\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return readDocumentViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n key,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsFromLocalCache(\n client: FirestoreClient,\n query: Query\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return executeQueryFromCache(localStore, query, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsViaSnapshotListener(\n client: FirestoreClient,\n query: Query,\n options: GetOptions = {}\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return executeQueryViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n query,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientRunAggregateQuery(\n client: FirestoreClient,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const deferred = new Deferred>();\n\n client.asyncQueue.enqueueAndForget(async () => {\n // Implement and call executeAggregateQueryViaSnapshotListener, similar\n // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n // above\n try {\n // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n const datastore = await getDatastore(client);\n deferred.resolve(\n invokeRunAggregationQueryRpc(datastore, query, aggregates)\n );\n } catch (e) {\n deferred.reject(e as Error);\n }\n });\n return deferred.promise;\n}\n\nexport function firestoreClientWrite(\n client: FirestoreClient,\n mutations: Mutation[]\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineWrite(syncEngine, mutations, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientAddSnapshotsInSyncListener(\n client: FirestoreClient,\n observer: Partial>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return addSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return removeSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */\nexport function firestoreClientTransaction(\n client: FirestoreClient,\n updateFunction: (transaction: Transaction) => Promise,\n options: TransactionOptions\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const datastore = await getDatastore(client);\n new TransactionRunner(\n client.asyncQueue,\n datastore,\n options,\n updateFunction,\n deferred\n ).run();\n });\n return deferred.promise;\n}\n\nasync function readDocumentFromCache(\n localStore: LocalStore,\n docKey: DocumentKey,\n result: Deferred\n): Promise {\n try {\n const document = await localStoreReadDocument(localStore, docKey);\n if (document.isFoundDocument()) {\n result.resolve(document);\n } else if (document.isNoDocument()) {\n result.resolve(null);\n } else {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from cache. (However, this document may ' +\n \"exist on the server. Run again without setting 'source' in \" +\n 'the GetOptions to attempt to retrieve the document from the ' +\n 'server.)'\n )\n );\n }\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to get document '${docKey} from cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */\nfunction readDocumentViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n key: DocumentKey,\n options: GetOptions,\n result: Deferred\n): Promise {\n const wrappedObserver = new AsyncObserver({\n next: (snap: ViewSnapshot) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n const exists = snap.docs.has(key);\n if (!exists && snap.fromCache) {\n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document because the client is offline.'\n )\n );\n } else if (\n exists &&\n snap.fromCache &&\n options &&\n options.source === 'server'\n ) {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from server. (However, this ' +\n 'document does exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached document.)'\n )\n );\n } else {\n debugAssert(\n snap.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n result.resolve(snap);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(\n newQueryForPath(key.path),\n wrappedObserver,\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n }\n );\n return eventManagerListen(eventManager, listener);\n}\n\nasync function executeQueryFromCache(\n localStore: LocalStore,\n query: Query,\n result: Deferred\n): Promise {\n try {\n const queryResult = await localStoreExecuteQuery(\n localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ false\n );\n result.resolve(viewChange.snapshot!);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to execute query '${query} against cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */\nfunction executeQueryViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n query: Query,\n options: GetOptions,\n result: Deferred\n): Promise {\n const wrappedObserver = new AsyncObserver({\n next: snapshot => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n if (snapshot.fromCache && options.source === 'server') {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get documents from server. (However, these ' +\n 'documents may exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached documents.)'\n )\n );\n } else {\n result.resolve(snapshot);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(query, wrappedObserver, {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n });\n return eventManagerListen(eventManager, listener);\n}\n\nexport function firestoreClientLoadBundle(\n client: FirestoreClient,\n databaseId: DatabaseId,\n data: ReadableStream | ArrayBuffer | string,\n resultTask: LoadBundleTask\n): void {\n const reader = createBundleReader(data, newSerializer(databaseId));\n client.asyncQueue.enqueueAndForget(async () => {\n syncEngineLoadBundle(await getSyncEngine(client), reader, resultTask);\n });\n}\n\nexport function firestoreClientGetNamedQuery(\n client: FirestoreClient,\n queryName: string\n): Promise {\n return client.asyncQueue.enqueue(async () =>\n localStoreGetNamedQuery(await getLocalStore(client), queryName)\n );\n}\n\nfunction createBundleReader(\n data: ReadableStream | ArrayBuffer | string,\n serializer: JsonProtoSerializer\n): BundleReader {\n let content: ReadableStream | ArrayBuffer;\n if (typeof data === 'string') {\n content = newTextEncoder().encode(data);\n } else {\n content = data;\n }\n return newBundleReader(toByteStreamReader(content), serializer);\n}\n\nexport function firestoreClientSetIndexConfiguration(\n client: FirestoreClient,\n indexes: FieldIndex[]\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n return localStoreConfigureFieldIndexes(\n await getLocalStore(client),\n indexes\n );\n });\n}\n\nexport function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n client: FirestoreClient,\n isEnabled: boolean\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n return localStoreSetIndexAutoCreationEnabled(\n await getLocalStore(client),\n isEnabled\n );\n });\n}\n\nexport function firestoreClientDeleteAllFieldIndexes(\n client: FirestoreClient\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n return localStoreDeleteAllFieldIndexes(await getLocalStore(client));\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 { BundleSource } from '../../util/bundle_reader';\nimport { toByteStreamReaderHelper } from '../../util/byte_stream';\n\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\nexport function toByteStreamReader(\n source: BundleSource,\n bytesPerRead: number\n): ReadableStreamReader {\n if (source instanceof Uint8Array) {\n return toByteStreamReaderHelper(source, bytesPerRead);\n }\n if (source instanceof ArrayBuffer) {\n return toByteStreamReaderHelper(new Uint8Array(source), bytesPerRead);\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n throw new Error(\n 'Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream'\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 true iff the array contains the value using strong equality.\n */\nexport function includes(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value mathching the predicate\n */\nexport function some(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffArrays(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\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/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\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// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider;\n _appCheckCredentials: CredentialsProvider;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${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\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\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// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down.\n private _terminateTask?: Promise;\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== undefined;\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise {\n if (!this._terminateTask) {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const settings = firestore._getSettings();\n const newHostSetting = `${host}:${port}`;\n\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n\n firestore._setSettings({\n ...settings,\n host: newHostSetting,\n ssl: false\n });\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\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 } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to Typescript's `Partial`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference {\n return new CollectionReference(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\n this.firestore,\n converter,\n this._key\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-genrated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual(\n left: Query,\n right: Query\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\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 { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise = Promise.resolve();\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor() {\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred();\n return this.enqueueInternal(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal(op: () => Promise): Promise {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overriden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + getMessageOrStack(this.failure));\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver(obj: unknown): obj is PartialObserver {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as JsonObject;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\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 { PartialObserver } from '../api/observer';\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\n\n/**\n * Represents the state of bundle loading tasks.\n *\n * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will\n * be no more updates after they are reported.\n */\nexport type TaskState = 'Error' | 'Running' | 'Success';\n\n/**\n * Represents a progress update or a final state from loading bundles.\n */\nexport interface LoadBundleTaskProgress {\n /** How many documents have been loaded. */\n documentsLoaded: number;\n /** How many documents are in the bundle being loaded. */\n totalDocuments: number;\n /** How many bytes have been loaded. */\n bytesLoaded: number;\n /** How many bytes are in the bundle being loaded. */\n totalBytes: number;\n /** Current task state. */\n taskState: TaskState;\n}\n\n/**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */\nexport class LoadBundleTask implements PromiseLike {\n private _progressObserver: PartialObserver = {};\n private _taskCompletionResolver = new Deferred();\n\n private _lastProgress: LoadBundleTaskProgress = {\n taskState: 'Running',\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */\n onProgress(\n next?: (progress: LoadBundleTaskProgress) => unknown,\n error?: (err: Error) => unknown,\n complete?: () => void\n ): void {\n this._progressObserver = {\n next,\n error,\n complete\n };\n }\n\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n catch(\n onRejected: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.catch(onRejected);\n }\n\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n then(\n onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike,\n onRejected?: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n }\n\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */\n _completeWith(progress: LoadBundleTaskProgress): void {\n debugAssert(\n progress.taskState === 'Success',\n 'Task is not completed with Success.'\n );\n this._updateProgress(progress);\n if (this._progressObserver.complete) {\n this._progressObserver.complete();\n }\n\n this._taskCompletionResolver.resolve(progress);\n }\n\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */\n _failWith(error: FirestoreError): void {\n this._lastProgress.taskState = 'Error';\n\n if (this._progressObserver.next) {\n this._progressObserver.next(this._lastProgress);\n }\n\n if (this._progressObserver.error) {\n this._progressObserver.error(error);\n }\n\n this._taskCompletionResolver.reject(error);\n }\n\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */\n _updateProgress(progress: LoadBundleTaskProgress): void {\n debugAssert(\n this._lastProgress.taskState === 'Running',\n 'Cannot update progress on a completed or failed task'\n );\n\n this._lastProgress = progress;\n if (this._progressObserver.next) {\n this._progressObserver.next(progress);\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 {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { deepEqual, getDefaultEmulatorHostnameAndPort } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport {\n IndexedDbOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from '../core/component_provider';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport {\n canFallbackFromIndexedDbError,\n FirestoreClient,\n firestoreClientDisableNetwork,\n firestoreClientEnableNetwork,\n firestoreClientGetNamedQuery,\n firestoreClientLoadBundle,\n firestoreClientWaitForPendingWrites,\n setOfflineComponentProvider,\n setOnlineComponentProvider\n} from '../core/firestore_client';\nimport { makeDatabaseInfo } from '../lite-api/components';\nimport {\n Firestore as LiteFirestore,\n connectFirestoreEmulator\n} from '../lite-api/database';\nimport { Query } from '../lite-api/reference';\nimport {\n indexedDbClearPersistence,\n indexedDbStoragePrefix\n} from '../local/indexeddb_persistence';\nimport { LRU_COLLECTION_DISABLED } from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { LoadBundleTask } from './bundle';\nimport { CredentialsProvider } from './credentials';\nimport { PersistenceSettings, FirestoreSettings } from './settings';\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\n }\n}\n\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * {@link Firestore} instance.\n */\nexport const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore extends LiteFirestore {\n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore';\n\n readonly _queue: AsyncQueue = newAsyncQueue();\n readonly _persistenceKey: string;\n\n _firestoreClient: FirestoreClient | undefined;\n\n /** @hideconstructor */\n constructor(\n authCredentialsProvider: CredentialsProvider,\n appCheckCredentialsProvider: CredentialsProvider,\n databaseId: DatabaseId,\n app?: FirebaseApp\n ) {\n super(\n authCredentialsProvider,\n appCheckCredentialsProvider,\n databaseId,\n app\n );\n this._persistenceKey = app?.name || '[DEFAULT]';\n }\n\n _terminate(): Promise {\n if (!this._firestoreClient) {\n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n configureFirestore(this);\n }\n return this._firestoreClient!.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore');\n\n if (provider.isInitialized(databaseId)) {\n const existingInstance = provider.getImmediate({\n identifier: databaseId\n });\n const initialSettings = provider.getOptions(\n databaseId\n ) as FirestoreSettings;\n if (deepEqual(initialSettings, settings)) {\n return existingInstance;\n } else {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'initializeFirestore() has already been called with ' +\n 'different options. To avoid this error, call initializeFirestore() with the ' +\n 'same options as when it was originally called, or call getFirestore() to return the' +\n ' already initialized instance.'\n );\n }\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.localCache !== undefined\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes will` +\n `be deprecated. Instead, specify the cache size in the cache object`\n );\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The default {@link Firestore} instance of the default app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The default {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the default app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || DEFAULT_DATABASE_NAME;\n const db = _getProvider(app, 'firestore').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * @internal\n */\nexport function ensureFirestoreConfigured(\n firestore: Firestore\n): FirestoreClient {\n if (!firestore._firestoreClient) {\n configureFirestore(firestore);\n }\n firestore._firestoreClient!.verifyNotTerminated();\n return firestore._firestoreClient as FirestoreClient;\n}\n\nexport function configureFirestore(firestore: Firestore): void {\n const settings = firestore._freezeSettings();\n debugAssert(!!settings.host, 'FirestoreSettings.host is not set');\n debugAssert(\n !firestore._firestoreClient,\n 'configureFirestore() called multiple times'\n );\n\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore._app?.options.appId || '',\n firestore._persistenceKey,\n settings\n );\n firestore._firestoreClient = new FirestoreClient(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n firestore._queue,\n databaseInfo\n );\n if (\n settings.localCache?._offlineComponentProvider &&\n settings.localCache?._onlineComponentProvider\n ) {\n firestore._firestoreClient._uninitializedComponentsProvider = {\n _offlineKind: settings.localCache.kind,\n _offline: settings.localCache._offlineComponentProvider,\n _online: settings.localCache._onlineComponentProvider\n };\n }\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * On failure, `enableIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * Note: `enableIndexedDbPersistence()` must be called before any other functions\n * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableIndexedDbPersistence(\n firestore: Firestore,\n persistenceSettings?: PersistenceSettings\n): Promise {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new IndexedDbOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes,\n persistenceSettings?.forceOwnership\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableMultiTabIndexedDbPersistence(\n firestore: Firestore\n): Promise {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableMultiTabIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new MultiTabOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */\nfunction setPersistenceProviders(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider,\n offlineComponentProvider: OfflineComponentProvider\n): Promise {\n const persistenceResult = new Deferred();\n return client.asyncQueue\n .enqueue(async () => {\n try {\n await setOfflineComponentProvider(client, offlineComponentProvider);\n await setOnlineComponentProvider(client, onlineComponentProvider);\n persistenceResult.resolve();\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error enabling indexeddb cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n persistenceResult.reject(error);\n }\n })\n .then(() => persistenceResult.promise);\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */\nexport function clearIndexedDbPersistence(firestore: Firestore): Promise {\n if (firestore._initialized && !firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Persistence can only be cleared before a Firestore instance is ' +\n 'initialized or after it is terminated.'\n );\n }\n\n const deferred = new Deferred();\n firestore._queue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n await indexedDbClearPersistence(\n indexedDbStoragePrefix(firestore._databaseId, firestore._persistenceKey)\n );\n deferred.resolve();\n } catch (e) {\n deferred.reject(e as Error | undefined);\n }\n });\n return deferred.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */\nexport function waitForPendingWrites(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWaitForPendingWrites(client);\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */\nexport function enableNetwork(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientEnableNetwork(client);\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */\nexport function disableNetwork(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientDisableNetwork(client);\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n _removeServiceInstance(\n firestore.app,\n 'firestore',\n firestore._databaseId.database\n );\n return firestore._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise`.\n */\nexport function loadBundle(\n firestore: Firestore,\n bundleData: ReadableStream | ArrayBuffer | string\n): LoadBundleTask {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const resultTask = new LoadBundleTask();\n firestoreClientLoadBundle(\n client,\n firestore._databaseId,\n bundleData,\n resultTask\n );\n return resultTask;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */\nexport function namedQuery(\n firestore: Firestore,\n name: string\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientGetNamedQuery(client, name).then(namedQuery => {\n if (!namedQuery) {\n return null;\n }\n\n return new Query(firestore, null, namedQuery.query);\n });\n}\n\nfunction verifyNotInitialized(firestore: Firestore): void {\n if (firestore._initialized || firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and persistence can no longer be ' +\n 'enabled. You can only enable persistence before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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 { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\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 {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\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 { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | 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 { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /** Returns a JSON-serializable representation of this GeoPoint. */\n toJSON(): { latitude: number; longitude: number } {\n return { latitude: this._lat, longitude: this._long };\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\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 DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nfunction parseObject(\n obj: Dict,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\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 { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference {\n return new DocumentReference(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\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 } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\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 compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link 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\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply(\n query: Query\n ): Query {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse(\n query: Query\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse(\n query: Query\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply(\n query: Query\n ): Query {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply(\n query: Query\n ): Query {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply(\n query: Query\n ): Query {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n methodName: string,\n docOrFields: Array>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\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 { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 'ReferenceValue is not valid ' + name\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\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 {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(result.length === 1, 'Expected a single document result');\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\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 { newQueryComparator } from '../core/query';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { FieldPath } from '../lite-api/field_path';\nimport {\n DocumentData,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from '../lite-api/reference';\nimport {\n DocumentSnapshot as LiteDocumentSnapshot,\n fieldPathFromArgument,\n FirestoreDataConverter as LiteFirestoreDataConverter\n} from '../lite-api/snapshot';\nimport { UntypedFirestoreDataConverter } from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> extends LiteFirestoreDataConverter {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. To use `set()`\n * with `merge` and `mergeFields`, `toFirestore()` must be defined with\n * `PartialWithFieldValue`.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and\n * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data(options)`.\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.\n * @param options - The `SnapshotOptions` from the initial call to `data()`.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot,\n options?: SnapshotOptions\n ): AppModelType;\n}\n\n/**\n * Options that configure how data is retrieved from a `DocumentSnapshot` (for\n * example the desired behavior for server timestamps that have not yet been set\n * to their final value).\n */\nexport interface SnapshotOptions {\n /**\n * If set, controls the return value for server timestamps that have not yet\n * been set to their final value.\n *\n * By specifying 'estimate', pending server timestamps return an estimate\n * based on the local clock. This estimate will differ from the final value\n * and cause these values to change once the server result becomes available.\n *\n * By specifying 'previous', pending timestamps will be ignored and return\n * their previous value instead.\n *\n * If omitted or set to 'none', `null` will be returned by default until the\n * server value becomes available.\n */\n readonly serverTimestamps?: 'estimate' | 'previous' | 'none';\n}\n\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */\nexport class SnapshotMetadata {\n /**\n * True if the snapshot contains the result of local writes (for example\n * `set()` or `update()` calls) that have not yet been committed to the\n * backend. If your listener has opted into metadata updates (via\n * `SnapshotListenOptions`) you will receive another snapshot with\n * `hasPendingWrites` equal to false once the writes have been committed to\n * the backend.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * True if the snapshot was created from cached data rather than guaranteed\n * up-to-date server data. If your listener has opted into metadata updates\n * (via `SnapshotListenOptions`) you will receive another snapshot with\n * `fromCache` set to false once the client has received up-to-date data from\n * the backend.\n */\n readonly fromCache: boolean;\n\n /** @hideconstructor */\n constructor(hasPendingWrites: boolean, fromCache: boolean) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */\n isEqual(other: SnapshotMetadata): boolean {\n return (\n this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache\n );\n }\n}\n\n/**\n * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.\n */\nexport type DocumentChangeType = 'added' | 'removed' | 'modified';\n\n/**\n * A `DocumentChange` represents a change to the documents matching a query.\n * It contains the document affected and the type of change that occurred.\n */\nexport interface DocumentChange<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of change ('added', 'modified', or 'removed'). */\n readonly type: DocumentChangeType;\n\n /** The document affected by this change. */\n readonly doc: QueryDocumentSnapshot;\n\n /**\n * The index of the changed document in the result set immediately prior to\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects\n * have been applied). Is `-1` for 'added' events.\n */\n readonly oldIndex: number;\n\n /**\n * The index of the changed document in the result set immediately after\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`\n * objects and the current `DocumentChange` object have been applied).\n * Is -1 for 'removed' events.\n */\n readonly newIndex: number;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends LiteDocumentSnapshot {\n private readonly _firestoreImpl: Firestore;\n\n /**\n * Metadata about the `DocumentSnapshot`, including information about its\n * source and local modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /** @hideconstructor protected */\n constructor(\n readonly _firestore: Firestore,\n userDataWriter: AbstractUserDataWriter,\n key: DocumentKey,\n document: Document | null,\n metadata: SnapshotMetadata,\n converter: UntypedFirestoreDataConverter | null\n ) {\n super(_firestore, userDataWriter, key, document, converter);\n this._firestoreImpl = _firestore;\n this.metadata = metadata;\n }\n\n /**\n * Returns whether or not the data exists. True if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return super.exists();\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */\n data(options: SnapshotOptions = {}): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n this.metadata,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot, options);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value,\n options.serverTimestamps\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath, options: SnapshotOptions = {}): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(\n value,\n options.serverTimestamps\n );\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(options: SnapshotOptions = {}): AppModelType {\n return super.data(options) as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Metadata about this snapshot, concerning its source and if it has local\n * modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /**\n * The query on which you called `get` or `onSnapshot` in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n private _cachedChanges?: Array>;\n private _cachedChangesIncludeMetadataChanges?: boolean;\n\n /** @hideconstructor */\n constructor(\n readonly _firestore: Firestore,\n readonly _userDataWriter: AbstractUserDataWriter,\n query: Query,\n readonly _snapshot: ViewSnapshot\n ) {\n this.metadata = new SnapshotMetadata(\n _snapshot.hasPendingWrites,\n _snapshot.fromCache\n );\n this.query = query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n const result: Array> = [];\n this.forEach(doc => result.push(doc));\n return result;\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this._snapshot.docs.size;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._snapshot.docs.forEach(doc => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n doc.key,\n doc,\n new SnapshotMetadata(\n this._snapshot.mutatedKeys.has(doc.key),\n this._snapshot.fromCache\n ),\n this.query.converter\n )\n );\n });\n }\n\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */\n docChanges(\n options: SnapshotListenOptions = {}\n ): Array> {\n const includeMetadataChanges = !!options.includeMetadataChanges;\n\n if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'To include metadata changes with your document changes, you must ' +\n 'also pass { includeMetadataChanges:true } to onSnapshot().'\n );\n }\n\n if (\n !this._cachedChanges ||\n this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges\n ) {\n this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges);\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n }\n\n return this._cachedChanges;\n }\n}\n\n/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\nexport function changesFromSnapshot<\n AppModelType,\n DbModelType extends DocumentData\n>(\n querySnapshot: QuerySnapshot,\n includeMetadataChanges: boolean\n): Array> {\n if (querySnapshot._snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n let lastDoc: Document;\n let index = 0;\n return querySnapshot._snapshot.docChanges.map(change => {\n debugAssert(\n change.type === ChangeType.Added,\n 'Invalid event type for first snapshot'\n );\n debugAssert(\n !lastDoc ||\n newQueryComparator(querySnapshot._snapshot.query)(\n lastDoc,\n change.doc\n ) < 0,\n 'Got added events in wrong order'\n );\n const doc = new QueryDocumentSnapshot(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n lastDoc = change.doc;\n return {\n type: 'added' as DocumentChangeType,\n doc,\n oldIndex: -1,\n newIndex: index++\n };\n });\n } else {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let indexTracker = querySnapshot._snapshot.oldDocs;\n return querySnapshot._snapshot.docChanges\n .filter(\n change => includeMetadataChanges || change.type !== ChangeType.Metadata\n )\n .map(change => {\n const doc = new QueryDocumentSnapshot(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n let oldIndex = -1;\n let newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker.indexOf(change.doc.key);\n debugAssert(oldIndex >= 0, 'Index for document not found');\n indexTracker = indexTracker.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker = indexTracker.add(change.doc);\n newIndex = indexTracker.indexOf(change.doc.key);\n }\n return {\n type: resultChangeType(change.type),\n doc,\n oldIndex,\n newIndex\n };\n });\n }\n}\n\nexport function resultChangeType(type: ChangeType): DocumentChangeType {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n left._firestore === right._firestore &&\n queryEqual(left.query, right.query) &&\n left.metadata.isEqual(right.metadata) &&\n left._snapshot.isEqual(right._snapshot)\n );\n }\n\n return false;\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 } from '@firebase/util';\n\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver\n} from '../api/observer';\nimport { ListenerDataSource } from '../core/event_manager';\nimport {\n firestoreClientAddSnapshotsInSyncListener,\n firestoreClientGetDocumentFromLocalCache,\n firestoreClientGetDocumentsFromLocalCache,\n firestoreClientGetDocumentsViaSnapshotListener,\n firestoreClientGetDocumentViaSnapshotListener,\n firestoreClientListen,\n firestoreClientWrite\n} from '../core/firestore_client';\nimport { newQueryForPath, Query as InternalQuery } from '../core/query';\nimport { ViewSnapshot } from '../core/view_snapshot';\nimport { Bytes } from '../lite-api/bytes';\nimport { FieldPath } from '../lite-api/field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from '../lite-api/query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from '../lite-api/reference';\nimport { applyFirestoreDataConverter } from '../lite-api/reference_impl';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs\n} from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { DocumentSnapshot, QuerySnapshot, SnapshotMetadata } from './snapshot';\n\n/**\n * An options object that can be passed to {@link (onSnapshot:1)} and {@link\n * QuerySnapshot.docChanges} to control which types of changes to include in the\n * result set.\n */\nexport interface SnapshotListenOptions {\n /**\n * Include a change even if only the metadata of the query or of a document\n * changed. Default is false.\n */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Set the source the query listens to. Default to \"default\", which\n * listens to both cache and server.\n */\n readonly source?: ListenSource;\n}\n\n/**\n * Describe the source a query listens to.\n *\n * Set to `default` to listen to both cache and server changes. Set to `cache`\n * to listen to changes in cache only.\n */\nexport type ListenSource = 'default' | 'cache';\n\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(\n client,\n reference._key\n ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\nexport class ExpUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromCache(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(\n doc =>\n new DocumentSnapshot(\n firestore,\n userDataWriter,\n reference._key,\n doc,\n new SnapshotMetadata(\n doc !== null && doc.hasLocalMutations,\n /* fromCache= */ true\n ),\n reference.converter\n )\n );\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, {\n source: 'server'\n }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n validateHasExplicitOrderByForLimitToLast(query._query);\n return firestoreClientGetDocumentsViaSnapshotListener(\n client,\n query._query\n ).then(\n snapshot =>\n new QuerySnapshot(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromCache<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsFromLocalCache(client, query._query).then(\n snapshot =>\n new QuerySnapshot(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, {\n source: 'server'\n }).then(\n snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n}\n\n/**\n * Writes to the document referred to by this `DocumentReference`. If the\n * document does not yet exist, it will be created.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @returns A Promise resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as WithFieldValue,\n options\n );\n const dataReader = newUserDataReader(firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const mutation = parsed.toMutation(reference._key, Precondition.none());\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const dataReader = newUserDataReader(firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const mutation = parsed.toMutation(reference._key, Precondition.exists(true));\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n const firestore = cast(reference.firestore, Firestore);\n const mutations = [new DeleteMutation(reference._key, Precondition.none())];\n return executeWrite(firestore, mutations);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n const firestore = cast(reference.firestore, Firestore);\n\n const docRef = doc(reference);\n const convertedValue = applyFirestoreDataConverter(reference.converter, data);\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n reference.converter !== null,\n {}\n );\n\n const mutation = parsed.toMutation(docRef._key, Precondition.exists(false));\n return executeWrite(firestore, [mutation]).then(() => docRef);\n}\n\n/**\n * A function returned by `onSnapshot()` that removes the listener when invoked.\n */\nexport interface Unsubscribe {\n /** Removes the listener when invoked. */\n (): void;\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n reference: DocumentReference,\n observer: {\n next?: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n reference: DocumentReference,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n reference: DocumentReference,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n reference: DocumentReference,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n query: Query,\n observer: {\n next?: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n query: Query,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n query: Query,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n query: Query,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\nexport function onSnapshot(\n reference:\n | Query\n | DocumentReference,\n ...args: unknown[]\n): Unsubscribe {\n reference = getModularInstance(reference);\n\n let options: SnapshotListenOptions = {\n includeMetadataChanges: false,\n source: 'default'\n };\n let currArg = 0;\n if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) {\n options = args[currArg] as SnapshotListenOptions;\n currArg++;\n }\n\n const internalOptions = {\n includeMetadataChanges: options.includeMetadataChanges,\n source: options.source as ListenerDataSource\n };\n\n if (isPartialObserver(args[currArg])) {\n const userObserver = args[currArg] as PartialObserver<\n QuerySnapshot\n >;\n args[currArg] = userObserver.next?.bind(userObserver);\n args[currArg + 1] = userObserver.error?.bind(userObserver);\n args[currArg + 2] = userObserver.complete?.bind(userObserver);\n }\n\n let observer: PartialObserver;\n let firestore: Firestore;\n let internalQuery: InternalQuery;\n\n if (reference instanceof DocumentReference) {\n firestore = cast(reference.firestore, Firestore);\n internalQuery = newQueryForPath(reference._key.path);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (\n args[currArg] as NextFn>\n )(\n convertToDocSnapshot(\n firestore,\n reference as DocumentReference,\n snapshot\n )\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n } else {\n const query = cast>(reference, Query);\n firestore = cast(query.firestore, Firestore);\n internalQuery = query._query;\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (args[currArg] as NextFn>)(\n new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n\n validateHasExplicitOrderByForLimitToLast(reference._query);\n }\n\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientListen(\n client,\n internalQuery,\n internalOptions,\n observer\n );\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use SnapshotMetadata in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The instance of Firestore for synchronizing snapshots.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n observer: {\n next?: (value: void) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use `SnapshotMetadata` in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The `Firestore` instance for synchronizing snapshots.\n * @param onSync - A callback to be called every time all snapshot listeners are\n * in sync with each other.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n onSync: () => void\n): Unsubscribe;\nexport function onSnapshotsInSync(\n firestore: Firestore,\n arg: unknown\n): Unsubscribe {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const observer = isPartialObserver(arg)\n ? (arg as PartialObserver)\n : {\n next: arg as () => void\n };\n\n return firestoreClientAddSnapshotsInSyncListener(client, observer);\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */\nexport function executeWrite(\n firestore: Firestore,\n mutations: Mutation[]\n): Promise {\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWrite(client, mutations);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */\nfunction convertToDocSnapshot(\n firestore: Firestore,\n ref: DocumentReference,\n snapshot: ViewSnapshot\n): DocumentSnapshot {\n debugAssert(\n snapshot.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n const doc = snapshot.docs.get(ref._key);\n\n const userDataWriter = new ExpUserDataWriter(firestore);\n return new DocumentSnapshot(\n firestore,\n userDataWriter,\n ref._key,\n doc,\n new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache),\n ref.converter\n );\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 { AggregateField, AggregateSpec, DocumentData, Query } from '../api';\nimport { AggregateImpl } from '../core/aggregate';\nimport { firestoreClientRunAggregateQuery } from '../core/firestore_client';\nimport { count } from '../lite-api/aggregate';\nimport { AggregateQuerySnapshot } from '../lite-api/aggregate_types';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\n\nexport {\n aggregateQuerySnapshotEqual,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../lite-api/aggregate';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCountFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregateFromServer(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregateFromServer<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return firestoreClientRunAggregateQuery(\n client,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\n/**\n * Converts the core aggregration result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new ExpUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\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 IndexedDbOfflineComponentProvider,\n LruGcMemoryOfflineComponentProvider,\n MemoryOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from '../core/component_provider';\n\n/* eslint @typescript-eslint/consistent-type-definitions: [\"error\", \"type\"] */\n/**\n * Provides an in-memory cache to the SDK. This is the default cache unless explicitly\n * configured otherwise.\n *\n * To use, create an instance using the factory function {@link memoryLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type MemoryLocalCache = {\n kind: 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n};\n\nclass MemoryLocalCacheImpl implements MemoryLocalCache {\n kind: 'memory' = 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n\n constructor(settings?: MemoryCacheSettings) {\n this._onlineComponentProvider = new OnlineComponentProvider();\n if (settings?.garbageCollector) {\n this._offlineComponentProvider =\n settings.garbageCollector._offlineComponentProvider;\n } else {\n this._offlineComponentProvider = new MemoryOfflineComponentProvider();\n }\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Provides a persistent cache backed by IndexedDb to the SDK.\n *\n * To use, create an instance using the factory function {@link persistentLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type PersistentLocalCache = {\n kind: 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProvider;\n};\n\nclass PersistentLocalCacheImpl implements PersistentLocalCache {\n kind: 'persistent' = 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProvider;\n\n constructor(settings: PersistentCacheSettings | undefined) {\n let tabManager: PersistentTabManager;\n if (settings?.tabManager) {\n settings.tabManager._initialize(settings);\n tabManager = settings.tabManager;\n } else {\n tabManager = persistentSingleTabManager(undefined);\n tabManager._initialize(settings);\n }\n this._onlineComponentProvider = tabManager._onlineComponentProvider!;\n this._offlineComponentProvider = tabManager._offlineComponentProvider!;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Union type from all supported SDK cache layer.\n */\nexport type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;\n\n/**\n * Union type from all support gabage collectors for memory local cache.\n */\nexport type MemoryGarbageCollector =\n | MemoryEagerGarbageCollector\n | MemoryLruGarbageCollector;\n\n/**\n * A garbage collector deletes documents whenever they are not part of any\n * active queries, and have no local mutations attached to them.\n *\n * This collector tries to ensure lowest memory footprints from the SDK,\n * at the risk of documents not being cached for offline queries or for\n * direct queries to the cache.\n *\n * Use factory function {@link memoryEagerGarbageCollector()} to create an\n * instance of this collector.\n */\nexport type MemoryEagerGarbageCollector = {\n kind: 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n};\n\n/**\n * A garbage collector deletes Least-Recently-Used documents in multiple\n * batches.\n *\n * This collector is configured with a target size, and will only perform\n * collection when the cached documents exceed the target size. It avoids\n * querying backend repeated for the same query or document, at the risk\n * of having a larger memory footprint.\n *\n * Use factory function {@link memoryLruGarbageCollector()} to create a\n * instance of this collector.\n */\nexport type MemoryLruGarbageCollector = {\n kind: 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n};\n\nclass MemoryEagerGabageCollectorImpl implements MemoryEagerGarbageCollector {\n kind: 'memoryEager' = 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n\n constructor() {\n this._offlineComponentProvider = new MemoryOfflineComponentProvider();\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\nclass MemoryLruGabageCollectorImpl implements MemoryLruGarbageCollector {\n kind: 'memoryLru' = 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n\n constructor(cacheSize?: number) {\n this._offlineComponentProvider = new LruGcMemoryOfflineComponentProvider(\n cacheSize\n );\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */\nexport function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector {\n return new MemoryEagerGabageCollectorImpl();\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */\nexport function memoryLruGarbageCollector(settings?: {\n cacheSizeBytes?: number;\n}): MemoryLruGarbageCollector {\n return new MemoryLruGabageCollectorImpl(settings?.cacheSizeBytes);\n}\n\n/**\n * An settings object to configure an `MemoryLocalCache` instance.\n */\nexport type MemoryCacheSettings = {\n /**\n * The garbage collector to use, for the memory cache layer.\n * A `MemoryEagerGarbageCollector` is used when this is undefined.\n */\n garbageCollector?: MemoryGarbageCollector;\n};\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */\nexport function memoryLocalCache(\n settings?: MemoryCacheSettings\n): MemoryLocalCache {\n return new MemoryLocalCacheImpl(settings);\n}\n\n/**\n * An settings object to configure an `PersistentLocalCache` instance.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport type PersistentCacheSettings = {\n /**\n * An approximate cache size threshold for the on-disk data. If the cache\n * grows beyond this size, Firestore will start removing data that hasn't been\n * recently used. The SDK does not guarantee that the cache will stay below\n * that size, only that if the cache exceeds the given size, cleanup will be\n * attempted.\n *\n * The default value is 40 MB. The threshold must be set to at least 1 MB, and\n * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.\n */\n cacheSizeBytes?: number;\n\n /**\n * Specifies how multiple tabs/windows will be managed by the SDK.\n */\n tabManager?: PersistentTabManager;\n};\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport function persistentLocalCache(\n settings?: PersistentCacheSettings\n): PersistentLocalCache {\n return new PersistentLocalCacheImpl(settings);\n}\n\n/**\n * A tab manager supportting only one tab, no synchronization will be\n * performed across tabs.\n */\nexport type PersistentSingleTabManager = {\n kind: 'persistentSingleTab';\n /**\n * @internal\n */\n _initialize: (\n settings: Omit | undefined\n ) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProvider;\n};\n\nclass SingleTabManagerImpl implements PersistentSingleTabManager {\n kind: 'persistentSingleTab' = 'persistentSingleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProvider;\n\n constructor(private forceOwnership?: boolean) {}\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = new OnlineComponentProvider();\n this._offlineComponentProvider = new IndexedDbOfflineComponentProvider(\n this._onlineComponentProvider,\n settings?.cacheSizeBytes,\n this.forceOwnership\n );\n }\n}\n\n/**\n * A tab manager supporting multiple tabs. SDK will synchronize queries and\n * mutations done across all tabs using the SDK.\n */\nexport type PersistentMultipleTabManager = {\n kind: 'PersistentMultipleTab';\n /**\n * @internal\n */\n _initialize: (settings: Omit) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProvider;\n /**\n * @internal\n */\n\n _offlineComponentProvider?: OfflineComponentProvider;\n};\n\nclass MultiTabManagerImpl implements PersistentMultipleTabManager {\n kind: 'PersistentMultipleTab' = 'PersistentMultipleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProvider;\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = new OnlineComponentProvider();\n this._offlineComponentProvider = new MultiTabOfflineComponentProvider(\n this._onlineComponentProvider,\n settings?.cacheSizeBytes\n );\n }\n}\n\n/**\n * A union of all available tab managers.\n */\nexport type PersistentTabManager =\n | PersistentSingleTabManager\n | PersistentMultipleTabManager;\n\n/**\n * Type to configure an `PersistentSingleTabManager` instance.\n */\nexport type PersistentSingleTabManagerSettings = {\n /**\n * Whether to force-enable persistent (IndexedDB) cache for the client. This\n * cannot be used with multi-tab synchronization and is primarily intended for\n * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause\n * other tabs using IndexedDB cache to fail.\n */\n forceOwnership?: boolean;\n};\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */\nexport function persistentSingleTabManager(\n settings: PersistentSingleTabManagerSettings | undefined\n): PersistentSingleTabManager {\n return new SingleTabManagerImpl(settings?.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */\nexport function persistentMultipleTabManager(): PersistentMultipleTabManager {\n return new MultiTabManagerImpl();\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 { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\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 { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\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 { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n TransactionOptions as TranasactionOptionsInternal,\n DEFAULT_TRANSACTION_OPTIONS,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n _transaction: InternalTransaction\n ) {\n super(_firestore, _transaction);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new ExpUserDataWriter(this._firestore);\n return super\n .get(documentRef)\n .then(\n liteDocumentSnapshot =>\n new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n liteDocumentSnapshot._document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n ref.converter\n )\n );\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const optionsWithDefaults: TranasactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientTransaction(\n client,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n optionsWithDefaults\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 } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TranasactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n `BatchGetDocumentsRequest returned unexpected document: ${doc}`\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TranasactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\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 { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', 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 { WriteBatch } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { executeWrite } from './reference_impl';\n\nexport { WriteBatch };\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n ensureFirestoreConfigured(firestore);\n return new WriteBatch(firestore, mutations =>\n executeWrite(firestore, mutations)\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 { firestoreClientSetIndexConfiguration } from '../core/firestore_client';\nimport { fieldPathFromDotSeparatedString } from '../lite-api/user_data_reader';\nimport {\n FieldIndex,\n IndexKind,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\n/**\n * A single field element in an index configuration.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexField {\n /** The field path to index. */\n readonly fieldPath: string;\n /**\n * What type of array index to create. Set to `CONTAINS` for `array-contains`\n * and `array-contains-any` indexes.\n *\n * Only one of `arrayConfig` or `order` should be set;\n */\n readonly arrayConfig?: 'CONTAINS';\n /**\n * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for\n * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.\n *\n * Only one of `arrayConfig` or `order` should be set.\n */\n readonly order?: 'ASCENDING' | 'DESCENDING';\n\n [key: string]: unknown;\n}\n\n/**\n * The SDK definition of a Firestore index.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface Index {\n /** The ID of the collection to index. */\n readonly collectionGroup: string;\n /** A list of fields to index. */\n readonly fields?: IndexField[];\n\n [key: string]: unknown;\n}\n\n/**\n * A list of Firestore indexes to speed up local query execution.\n *\n * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}\n * for a description of the format of the index definition.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexConfiguration {\n /** A list of all Firestore indexes. */\n readonly indexes?: Index[];\n\n [key: string]: unknown;\n}\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. If IndexedDb is not\n * enabled, any index configuration is ignored.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param configuration -The index definition.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n configuration: IndexConfiguration\n): Promise;\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. Invoke either\n * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`\n * before setting an index configuration. If IndexedDb is not enabled, any\n * index configuration is ignored.\n *\n * The method accepts the JSON format exported by the Firebase CLI (`firebase\n * firestore:indexes`). If the JSON format is invalid, this method throws an\n * error.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param json -The JSON format exported by the Firebase CLI.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n json: string\n): Promise;\n\nexport function setIndexConfiguration(\n firestore: Firestore,\n jsonOrConfiguration: string | IndexConfiguration\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n if (\n !client._uninitializedComponentsProvider ||\n client._uninitializedComponentsProvider?._offlineKind === 'memory'\n ) {\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n logWarn('Cannot enable indexes when persistence is disabled');\n return Promise.resolve();\n }\n const parsedIndexes = parseIndexes(jsonOrConfiguration);\n return firestoreClientSetIndexConfiguration(client, parsedIndexes);\n}\n\nexport function parseIndexes(\n jsonOrConfiguration: string | IndexConfiguration\n): FieldIndex[] {\n const indexConfiguration =\n typeof jsonOrConfiguration === 'string'\n ? (tryParseJson(jsonOrConfiguration) as IndexConfiguration)\n : jsonOrConfiguration;\n const parsedIndexes: FieldIndex[] = [];\n\n if (Array.isArray(indexConfiguration.indexes)) {\n for (const index of indexConfiguration.indexes) {\n const collectionGroup = tryGetString(index, 'collectionGroup');\n\n const segments: IndexSegment[] = [];\n if (Array.isArray(index.fields)) {\n for (const field of index.fields) {\n const fieldPathString = tryGetString(field, 'fieldPath');\n const fieldPath = fieldPathFromDotSeparatedString(\n 'setIndexConfiguration',\n fieldPathString\n );\n\n if (field.arrayConfig === 'CONTAINS') {\n segments.push(new IndexSegment(fieldPath, IndexKind.CONTAINS));\n } else if (field.order === 'ASCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.ASCENDING));\n } else if (field.order === 'DESCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.DESCENDING));\n }\n }\n }\n\n parsedIndexes.push(\n new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n collectionGroup,\n segments,\n IndexState.empty()\n )\n );\n }\n }\n return parsedIndexes;\n}\n\nfunction tryParseJson(json: string): Record {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to parse JSON: ' + (e as Error)?.message\n );\n }\n}\n\nfunction tryGetString(data: Record, property: string): string {\n if (typeof data[property] !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Missing string value for: ' + property\n );\n }\n return data[property] as string;\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 firestoreClientDeleteAllFieldIndexes,\n firestoreClientSetPersistentCacheIndexAutoCreationEnabled,\n FirestoreClient\n} from '../core/firestore_client';\nimport { cast } from '../util/input_validation';\nimport { logDebug, logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\n/**\n * A `PersistentCacheIndexManager` for configuring persistent cache indexes used\n * for local query execution.\n *\n * To use, call `getPersistentCacheIndexManager()` to get an instance.\n */\nexport class PersistentCacheIndexManager {\n /** A type string to uniquely identify instances of this class. */\n readonly type: 'PersistentCacheIndexManager' = 'PersistentCacheIndexManager';\n\n /** @hideconstructor */\n constructor(readonly _client: FirestoreClient) {}\n}\n\n/**\n * Returns the PersistentCache Index Manager used by the given `Firestore`\n * object.\n *\n * @return The `PersistentCacheIndexManager` instance, or `null` if local\n * persistent storage is not in use.\n */\nexport function getPersistentCacheIndexManager(\n firestore: Firestore\n): PersistentCacheIndexManager | null {\n firestore = cast(firestore, Firestore);\n\n const cachedInstance = persistentCacheIndexManagerByFirestore.get(firestore);\n if (cachedInstance) {\n return cachedInstance;\n }\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider?._offlineKind !== 'persistent') {\n return null;\n }\n\n const instance = new PersistentCacheIndexManager(client);\n persistentCacheIndexManagerByFirestore.set(firestore, instance);\n return instance;\n}\n\n/**\n * Enables the SDK to create persistent cache indexes automatically for local\n * query execution when the SDK believes cache indexes can help improve\n * performance.\n *\n * This feature is disabled by default.\n */\nexport function enablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, true);\n}\n\n/**\n * Stops creating persistent cache indexes automatically for local query\n * execution. The indexes which have been created by calling\n * `enablePersistentCacheIndexAutoCreation()` still take effect.\n */\nexport function disablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, false);\n}\n\n/**\n * Removes all persistent cache indexes.\n *\n * Please note this function will also deletes indexes generated by\n * `setIndexConfiguration()`, which is deprecated.\n */\nexport function deleteAllPersistentCacheIndexes(\n indexManager: PersistentCacheIndexManager\n): void {\n indexManager._client.verifyNotTerminated();\n\n const promise = firestoreClientDeleteAllFieldIndexes(indexManager._client);\n\n promise\n .then(_ => logDebug('deleting all persistent cache indexes succeeded'))\n .catch(error =>\n logWarn('deleting all persistent cache indexes failed', error)\n );\n}\n\nfunction setPersistentCacheIndexAutoCreationEnabled(\n indexManager: PersistentCacheIndexManager,\n isEnabled: boolean\n): void {\n indexManager._client.verifyNotTerminated();\n\n const promise = firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n indexManager._client,\n isEnabled\n );\n\n promise\n .then(_ =>\n logDebug(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} succeeded`\n )\n )\n .catch(error =>\n logWarn(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} failed`,\n error\n )\n );\n}\n\n/**\n * Maps `Firestore` instances to their corresponding\n * `PersistentCacheIndexManager` instances.\n *\n * Use a `WeakMap` so that the mapping will be automatically dropped when the\n * `Firestore` instance is garbage collected. This emulates a private member\n * as described in https://goo.gle/454yvug.\n */\nconst persistentCacheIndexManagerByFirestore = new WeakMap<\n Firestore,\n PersistentCacheIndexManager\n>();\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ensureFirestoreConfigured, Firestore } from '../api/database';\nimport { AggregateImpl } from '../core/aggregate';\nimport { queryToAggregateTarget, queryToTarget } from '../core/query';\nimport { AggregateSpec } from '../lite-api/aggregate_types';\nimport { Query } from '../lite-api/reference';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { toQueryTarget, toRunAggregationQueryRequest } from './serializer';\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `QueryTarget` representation of the given query. Returns `null`\n * if the Firestore client associated with the given query has not been\n * initialized or has been terminated.\n *\n * @param query - The Query to convert to proto representation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _internalQueryToProtoQueryTarget(query: Query): any {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n return toQueryTarget(serializer!, queryToTarget(query._query)).queryTarget;\n}\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns `RunAggregationQueryRequest` which contains the proto representation\n * of the given aggregation query request. Returns null if the Firestore client\n * associated with the given query has not been initialized or has been\n * terminated.\n *\n * @param query - The Query to convert to proto representation.\n * @param aggregateSpec - The set of aggregations and their aliases.\n */\nexport function _internalAggregationQueryToProtoRunAggregationQueryRequest<\n AggregateSpecType extends AggregateSpec\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n>(query: Query, aggregateSpec: AggregateSpecType): any {\n const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n\n return toRunAggregationQueryRequest(\n serializer!,\n queryToAggregateTarget(query._query),\n aggregates,\n /* skipAliasing= */ true\n ).request;\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 { Unsubscribe } from '../api/reference_impl';\n\nimport {\n setTestingHooksSpi,\n ExistenceFilterMismatchInfo,\n TestingHooksSpi\n} from './testing_hooks_spi';\n\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('instances of this class should not be created');\n }\n\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */\n static onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback);\n }\n}\n\n/**\n * The signature of callbacks registered with\n * `TestingUtils.onExistenceFilterMismatch()`.\n *\n * The return value, if any, is ignored.\n *\n * @internal\n */\nexport type ExistenceFilterMismatchCallback = (\n info: ExistenceFilterMismatchInfo\n) => unknown;\n\n/**\n * The implementation of `TestingHooksSpi`.\n */\nclass TestingHooksSpiImpl implements TestingHooksSpi {\n private readonly existenceFilterMismatchCallbacksById = new Map<\n Symbol,\n ExistenceFilterMismatchCallback\n >();\n\n private constructor() {}\n\n static get instance(): TestingHooksSpiImpl {\n if (!testingHooksSpiImplInstance) {\n testingHooksSpiImplInstance = new TestingHooksSpiImpl();\n setTestingHooksSpi(testingHooksSpiImplInstance);\n }\n return testingHooksSpiImplInstance;\n }\n\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void {\n this.existenceFilterMismatchCallbacksById.forEach(callback =>\n callback(info)\n );\n }\n\n onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n const id = Symbol();\n const callbacks = this.existenceFilterMismatchCallbacksById;\n callbacks.set(id, callback);\n return () => callbacks.delete(id);\n }\n}\n\nlet testingHooksSpiImplInstance: TestingHooksSpiImpl | null = null;\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 {\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 {\n FirebaseAppCheckTokenProvider,\n FirebaseAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { Firestore } from './api/database';\nimport { databaseIdFromApp } from './core/database_info';\n\nexport function registerFirestore(\n variant?: string,\n useFetchStreams = true\n): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'firestore',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new FirebaseAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new FirebaseAppCheckTokenProvider(\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n settings = { useFetchStreams, ...settings };\n firestoreInstance._setSettings(settings);\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n", "/**\n * Cloud Firestore\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 { Firestore } from './api/database';\nimport { registerFirestore } from './register';\n\nregisterFirestore();\n\nexport * from './api';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\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 */\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nregisterVersion(name, version, 'app');\nexport * from '@firebase/app';\n", "// Add your own firebase credentials here.\nexport default {};\n", "import { initializeApp } from 'firebase/app';\nimport config from '../config/firebase.js';\n\nconst init = function () {\n if (!config.apiKey) {\n throw Error('Firebase config is not setup.');\n }\n initializeApp(config);\n};\n\nexport {\n init\n};\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\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;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\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: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\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); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\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; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\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);\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); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\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\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\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\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof 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\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\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/**\n * An enum of factors that may be used for multifactor authentication.\n *\n * @public\n */\nexport const FactorId = {\n /** Phone as second factor */\n PHONE: 'phone',\n TOTP: 'totp'\n} as const;\n\n/**\n * Enumeration of supported providers.\n *\n * @public\n */\nexport const ProviderId = {\n /** Facebook provider ID */\n FACEBOOK: 'facebook.com',\n /** GitHub provider ID */\n GITHUB: 'github.com',\n /** Google provider ID */\n GOOGLE: 'google.com',\n /** Password provider */\n PASSWORD: 'password',\n /** Phone provider */\n PHONE: 'phone',\n /** Twitter provider ID */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported sign-in methods.\n *\n * @public\n */\nexport const SignInMethod = {\n /** Email link sign in method */\n EMAIL_LINK: 'emailLink',\n /** Email/password sign in method */\n EMAIL_PASSWORD: 'password',\n /** Facebook sign in method */\n FACEBOOK: 'facebook.com',\n /** GitHub sign in method */\n GITHUB: 'github.com',\n /** Google sign in method */\n GOOGLE: 'google.com',\n /** Phone sign in method */\n PHONE: 'phone',\n /** Twitter sign in method */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported operation types.\n *\n * @public\n */\nexport const OperationType = {\n /** Operation involving linking an additional provider to an already signed-in user. */\n LINK: 'link',\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\n REAUTHENTICATE: 'reauthenticate',\n /** Operation involving signing in a user. */\n SIGN_IN: 'signIn'\n} as const;\n\n/**\n * An enumeration of the possible email action types.\n *\n * @public\n */\nexport const ActionCodeOperation = {\n /** The email link sign-in action. */\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n /** The password reset action. */\n PASSWORD_RESET: 'PASSWORD_RESET',\n /** The email revocation action. */\n RECOVER_EMAIL: 'RECOVER_EMAIL',\n /** The revert second factor addition email action. */\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\n /** The revert second factor addition email action. */\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n /** The email verification action. */\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n} as const;\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 { AuthErrorMap, User } from '../model/public_types';\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { AppName } from '../model/auth';\nimport { AuthCredential } from './credentials';\n\n/**\n * Enumeration of Firebase Auth error codes.\n *\n * @internal\n */\nexport const enum AuthErrorCode {\n ADMIN_ONLY_OPERATION = 'admin-restricted-operation',\n ARGUMENT_ERROR = 'argument-error',\n APP_NOT_AUTHORIZED = 'app-not-authorized',\n APP_NOT_INSTALLED = 'app-not-installed',\n CAPTCHA_CHECK_FAILED = 'captcha-check-failed',\n CODE_EXPIRED = 'code-expired',\n CORDOVA_NOT_READY = 'cordova-not-ready',\n CORS_UNSUPPORTED = 'cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE = 'credential-already-in-use',\n CREDENTIAL_MISMATCH = 'custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH = 'dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',\n EMAIL_EXISTS = 'email-already-in-use',\n EMULATOR_CONFIG_FAILED = 'emulator-config-failed',\n EXPIRED_OOB_CODE = 'expired-action-code',\n EXPIRED_POPUP_REQUEST = 'cancelled-popup-request',\n INTERNAL_ERROR = 'internal-error',\n INVALID_API_KEY = 'invalid-api-key',\n INVALID_APP_CREDENTIAL = 'invalid-app-credential',\n INVALID_APP_ID = 'invalid-app-id',\n INVALID_AUTH = 'invalid-user-token',\n INVALID_AUTH_EVENT = 'invalid-auth-event',\n INVALID_CERT_HASH = 'invalid-cert-hash',\n INVALID_CODE = 'invalid-verification-code',\n INVALID_CONTINUE_URI = 'invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION = 'invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN = 'invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN = 'invalid-dynamic-link-domain',\n INVALID_EMAIL = 'invalid-email',\n INVALID_EMULATOR_SCHEME = 'invalid-emulator-scheme',\n INVALID_CREDENTIAL = 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD = 'invalid-message-payload',\n INVALID_MFA_SESSION = 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID = 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER = 'invalid-oauth-provider',\n INVALID_OOB_CODE = 'invalid-action-code',\n INVALID_ORIGIN = 'unauthorized-domain',\n INVALID_PASSWORD = 'wrong-password',\n INVALID_PERSISTENCE = 'invalid-persistence-type',\n INVALID_PHONE_NUMBER = 'invalid-phone-number',\n INVALID_PROVIDER_ID = 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL = 'invalid-recipient-email',\n INVALID_SENDER = 'invalid-sender',\n INVALID_SESSION_INFO = 'invalid-verification-id',\n INVALID_TENANT_ID = 'invalid-tenant-id',\n LOGIN_BLOCKED = 'login-blocked',\n MFA_INFO_NOT_FOUND = 'multi-factor-info-not-found',\n MFA_REQUIRED = 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME = 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL = 'missing-app-credential',\n MISSING_AUTH_DOMAIN = 'auth-domain-config-required',\n MISSING_CODE = 'missing-verification-code',\n MISSING_CONTINUE_URI = 'missing-continue-uri',\n MISSING_IFRAME_START = 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID = 'missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE = 'missing-or-invalid-nonce',\n MISSING_MFA_INFO = 'missing-multi-factor-info',\n MISSING_MFA_SESSION = 'missing-multi-factor-session',\n MISSING_PHONE_NUMBER = 'missing-phone-number',\n MISSING_PASSWORD = 'missing-password',\n MISSING_SESSION_INFO = 'missing-verification-id',\n MODULE_DESTROYED = 'app-deleted',\n NEED_CONFIRMATION = 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED = 'network-request-failed',\n NULL_USER = 'null-user',\n NO_AUTH_EVENT = 'no-auth-event',\n NO_SUCH_PROVIDER = 'no-such-provider',\n OPERATION_NOT_ALLOWED = 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED = 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED = 'popup-blocked',\n POPUP_CLOSED_BY_USER = 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED = 'provider-already-linked',\n QUOTA_EXCEEDED = 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER = 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING = 'redirect-operation-pending',\n REJECTED_CREDENTIAL = 'rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED = 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH = 'tenant-id-mismatch',\n TIMEOUT = 'timeout',\n TOKEN_EXPIRED = 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'too-many-requests',\n UNAUTHORIZED_DOMAIN = 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR = 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE = 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION = 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL = 'unverified-email',\n USER_CANCELLED = 'user-cancelled',\n USER_DELETED = 'user-not-found',\n USER_DISABLED = 'user-disabled',\n USER_MISMATCH = 'user-mismatch',\n USER_SIGNED_OUT = 'user-signed-out',\n WEAK_PASSWORD = 'weak-password',\n WEB_STORAGE_UNSUPPORTED = 'web-storage-unsupported',\n ALREADY_INITIALIZED = 'already-initialized',\n RECAPTCHA_NOT_ENABLED = 'recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN = 'missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN = 'invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION = 'invalid-recaptcha-action',\n MISSING_CLIENT_TYPE = 'missing-client-type',\n MISSING_RECAPTCHA_VERSION = 'missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION = 'invalid-recaptcha-version',\n INVALID_REQ_TYPE = 'invalid-req-type',\n UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION = 'unsupported-password-policy-schema-version',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'password-does-not-meet-requirements'\n}\n\nfunction _debugErrorMap(): ErrorMap {\n return {\n [AuthErrorCode.ADMIN_ONLY_OPERATION]:\n 'This operation is restricted to administrators only.',\n [AuthErrorCode.ARGUMENT_ERROR]: '',\n [AuthErrorCode.APP_NOT_AUTHORIZED]:\n \"This app, identified by the domain where it's hosted, is not \" +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.',\n [AuthErrorCode.APP_NOT_INSTALLED]:\n 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.',\n [AuthErrorCode.CAPTCHA_CHECK_FAILED]:\n 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.',\n [AuthErrorCode.CODE_EXPIRED]:\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [AuthErrorCode.CORDOVA_NOT_READY]: 'Cordova framework is not ready.',\n [AuthErrorCode.CORS_UNSUPPORTED]: 'This browser is not supported.',\n [AuthErrorCode.CREDENTIAL_ALREADY_IN_USE]:\n 'This credential is already associated with a different user account.',\n [AuthErrorCode.CREDENTIAL_MISMATCH]:\n 'The custom token corresponds to a different audience.',\n [AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED]:\n 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION]:\n 'Multi-factor users must always have a verified email.',\n [AuthErrorCode.EMAIL_EXISTS]:\n 'The email address is already in use by another account.',\n [AuthErrorCode.EMULATOR_CONFIG_FAILED]:\n 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',\n [AuthErrorCode.EXPIRED_POPUP_REQUEST]:\n 'This operation has been cancelled due to another conflicting popup being opened.',\n [AuthErrorCode.INTERNAL_ERROR]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_APP_CREDENTIAL]:\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [AuthErrorCode.INVALID_APP_ID]:\n 'The mobile app identifier is not registed for the current project.',\n [AuthErrorCode.INVALID_AUTH]:\n \"This user's credential isn't valid for this project. This can happen \" +\n \"if the user's token has been tampered with, or if the user isn't for \" +\n 'the project associated with this API key.',\n [AuthErrorCode.INVALID_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_CODE]:\n 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure to use the ' +\n 'verification code provided by the user.',\n [AuthErrorCode.INVALID_CONTINUE_URI]:\n 'The continue URL provided in the request is invalid.',\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]:\n 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.',\n [AuthErrorCode.INVALID_CUSTOM_TOKEN]:\n 'The custom token format is incorrect. Please check the documentation.',\n [AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN]:\n 'The provided dynamic link domain is not configured or authorized for the current project.',\n [AuthErrorCode.INVALID_EMAIL]: 'The email address is badly formatted.',\n [AuthErrorCode.INVALID_EMULATOR_SCHEME]:\n 'Emulator URL must start with a valid scheme (http:// or https://).',\n [AuthErrorCode.INVALID_API_KEY]:\n 'Your API key is invalid, please check you have copied it correctly.',\n [AuthErrorCode.INVALID_CERT_HASH]:\n 'The SHA-1 certificate hash provided is invalid.',\n [AuthErrorCode.INVALID_CREDENTIAL]:\n 'The supplied auth credential is incorrect, malformed or has expired.',\n [AuthErrorCode.INVALID_MESSAGE_PAYLOAD]:\n 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_MFA_SESSION]:\n 'The request does not contain a valid proof of first factor successful sign-in.',\n [AuthErrorCode.INVALID_OAUTH_PROVIDER]:\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [AuthErrorCode.INVALID_OAUTH_CLIENT_ID]:\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [AuthErrorCode.INVALID_ORIGIN]:\n 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.',\n [AuthErrorCode.INVALID_OOB_CODE]:\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [AuthErrorCode.INVALID_PASSWORD]:\n 'The password is invalid or the user does not have a password.',\n [AuthErrorCode.INVALID_PERSISTENCE]:\n 'The specified persistence type is invalid. It can only be local, session or none.',\n [AuthErrorCode.INVALID_PHONE_NUMBER]:\n 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].',\n [AuthErrorCode.INVALID_PROVIDER_ID]:\n 'The specified provider ID is invalid.',\n [AuthErrorCode.INVALID_RECIPIENT_EMAIL]:\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [AuthErrorCode.INVALID_SENDER]:\n 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_SESSION_INFO]:\n 'The verification ID used to create the phone auth credential is invalid.',\n [AuthErrorCode.INVALID_TENANT_ID]:\n \"The Auth instance's tenant ID is invalid.\",\n [AuthErrorCode.LOGIN_BLOCKED]:\n 'Login blocked by user-provided method: {$originalMessage}',\n [AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME]:\n 'An Android Package Name must be provided if the Android App is required to be installed.',\n [AuthErrorCode.MISSING_AUTH_DOMAIN]:\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [AuthErrorCode.MISSING_APP_CREDENTIAL]:\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [AuthErrorCode.MISSING_CODE]:\n 'The phone auth credential was created with an empty SMS verification code.',\n [AuthErrorCode.MISSING_CONTINUE_URI]:\n 'A continue URL must be provided in the request.',\n [AuthErrorCode.MISSING_IFRAME_START]: 'An internal AuthError has occurred.',\n [AuthErrorCode.MISSING_IOS_BUNDLE_ID]:\n 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [AuthErrorCode.MISSING_OR_INVALID_NONCE]:\n 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.',\n [AuthErrorCode.MISSING_PASSWORD]: 'A non-empty password must be provided',\n [AuthErrorCode.MISSING_MFA_INFO]:\n 'No second factor identifier is provided.',\n [AuthErrorCode.MISSING_MFA_SESSION]:\n 'The request is missing proof of first factor successful sign-in.',\n [AuthErrorCode.MISSING_PHONE_NUMBER]:\n 'To send verification codes, provide a phone number for the recipient.',\n [AuthErrorCode.MISSING_SESSION_INFO]:\n 'The phone auth credential was created with an empty verification ID.',\n [AuthErrorCode.MODULE_DESTROYED]:\n 'This instance of FirebaseApp has been deleted.',\n [AuthErrorCode.MFA_INFO_NOT_FOUND]:\n 'The user does not have a second factor matching the identifier provided.',\n [AuthErrorCode.MFA_REQUIRED]:\n 'Proof of ownership of a second factor is required to complete sign-in.',\n [AuthErrorCode.NEED_CONFIRMATION]:\n 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.',\n [AuthErrorCode.NETWORK_REQUEST_FAILED]:\n 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [AuthErrorCode.NO_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.NO_SUCH_PROVIDER]:\n 'User was not linked to an account with the given provider.',\n [AuthErrorCode.NULL_USER]:\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [AuthErrorCode.OPERATION_NOT_ALLOWED]:\n 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.',\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]:\n 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.',\n [AuthErrorCode.POPUP_BLOCKED]:\n 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [AuthErrorCode.POPUP_CLOSED_BY_USER]:\n 'The popup has been closed by the user before finalizing the operation.',\n [AuthErrorCode.PROVIDER_ALREADY_LINKED]:\n 'User can only be linked to one identity for the given provider.',\n [AuthErrorCode.QUOTA_EXCEEDED]:\n \"The project's quota for this operation has been exceeded.\",\n [AuthErrorCode.REDIRECT_CANCELLED_BY_USER]:\n 'The redirect operation has been cancelled by the user before finalizing.',\n [AuthErrorCode.REDIRECT_OPERATION_PENDING]:\n 'A redirect sign-in operation is already pending.',\n [AuthErrorCode.REJECTED_CREDENTIAL]:\n 'The request contains malformed or mismatching credentials.',\n [AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED]:\n 'The second factor is already enrolled on this account.',\n [AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED]:\n 'The maximum allowed number of second factors on a user has been exceeded.',\n [AuthErrorCode.TENANT_ID_MISMATCH]:\n \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [AuthErrorCode.TIMEOUT]: 'The operation has timed out.',\n [AuthErrorCode.TOKEN_EXPIRED]:\n \"The user's credential is no longer valid. The user must sign in again.\",\n [AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER]:\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [AuthErrorCode.UNAUTHORIZED_DOMAIN]:\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\n [AuthErrorCode.UNSUPPORTED_FIRST_FACTOR]:\n 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\n [AuthErrorCode.UNSUPPORTED_PERSISTENCE]:\n 'The current environment does not support the specified persistence type.',\n [AuthErrorCode.UNSUPPORTED_TENANT_OPERATION]:\n 'This operation is not supported in a multi-tenant context.',\n [AuthErrorCode.UNVERIFIED_EMAIL]:\n 'The operation requires a verified email.',\n [AuthErrorCode.USER_CANCELLED]:\n 'The user did not grant your application the permissions it requested.',\n [AuthErrorCode.USER_DELETED]:\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [AuthErrorCode.USER_DISABLED]:\n 'The user account has been disabled by an administrator.',\n [AuthErrorCode.USER_MISMATCH]:\n 'The supplied credentials do not correspond to the previously signed in user.',\n [AuthErrorCode.USER_SIGNED_OUT]: '',\n [AuthErrorCode.WEAK_PASSWORD]:\n 'The password must be 6 characters long or more.',\n [AuthErrorCode.WEB_STORAGE_UNSUPPORTED]:\n 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [AuthErrorCode.ALREADY_INITIALIZED]:\n 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.',\n [AuthErrorCode.MISSING_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is invalid when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_ACTION]:\n 'The reCAPTCHA action is invalid when sending request to the backend.',\n [AuthErrorCode.RECAPTCHA_NOT_ENABLED]:\n 'reCAPTCHA Enterprise integration is not enabled for this project.',\n [AuthErrorCode.MISSING_CLIENT_TYPE]:\n 'The reCAPTCHA client type is missing when sending request to the backend.',\n [AuthErrorCode.MISSING_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_REQ_TYPE]: 'Invalid request parameters.',\n [AuthErrorCode.INVALID_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is invalid when sending request to the backend.',\n [AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION]:\n 'The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.',\n [AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n 'The password does not meet the requirements.'\n };\n}\n\nexport interface ErrorMapRetriever extends AuthErrorMap {\n (): ErrorMap;\n}\n\nfunction _prodErrorMap(): ErrorMap {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n } as ErrorMap;\n}\n\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const debugErrorMap: AuthErrorMap = _debugErrorMap;\n\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const prodErrorMap: AuthErrorMap = _prodErrorMap;\n\nexport interface NamedErrorParams {\n appName: AppName;\n credential?: AuthCredential;\n email?: string;\n phoneNumber?: string;\n tenantId?: string;\n user?: User;\n _serverResponse?: object;\n}\n\n/**\n * @internal\n */\ntype GenericAuthErrorParams = {\n [key in Exclude<\n AuthErrorCode,\n | AuthErrorCode.ARGUMENT_ERROR\n | AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n | AuthErrorCode.INTERNAL_ERROR\n | AuthErrorCode.MFA_REQUIRED\n | AuthErrorCode.NO_AUTH_EVENT\n | AuthErrorCode.OPERATION_NOT_SUPPORTED\n >]: {\n appName?: AppName;\n email?: string;\n phoneNumber?: string;\n message?: string;\n };\n};\n\n/**\n * @internal\n */\nexport interface AuthErrorParams extends GenericAuthErrorParams {\n [AuthErrorCode.ARGUMENT_ERROR]: { appName?: AppName };\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]: { appName?: AppName };\n [AuthErrorCode.INTERNAL_ERROR]: { appName?: AppName };\n [AuthErrorCode.LOGIN_BLOCKED]: {\n appName?: AppName;\n originalMessage?: string;\n };\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]: { appName?: AppName };\n [AuthErrorCode.NO_AUTH_EVENT]: { appName?: AppName };\n [AuthErrorCode.MFA_REQUIRED]: {\n appName: AppName;\n _serverResponse: IdTokenMfaResponse;\n };\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]: {\n appName: AppName;\n missingPlugin?: string;\n };\n}\n\nexport const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory<\n AuthErrorCode,\n AuthErrorParams\n>('auth', 'Firebase', _prodErrorMap());\n\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nexport const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_LOGIN_CREDENTIALS: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized',\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\n} as const;\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 { Logger, LogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '@firebase/app';\n\nexport { LogLevel };\n\nconst logClient = new Logger('@firebase/auth');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function _getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\nexport function _setLogLevel(newLevel: LogLevel): void {\n logClient.logLevel = newLevel;\n}\n\nexport function _logDebug(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n logClient.debug(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logWarn(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logError(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\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 { Auth } from '../../model/public_types';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../../model/auth';\nimport {\n _DEFAULT_AUTH_ERROR_FACTORY,\n AuthErrorCode,\n AuthErrorParams,\n prodErrorMap,\n ErrorMapRetriever\n} from '../errors';\nimport { _logError } from './log';\n\ntype AuthErrorListParams = K extends keyof AuthErrorParams\n ? [AuthErrorParams[K]]\n : [];\ntype LessAppName = Omit;\n\n/**\n * Unconditionally fails, throwing a developer facing INTERNAL_ERROR\n *\n * @example\n * ```javascript\n * fail(auth, AuthErrorCode.MFA_REQUIRED); // Error: the MFA_REQUIRED error needs more params than appName\n * fail(auth, AuthErrorCode.MFA_REQUIRED, {serverResponse}); // Compiles\n * fail(AuthErrorCode.INTERNAL_ERROR); // Compiles; internal error does not need appName\n * fail(AuthErrorCode.USER_DELETED); // Error: USER_DELETED requires app name\n * fail(auth, AuthErrorCode.USER_DELETED); // Compiles; USER_DELETED _only_ needs app name\n * ```\n *\n * @param appName App name for tagging the error\n * @throws FirebaseError\n */\nexport function _fail(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): never;\nexport function _fail(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): never;\nexport function _fail(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): never {\n throw createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _createError(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): FirebaseError;\nexport function _createError(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): FirebaseError;\nexport function _createError(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n return createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _errorWithCustomMessage(\n auth: Auth,\n code: AuthErrorCode,\n message: string\n): FirebaseError {\n const errorMap = {\n ...(prodErrorMap as ErrorMapRetriever)(),\n [code]: message\n };\n const factory = new ErrorFactory(\n 'auth',\n 'Firebase',\n errorMap\n );\n return factory.create(code, {\n appName: auth.name\n });\n}\n\nexport function _serverAppCurrentUserOperationNotSupportedError(\n auth: Auth\n): FirebaseError {\n return _errorWithCustomMessage(\n auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED,\n 'Operations that alter the current user are not supported in conjunction with FirebaseServerApp'\n );\n}\n\nexport function _assertInstanceOf(\n auth: Auth,\n object: object,\n instance: unknown\n): void {\n const constructorInstance = instance as { new (...args: unknown[]): unknown };\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, AuthErrorCode.ARGUMENT_ERROR);\n }\n\n throw _errorWithCustomMessage(\n auth,\n AuthErrorCode.ARGUMENT_ERROR,\n `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`\n );\n }\n}\n\nfunction createErrorInternal(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n if (typeof authOrCode !== 'string') {\n const code = rest[0] as K;\n const fullParams = [...rest.slice(1)] as AuthErrorListParams;\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n\n return (authOrCode as AuthInternal)._errorFactory.create(\n code,\n ...fullParams\n );\n }\n\n return _DEFAULT_AUTH_ERROR_FACTORY.create(\n authOrCode,\n ...(rest as AuthErrorListParams)\n );\n}\n\nexport function _assert(\n assertion: unknown,\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): asserts assertion;\nexport function _assert(\n assertion: unknown,\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): asserts assertion;\nexport function _assert(\n assertion: unknown,\n authOrCode: Auth | K,\n ...rest: unknown[]\n): asserts assertion {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n\n// We really do want to accept literally any function type here\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype TypeExpectation = Function | string | MapType;\n\ninterface MapType extends Record {}\n\nclass Optional {\n constructor(readonly type: TypeExpectation) {}\n}\n\nexport function opt(type: TypeExpectation): Optional {\n return new Optional(type);\n}\n\n/**\n * Asserts the runtime types of arguments. The 'expected' field can be one of\n * a class, a string (representing a \"typeof\" call), or a record map of name\n * to type. Furthermore, the opt() function can be used to mark a field as\n * optional. For example:\n *\n * function foo(auth: Auth, profile: {displayName?: string}, update = false) {\n * assertTypes(arguments, [AuthImpl, {displayName: opt('string')}, opt('boolean')]);\n * }\n *\n * opt() can be used for any type:\n * function foo(auth?: Auth) {\n * assertTypes(arguments, [opt(AuthImpl)]);\n * }\n *\n * The string types can be or'd together, and you can use \"null\" as well (note\n * that typeof null === 'object'; this is an edge case). For example:\n *\n * function foo(profile: {displayName?: string | null}) {\n * assertTypes(arguments, [{displayName: opt('string|null')}]);\n * }\n *\n * @param args\n * @param expected\n */\nexport function assertTypes(\n args: Omit,\n ...expected: Array\n): void {\n if (args.length > expected.length) {\n _fail(AuthErrorCode.ARGUMENT_ERROR, {});\n }\n\n for (let i = 0; i < expected.length; i++) {\n let expect = expected[i];\n const arg = args[i];\n\n if (expect instanceof Optional) {\n // If the arg is undefined, then it matches \"optional\" and we can move to\n // the next arg\n if (typeof arg === 'undefined') {\n continue;\n }\n expect = expect.type;\n }\n\n if (typeof expect === 'string') {\n // Handle the edge case for null because typeof null === 'object'\n if (expect.includes('null') && arg === null) {\n continue;\n }\n\n const required = expect.split('|');\n _assert(required.includes(typeof arg), AuthErrorCode.ARGUMENT_ERROR, {});\n } else if (typeof expect === 'object') {\n // Recursively check record arguments\n const record = arg as Record;\n const map = expect as MapType;\n const keys = Object.keys(expect);\n\n assertTypes(\n keys.map(k => record[k]),\n ...keys.map(k => map[k])\n );\n } else {\n _assert(arg instanceof expect, AuthErrorCode.ARGUMENT_ERROR, {});\n }\n }\n}\n\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nexport function debugFail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n\n // NOTE: We don't use FirebaseError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * @param assertion\n * @param message\n */\nexport function debugAssert(\n assertion: unknown,\n message: string\n): asserts assertion {\n if (!assertion) {\n debugFail(message);\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\nexport function _getCurrentUrl(): string {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\n\nexport function _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\nexport function _getCurrentScheme(): string | null {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\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 { isBrowserExtension } from '@firebase/util';\nimport { _isHttpOrHttps } from './location';\n\n/**\n * Determine whether the browser is working online\n */\nexport function _isOnline(): boolean {\n if (\n typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in navigator &&\n typeof navigator.onLine === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)\n ) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\n\nexport function _getUserLanguage(): string | null {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage: NavigatorLanguage = navigator;\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language ||\n // Couldn't determine language.\n null\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 { isMobileCordova, isReactNative } from '@firebase/util';\nimport { _isOnline } from './navigator';\nimport { debugAssert } from './assert';\n\nexport const enum DelayMin {\n OFFLINE = 5000\n}\n\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n */\nexport class Delay {\n // The default value for the offline delay timeout in ms.\n\n private readonly isMobile: boolean;\n constructor(\n private readonly shortDelay: number,\n private readonly longDelay: number\n ) {\n // Internal error when improperly initialized.\n debugAssert(\n longDelay > shortDelay,\n 'Short delay should be less than long delay!'\n );\n this.isMobile = isMobileCordova() || isReactNative();\n }\n\n get(): number {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(DelayMin.OFFLINE, this.shortDelay);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile ? this.longDelay : this.shortDelay;\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 { ConfigInternal } from '../../model/auth';\nimport { debugAssert } from './assert';\n\nexport function _emulatorUrl(config: ConfigInternal, path?: string): string {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n\n if (!path) {\n return url;\n }\n\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\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 { debugFail } from './assert';\n\nexport class FetchProvider {\n private static fetchImpl: typeof fetch | null;\n private static headersImpl: typeof Headers | null;\n private static responseImpl: typeof Response | null;\n\n static initialize(\n fetchImpl: typeof fetch,\n headersImpl?: typeof Headers,\n responseImpl?: typeof Response\n ): void {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n\n static fetch(): typeof fetch {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\n return globalThis.fetch;\n }\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n debugFail(\n 'Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static headers(): typeof Headers {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\n return globalThis.Headers;\n }\n if (typeof Headers !== 'undefined') {\n return Headers;\n }\n debugFail(\n 'Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static response(): typeof Response {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\n return globalThis.Response;\n }\n if (typeof Response !== 'undefined') {\n return Response;\n }\n debugFail(\n 'Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\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 { AuthErrorCode } from '../core/errors';\n\n/**\n * Errors that can be returned by the backend\n */\nexport const enum ServerError {\n ADMIN_ONLY_OPERATION = 'ADMIN_ONLY_OPERATION',\n BLOCKING_FUNCTION_ERROR_RESPONSE = 'BLOCKING_FUNCTION_ERROR_RESPONSE',\n CAPTCHA_CHECK_FAILED = 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED = 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH = 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED = 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS = 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND = 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE = 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED = 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL = 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID = 'INVALID_APP_ID',\n INVALID_CERT_HASH = 'INVALID_CERT_HASH',\n INVALID_CODE = 'INVALID_CODE',\n INVALID_CONTINUE_URI = 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN = 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN = 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL = 'INVALID_EMAIL',\n INVALID_ID_TOKEN = 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE = 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER = 'INVALID_IDENTIFIER',\n INVALID_LOGIN_CREDENTIALS = 'INVALID_LOGIN_CREDENTIALS',\n INVALID_MESSAGE_PAYLOAD = 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL = 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID = 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE = 'INVALID_OOB_CODE',\n INVALID_PASSWORD = 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN = 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER = 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID = 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL = 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER = 'INVALID_SENDER',\n INVALID_SESSION_INFO = 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF = 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID = 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND = 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME = 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL = 'MISSING_APP_CREDENTIAL',\n MISSING_CODE = 'MISSING_CODE',\n MISSING_CONTINUE_URI = 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN = 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID = 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID = 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL = 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE = 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE = 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD = 'MISSING_PASSWORD',\n MISSING_REQ_TYPE = 'MISSING_REQ_TYPE',\n MISSING_PHONE_NUMBER = 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO = 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT = 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL = 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS = 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH = 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR = 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION = 'UNSUPPORTED_TENANT_OPERATION',\n UNAUTHORIZED_DOMAIN = 'UNAUTHORIZED_DOMAIN',\n UNVERIFIED_EMAIL = 'UNVERIFIED_EMAIL',\n USER_CANCELLED = 'USER_CANCELLED',\n USER_DISABLED = 'USER_DISABLED',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n RECAPTCHA_NOT_ENABLED = 'RECAPTCHA_NOT_ENABLED',\n MISSING_RECAPTCHA_TOKEN = 'MISSING_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_TOKEN = 'INVALID_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_ACTION = 'INVALID_RECAPTCHA_ACTION',\n MISSING_CLIENT_TYPE = 'MISSING_CLIENT_TYPE',\n MISSING_RECAPTCHA_VERSION = 'MISSING_RECAPTCHA_VERSION',\n INVALID_RECAPTCHA_VERSION = 'INVALID_RECAPTCHA_VERSION',\n INVALID_REQ_TYPE = 'INVALID_REQ_TYPE',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'PASSWORD_DOES_NOT_MEET_REQUIREMENTS'\n}\n\n/**\n * API Response in the event of an error\n */\nexport interface JsonError {\n error: {\n code: number;\n message: string;\n errors?: [\n {\n message: ServerError;\n domain: string;\n reason: string;\n }\n ];\n };\n}\n\n/**\n * Type definition for a map from server errors to developer visible errors\n */\nexport declare type ServerErrorMap = {\n readonly [K in ApiError]: AuthErrorCode;\n};\n\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nexport const SERVER_ERROR_MAP: Partial> = {\n // Custom token errors.\n [ServerError.CREDENTIAL_MISMATCH]: AuthErrorCode.CREDENTIAL_MISMATCH,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CUSTOM_TOKEN]: AuthErrorCode.INTERNAL_ERROR,\n\n // Create Auth URI errors.\n [ServerError.INVALID_IDENTIFIER]: AuthErrorCode.INVALID_EMAIL,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CONTINUE_URI]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign in with email and password errors (some apply to sign up too).\n [ServerError.INVALID_PASSWORD]: AuthErrorCode.INVALID_PASSWORD,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_PASSWORD]: AuthErrorCode.MISSING_PASSWORD,\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\n // invalid.\n [ServerError.INVALID_LOGIN_CREDENTIALS]: AuthErrorCode.INVALID_CREDENTIAL,\n\n // Sign up with email and password errors.\n [ServerError.EMAIL_EXISTS]: AuthErrorCode.EMAIL_EXISTS,\n [ServerError.PASSWORD_LOGIN_DISABLED]: AuthErrorCode.OPERATION_NOT_ALLOWED,\n\n // Verify assertion for sign in with credential errors:\n [ServerError.INVALID_IDP_RESPONSE]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.INVALID_PENDING_TOKEN]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.FEDERATED_USER_ID_ALREADY_LINKED]:\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_REQ_TYPE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Send Password reset email errors:\n [ServerError.EMAIL_NOT_FOUND]: AuthErrorCode.USER_DELETED,\n [ServerError.RESET_PASSWORD_EXCEED_LIMIT]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n [ServerError.EXPIRED_OOB_CODE]: AuthErrorCode.EXPIRED_OOB_CODE,\n [ServerError.INVALID_OOB_CODE]: AuthErrorCode.INVALID_OOB_CODE,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_OOB_CODE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Operations that require ID token in request:\n [ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,\n [ServerError.INVALID_ID_TOKEN]: AuthErrorCode.INVALID_AUTH,\n [ServerError.TOKEN_EXPIRED]: AuthErrorCode.TOKEN_EXPIRED,\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.TOKEN_EXPIRED,\n\n // Other errors.\n [ServerError.TOO_MANY_ATTEMPTS_TRY_LATER]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n [ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS,\n\n // Phone Auth related errors.\n [ServerError.INVALID_CODE]: AuthErrorCode.INVALID_CODE,\n [ServerError.INVALID_SESSION_INFO]: AuthErrorCode.INVALID_SESSION_INFO,\n [ServerError.INVALID_TEMPORARY_PROOF]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.MISSING_SESSION_INFO]: AuthErrorCode.MISSING_SESSION_INFO,\n [ServerError.SESSION_EXPIRED]: AuthErrorCode.CODE_EXPIRED,\n\n // Other action code errors when additional settings passed.\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n [ServerError.MISSING_ANDROID_PACKAGE_NAME]:\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME,\n [ServerError.UNAUTHORIZED_DOMAIN]: AuthErrorCode.UNAUTHORIZED_DOMAIN,\n\n // getProjectConfig errors when clientId is passed.\n [ServerError.INVALID_OAUTH_CLIENT_ID]: AuthErrorCode.INVALID_OAUTH_CLIENT_ID,\n\n // User actions (sign-up or deletion) disabled errors.\n [ServerError.ADMIN_ONLY_OPERATION]: AuthErrorCode.ADMIN_ONLY_OPERATION,\n\n // Multi factor related errors.\n [ServerError.INVALID_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.INVALID_MFA_SESSION,\n [ServerError.MFA_ENROLLMENT_NOT_FOUND]: AuthErrorCode.MFA_INFO_NOT_FOUND,\n [ServerError.MISSING_MFA_ENROLLMENT_ID]: AuthErrorCode.MISSING_MFA_INFO,\n [ServerError.MISSING_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.MISSING_MFA_SESSION,\n [ServerError.SECOND_FACTOR_EXISTS]:\n AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED,\n [ServerError.SECOND_FACTOR_LIMIT_EXCEEDED]:\n AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED,\n\n // Blocking functions related errors.\n [ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Recaptcha related errors.\n [ServerError.RECAPTCHA_NOT_ENABLED]: AuthErrorCode.RECAPTCHA_NOT_ENABLED,\n [ServerError.MISSING_RECAPTCHA_TOKEN]: AuthErrorCode.MISSING_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_TOKEN]: AuthErrorCode.INVALID_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_ACTION]:\n AuthErrorCode.INVALID_RECAPTCHA_ACTION,\n [ServerError.MISSING_CLIENT_TYPE]: AuthErrorCode.MISSING_CLIENT_TYPE,\n [ServerError.MISSING_RECAPTCHA_VERSION]:\n AuthErrorCode.MISSING_RECAPTCHA_VERSION,\n [ServerError.INVALID_RECAPTCHA_VERSION]:\n AuthErrorCode.INVALID_RECAPTCHA_VERSION,\n [ServerError.INVALID_REQ_TYPE]: AuthErrorCode.INVALID_REQ_TYPE\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 { FirebaseError, querystring } from '@firebase/util';\n\nimport { AuthErrorCode, NamedErrorParams } from '../core/errors';\nimport {\n _createError,\n _errorWithCustomMessage,\n _fail\n} from '../core/util/assert';\nimport { Delay } from '../core/util/delay';\nimport { _emulatorUrl } from '../core/util/emulator';\nimport { FetchProvider } from '../core/util/fetch_provider';\nimport { Auth } from '../model/public_types';\nimport { AuthInternal, ConfigInternal } from '../model/auth';\nimport { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';\nimport { IdTokenMfaResponse } from './authentication/mfa';\nimport { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';\n\nexport const enum HttpMethod {\n POST = 'POST',\n GET = 'GET'\n}\n\nexport const enum HttpHeader {\n CONTENT_TYPE = 'Content-Type',\n X_FIREBASE_LOCALE = 'X-Firebase-Locale',\n X_CLIENT_VERSION = 'X-Client-Version',\n X_FIREBASE_GMPID = 'X-Firebase-gmpid',\n X_FIREBASE_CLIENT = 'X-Firebase-Client',\n X_FIREBASE_APP_CHECK = 'X-Firebase-AppCheck'\n}\n\nexport const enum Endpoint {\n CREATE_AUTH_URI = '/v1/accounts:createAuthUri',\n DELETE_ACCOUNT = '/v1/accounts:delete',\n RESET_PASSWORD = '/v1/accounts:resetPassword',\n SIGN_UP = '/v1/accounts:signUp',\n SIGN_IN_WITH_CUSTOM_TOKEN = '/v1/accounts:signInWithCustomToken',\n SIGN_IN_WITH_EMAIL_LINK = '/v1/accounts:signInWithEmailLink',\n SIGN_IN_WITH_IDP = '/v1/accounts:signInWithIdp',\n SIGN_IN_WITH_PASSWORD = '/v1/accounts:signInWithPassword',\n SIGN_IN_WITH_PHONE_NUMBER = '/v1/accounts:signInWithPhoneNumber',\n SEND_VERIFICATION_CODE = '/v1/accounts:sendVerificationCode',\n SEND_OOB_CODE = '/v1/accounts:sendOobCode',\n SET_ACCOUNT_INFO = '/v1/accounts:update',\n GET_ACCOUNT_INFO = '/v1/accounts:lookup',\n GET_RECAPTCHA_PARAM = '/v1/recaptchaParams',\n START_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:start',\n FINALIZE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',\n START_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',\n FINALIZE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',\n WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',\n GET_PROJECT_CONFIG = '/v1/projects',\n GET_RECAPTCHA_CONFIG = '/v2/recaptchaConfig',\n GET_PASSWORD_POLICY = '/v2/passwordPolicy',\n TOKEN = '/v1/token',\n REVOKE_TOKEN = '/v2/accounts:revokeToken'\n}\n\nexport const enum RecaptchaClientType {\n WEB = 'CLIENT_TYPE_WEB',\n ANDROID = 'CLIENT_TYPE_ANDROID',\n IOS = 'CLIENT_TYPE_IOS'\n}\n\nexport const enum RecaptchaVersion {\n ENTERPRISE = 'RECAPTCHA_ENTERPRISE'\n}\n\nexport const enum RecaptchaActionName {\n SIGN_IN_WITH_PASSWORD = 'signInWithPassword',\n GET_OOB_CODE = 'getOobCode',\n SIGN_UP_PASSWORD = 'signUpPassword'\n}\n\nexport const enum EnforcementState {\n ENFORCE = 'ENFORCE',\n AUDIT = 'AUDIT',\n OFF = 'OFF',\n ENFORCEMENT_STATE_UNSPECIFIED = 'ENFORCEMENT_STATE_UNSPECIFIED'\n}\n\n// Providers that have reCAPTCHA Enterprise support.\nexport const enum RecaptchaProvider {\n EMAIL_PASSWORD_PROVIDER = 'EMAIL_PASSWORD_PROVIDER'\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);\n\nexport function _addTidIfNecessary(\n auth: Auth,\n request: T\n): T {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\n\nexport async function _performApiRequest(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial> = {}\n): Promise {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === HttpMethod.GET) {\n params = request;\n } else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n\n const query = querystring({\n key: auth.config.apiKey,\n ...params\n }).slice(1);\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/json';\n\n if (auth.languageCode) {\n headers[HttpHeader.X_FIREBASE_LOCALE] = auth.languageCode;\n }\n\n return FetchProvider.fetch()(\n _getFinalTarget(auth, auth.config.apiHost, path, query),\n {\n method,\n headers,\n referrerPolicy: 'no-referrer',\n ...body\n }\n );\n });\n}\n\nexport async function _performFetchWithErrorHandling(\n auth: Auth,\n customErrorMap: Partial>,\n fetchFn: () => Promise\n): Promise {\n (auth as AuthInternal)._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout(auth);\n const response: Response = await Promise.race>([\n fetchFn(),\n networkTimeout.promise\n ]);\n\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, json);\n }\n\n if (response.ok && !('errorMessage' in json)) {\n return json;\n } else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n throw _makeTaggedError(\n auth,\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n json\n );\n } else if (serverErrorCode === ServerError.EMAIL_EXISTS) {\n throw _makeTaggedError(auth, AuthErrorCode.EMAIL_EXISTS, json);\n } else if (serverErrorCode === ServerError.USER_DISABLED) {\n throw _makeTaggedError(auth, AuthErrorCode.USER_DISABLED, json);\n }\n const authError =\n errorMap[serverErrorCode as ServerError] ||\n (serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-') as unknown as AuthErrorCode);\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n } else {\n _fail(auth, authError);\n }\n }\n } catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n // Changing this to a different error code will log user out when there is a network error\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\n _fail(auth, AuthErrorCode.NETWORK_REQUEST_FAILED, { 'message': String(e) });\n }\n}\n\nexport async function _performSignInRequest(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial> = {}\n): Promise {\n const serverResponse = (await _performApiRequest(\n auth,\n method,\n path,\n request,\n customErrorMap\n )) as V;\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, AuthErrorCode.MFA_REQUIRED, {\n _serverResponse: serverResponse\n });\n }\n\n return serverResponse;\n}\n\nexport function _getFinalTarget(\n auth: Auth,\n host: string,\n path: string,\n query: string\n): string {\n const base = `${host}${path}?${query}`;\n\n if (!(auth as AuthInternal).config.emulator) {\n return `${auth.config.apiScheme}://${base}`;\n }\n\n return _emulatorUrl(auth.config as ConfigInternal, base);\n}\n\nexport function _parseEnforcementState(\n enforcementStateStr: string\n): EnforcementState {\n switch (enforcementStateStr) {\n case 'ENFORCE':\n return EnforcementState.ENFORCE;\n case 'AUDIT':\n return EnforcementState.AUDIT;\n case 'OFF':\n return EnforcementState.OFF;\n default:\n return EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED;\n }\n}\n\nclass NetworkTimeout {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timer: any | null = null;\n readonly promise = new Promise((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(\n _createError(this.auth, AuthErrorCode.NETWORK_REQUEST_FAILED)\n );\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n\n clearNetworkTimeout(): void {\n clearTimeout(this.timer);\n }\n\n constructor(private readonly auth: Auth) {}\n}\n\ninterface PotentialResponse extends IdTokenResponse {\n email?: string;\n phoneNumber?: string;\n}\n\nexport function _makeTaggedError(\n auth: Auth,\n code: AuthErrorCode,\n response: PotentialResponse\n): FirebaseError {\n const errorParams: NamedErrorParams = {\n appName: auth.name\n };\n\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n\n const error = _createError(auth, code, errorParams);\n\n // We know customData is defined on error because errorParams is defined\n (error.customData! as TaggedWithTokenResponse)._tokenResponse = response;\n return error;\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 { RecaptchaParameters } from '../../model/public_types';\nimport {\n GetRecaptchaConfigResponse,\n RecaptchaEnforcementProviderState\n} from '../../api/authentication/recaptcha';\nimport { EnforcementState, _parseEnforcementState } from '../../api/index';\n\n// reCAPTCHA v2 interface\nexport interface Recaptcha {\n render: (container: HTMLElement, parameters: RecaptchaParameters) => number;\n getResponse: (id: number) => string;\n execute: (id: number) => unknown;\n reset: (id: number) => unknown;\n}\n\nexport function isV2(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is Recaptcha {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as Recaptcha).getResponse !== undefined\n );\n}\n\n// reCAPTCHA Enterprise & v3 shared interface\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\n// reCAPTCHA Enterprise interface\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n}\n\nexport function isEnterprise(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is GreCAPTCHATopLevel {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as GreCAPTCHATopLevel).enterprise !== undefined\n );\n}\n\n// TODO(chuanr): Replace this with the AuthWindow after resolving the dependency issue in Node.js env.\ndeclare global {\n interface Window {\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n }\n}\n\nexport class RecaptchaConfig {\n /**\n * The reCAPTCHA site key.\n */\n siteKey: string = '';\n\n /**\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\n */\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[] = [];\n\n constructor(response: GetRecaptchaConfigResponse) {\n if (response.recaptchaKey === undefined) {\n throw new Error('recaptchaKey undefined');\n }\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\n this.siteKey = response.recaptchaKey.split('/')[3];\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\n }\n\n /**\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\n *\n * @param providerStr - The provider whose enforcement state is to be returned.\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\n */\n getProviderEnforcementState(providerStr: string): EnforcementState | null {\n if (\n !this.recaptchaEnforcementState ||\n this.recaptchaEnforcementState.length === 0\n ) {\n return null;\n }\n\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\n if (\n recaptchaEnforcementState.provider &&\n recaptchaEnforcementState.provider === providerStr\n ) {\n return _parseEnforcementState(\n recaptchaEnforcementState.enforcementState\n );\n }\n }\n return null;\n }\n\n /**\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\n *\n * @param providerStr - The provider whose enablement state is to be returned.\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\n */\n isProviderEnabled(providerStr: string): boolean {\n return (\n this.getProviderEnforcementState(providerStr) ===\n EnforcementState.ENFORCE ||\n this.getProviderEnforcementState(providerStr) === EnforcementState.AUDIT\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 {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _performApiRequest,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\ninterface GetRecaptchaParamResponse {\n recaptchaSiteKey?: string;\n}\n\nexport async function getRecaptchaParams(auth: Auth): Promise {\n return (\n (\n await _performApiRequest(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_PARAM\n )\n ).recaptchaSiteKey || ''\n );\n}\n\n// The following functions are for reCAPTCHA enterprise integration.\ninterface GetRecaptchaConfigRequest {\n tenantId?: string;\n clientType?: RecaptchaClientType;\n version?: RecaptchaVersion;\n}\n\nexport interface RecaptchaEnforcementProviderState {\n provider: string;\n enforcementState: string;\n}\n\nexport interface GetRecaptchaConfigResponse {\n recaptchaKey: string;\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[];\n}\n\nexport async function getRecaptchaConfig(\n auth: Auth,\n request: GetRecaptchaConfigRequest\n): Promise {\n return _performApiRequest<\n GetRecaptchaConfigRequest,\n GetRecaptchaConfigResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_CONFIG,\n _addTidIfNecessary(auth, request)\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 { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { MfaEnrollment } from './mfa';\nimport { Auth } from '../../model/public_types';\n\nexport interface DeleteAccountRequest {\n idToken: string;\n}\n\nexport async function deleteAccount(\n auth: Auth,\n request: DeleteAccountRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.DELETE_ACCOUNT,\n request\n );\n}\n\nexport interface ProviderUserInfo {\n providerId: string;\n rawId?: string;\n email?: string;\n displayName?: string;\n photoUrl?: string;\n phoneNumber?: string;\n}\n\nexport interface DeleteLinkedAccountsRequest {\n idToken: string;\n deleteProvider: string[];\n}\n\nexport interface DeleteLinkedAccountsResponse {\n providerUserInfo: ProviderUserInfo[];\n}\n\nexport async function deleteLinkedAccounts(\n auth: Auth,\n request: DeleteLinkedAccountsRequest\n): Promise {\n return _performApiRequest<\n DeleteLinkedAccountsRequest,\n DeleteLinkedAccountsResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface APIUserInfo {\n localId?: string;\n displayName?: string;\n photoUrl?: string;\n email?: string;\n emailVerified?: boolean;\n phoneNumber?: string;\n lastLoginAt?: number;\n createdAt?: number;\n tenantId?: string;\n passwordHash?: string;\n providerUserInfo?: ProviderUserInfo[];\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface GetAccountInfoRequest {\n idToken: string;\n}\n\nexport interface GetAccountInfoResponse {\n users: APIUserInfo[];\n}\n\nexport async function getAccountInfo(\n auth: Auth,\n request: GetAccountInfoRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.GET_ACCOUNT_INFO,\n request\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\nexport function utcTimestampToDateString(\n utcTimestamp?: string | number\n): string | undefined {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\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 { IdTokenResult, ParsedToken, User } from '../../model/public_types';\nimport { base64Decode, getModularInstance } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { _logError } from '../util/log';\nimport { utcTimestampToDateString } from '../util/time';\nimport { AuthErrorCode } from '../errors';\n\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport function getIdToken(user: User, forceRefresh = false): Promise {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getIdTokenResult(\n user: User,\n forceRefresh = false\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n\n _assert(\n claims && claims.exp && claims.auth_time && claims.iat,\n userInternal.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const firebase =\n typeof claims.firebase === 'object' ? claims.firebase : undefined;\n\n const signInProvider: string | undefined = firebase?.['sign_in_provider'];\n\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.auth_time)\n )!,\n issuedAtTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.iat)\n )!,\n expirationTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.exp)\n )!,\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\n\nfunction secondsStringToMilliseconds(seconds: string): number {\n return Number(seconds) * 1000;\n}\n\nexport function _parseToken(token: string): ParsedToken | null {\n const [algorithm, payload, signature] = token.split('.');\n if (\n algorithm === undefined ||\n payload === undefined ||\n signature === undefined\n ) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n } catch (e) {\n _logError(\n 'Caught error parsing JWT payload as JSON',\n (e as Error)?.toString()\n );\n return null;\n }\n}\n\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nexport function _tokenExpiresIn(token: string): number {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.exp !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.iat !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\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 { FirebaseError } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\nexport async function _logoutIfInvalidated(\n user: UserInternal,\n promise: Promise,\n bypassAuthState = false\n): Promise {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n } catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n\n throw e;\n }\n}\n\nfunction isUserInvalidated({ code }: FirebaseError): boolean {\n return (\n code === `auth/${AuthErrorCode.USER_DISABLED}` ||\n code === `auth/${AuthErrorCode.TOKEN_EXPIRED}`\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 { FirebaseError } from '@firebase/util';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\n// Refresh the token five minutes before expiration\nexport const enum Duration {\n OFFSET = 5 * 1000 * 60,\n RETRY_BACKOFF_MIN = 30 * 1000,\n RETRY_BACKOFF_MAX = 16 * 60 * 1000\n}\n\nexport class ProactiveRefresh {\n private isRunning = false;\n\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timerId: any | null = null;\n private errorBackoff = Duration.RETRY_BACKOFF_MIN;\n\n constructor(private readonly user: UserInternal) {}\n\n _start(): void {\n if (this.isRunning) {\n return;\n }\n\n this.isRunning = true;\n this.schedule();\n }\n\n _stop(): void {\n if (!this.isRunning) {\n return;\n }\n\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n\n private getInterval(wasError: boolean): number {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(\n this.errorBackoff * 2,\n Duration.RETRY_BACKOFF_MAX\n );\n return interval;\n } else {\n // Reset the error backoff\n this.errorBackoff = Duration.RETRY_BACKOFF_MIN;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - Duration.OFFSET;\n\n return Math.max(0, interval);\n }\n }\n\n private schedule(wasError = false): void {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n\n private async iteration(): Promise {\n try {\n await this.user.getIdToken(true);\n } catch (e) {\n // Only retry on network errors\n if (\n (e as FirebaseError)?.code ===\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n this.schedule(/* wasError */ true);\n }\n\n return;\n }\n this.schedule();\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 { UserMetadata as UserMetadataType } from '../../model/public_types';\n\nimport { utcTimestampToDateString } from '../util/time';\n\nexport class UserMetadata implements UserMetadataType {\n creationTime?: string;\n lastSignInTime?: string;\n\n constructor(\n private createdAt?: string | number,\n private lastLoginAt?: string | number\n ) {\n this._initializeTime();\n }\n\n private _initializeTime(): void {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n\n _copy(metadata: UserMetadata): void {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n\n toJSON(): object {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\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\nimport { User, UserInfo } from '../../model/public_types';\n\nimport {\n getAccountInfo,\n ProviderUserInfo\n} from '../../api/account_management/account';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserMetadata } from './user_metadata';\nimport { getModularInstance } from '@firebase/util';\n\nexport async function _reloadWithoutSaving(user: UserInternal): Promise {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(\n user,\n getAccountInfo(auth, { idToken })\n );\n\n _assert(response?.users.length, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const coreAccount = response.users[0];\n\n user._notifyReloadListener(coreAccount);\n\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const providerData = mergeProviderData(user.providerData, newProviderData);\n\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous =\n !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n\n const updates: Partial = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n\n Object.assign(user, updates);\n}\n\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function reload(user: User): Promise {\n const userInternal: UserInternal = getModularInstance(user) as UserInternal;\n await _reloadWithoutSaving(userInternal);\n\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\n\nfunction mergeProviderData(\n original: UserInfo[],\n newData: UserInfo[]\n): UserInfo[] {\n const deduped = original.filter(\n o => !newData.some(n => n.providerId === o.providerId)\n );\n return [...deduped, ...newData];\n}\n\nexport function extractProviderData(providers: ProviderUserInfo[]): UserInfo[] {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\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/* eslint-disable camelcase */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n _getFinalTarget,\n _performFetchWithErrorHandling,\n _performApiRequest,\n _addTidIfNecessary,\n HttpMethod,\n HttpHeader,\n Endpoint\n} from '../index';\nimport { FetchProvider } from '../../core/util/fetch_provider';\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\n\nexport const enum TokenType {\n REFRESH_TOKEN = 'REFRESH_TOKEN',\n ACCESS_TOKEN = 'ACCESS_TOKEN'\n}\n\n/** The server responses with snake_case; we convert to camelCase */\ninterface RequestStsTokenServerResponse {\n access_token: string;\n expires_in: string;\n refresh_token: string;\n}\n\nexport interface RequestStsTokenResponse {\n accessToken: string;\n expiresIn: string;\n refreshToken: string;\n}\n\nexport interface RevokeTokenRequest {\n providerId: string;\n tokenType: TokenType;\n token: string;\n idToken: string;\n tenantId?: string;\n}\n\nexport interface RevokeTokenResponse {}\n\nexport async function requestStsToken(\n auth: Auth,\n refreshToken: string\n): Promise {\n const response =\n await _performFetchWithErrorHandling(\n auth,\n {},\n async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = _getFinalTarget(\n auth,\n tokenApiHost,\n Endpoint.TOKEN,\n `key=${apiKey}`\n );\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/x-www-form-urlencoded';\n\n return FetchProvider.fetch()(url, {\n method: HttpMethod.POST,\n headers,\n body\n });\n }\n );\n\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\n\nexport async function revokeToken(\n auth: Auth,\n request: RevokeTokenRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.REVOKE_TOKEN,\n _addTidIfNecessary(auth, request)\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 { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { requestStsToken } from '../../api/authentication/token';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert, debugFail } from '../util/assert';\nimport { _tokenExpiresIn } from './id_token_result';\n\n/**\n * The number of milliseconds before the official expiration time of a token\n * to refresh that token, to provide a buffer for RPCs to complete.\n */\nexport const enum Buffer {\n TOKEN_REFRESH = 30_000\n}\n\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport class StsTokenManager {\n refreshToken: string | null = null;\n accessToken: string | null = null;\n expirationTime: number | null = null;\n\n get isExpired(): boolean {\n return (\n !this.expirationTime ||\n Date.now() > this.expirationTime - Buffer.TOKEN_REFRESH\n );\n }\n\n updateFromServerResponse(\n response: IdTokenResponse | FinalizeMfaResponse\n ): void {\n _assert(response.idToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(\n typeof response.idToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof response.refreshToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const expiresIn =\n 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(\n response.idToken,\n response.refreshToken,\n expiresIn\n );\n }\n\n updateFromIdToken(idToken: string): void {\n _assert(idToken.length !== 0, AuthErrorCode.INTERNAL_ERROR);\n const expiresIn = _tokenExpiresIn(idToken);\n this.updateTokensAndExpiration(idToken, null, expiresIn);\n }\n\n async getToken(\n auth: AuthInternal,\n forceRefresh = false\n ): Promise {\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n\n _assert(this.refreshToken, auth, AuthErrorCode.TOKEN_EXPIRED);\n\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken!);\n return this.accessToken;\n }\n\n return null;\n }\n\n clearRefreshToken(): void {\n this.refreshToken = null;\n }\n\n private async refresh(auth: AuthInternal, oldToken: string): Promise {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(\n auth,\n oldToken\n );\n this.updateTokensAndExpiration(\n accessToken,\n refreshToken,\n Number(expiresIn)\n );\n }\n\n private updateTokensAndExpiration(\n accessToken: string,\n refreshToken: string | null,\n expiresInSec: number\n ): void {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n\n static fromJSON(appName: string, object: PersistedBlob): StsTokenManager {\n const { refreshToken, accessToken, expirationTime } = object;\n\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(\n typeof expirationTime === 'number',\n AuthErrorCode.INTERNAL_ERROR,\n {\n appName\n }\n );\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n\n toJSON(): object {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n\n _assign(stsTokenManager: StsTokenManager): void {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n\n _clone(): StsTokenManager {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n\n _performRefresh(): never {\n return debugFail('not implemented');\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 { IdTokenResult, UserInfo } from '../../model/public_types';\nimport { NextFn } from '@firebase/util';\nimport {\n APIUserInfo,\n GetAccountInfoResponse,\n deleteAccount\n} from '../../api/account_management/account';\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport {\n MutableUserInfo,\n UserInternal,\n UserParameters\n} from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport {\n _assert,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../util/assert';\nimport { getIdTokenResult } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { ProactiveRefresh } from './proactive_refresh';\nimport { extractProviderData, _reloadWithoutSaving, reload } from './reload';\nimport { StsTokenManager } from './token_manager';\nimport { UserMetadata } from './user_metadata';\nimport { ProviderId } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\nfunction assertStringOrUndefined(\n assertion: unknown,\n appName: string\n): asserts assertion is string | undefined {\n _assert(\n typeof assertion === 'string' || typeof assertion === 'undefined',\n AuthErrorCode.INTERNAL_ERROR,\n { appName }\n );\n}\n\nexport class UserImpl implements UserInternal {\n // For the user object, provider is always Firebase.\n readonly providerId = ProviderId.FIREBASE;\n stsTokenManager: StsTokenManager;\n // Last known accessToken so we know when it changes\n private accessToken: string | null;\n\n uid: string;\n auth: AuthInternal;\n emailVerified: boolean;\n isAnonymous: boolean;\n tenantId: string | null;\n readonly metadata: UserMetadata;\n providerData: MutableUserInfo[];\n\n // Optional fields from UserInfo\n displayName: string | null;\n email: string | null;\n phoneNumber: string | null;\n photoURL: string | null;\n\n _redirectEventId?: string;\n private readonly proactiveRefresh = new ProactiveRefresh(this);\n\n constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) {\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(\n opt.createdAt || undefined,\n opt.lastLoginAt || undefined\n );\n }\n\n async getIdToken(forceRefresh?: boolean): Promise {\n const accessToken = await _logoutIfInvalidated(\n this,\n this.stsTokenManager.getToken(this.auth, forceRefresh)\n );\n _assert(accessToken, this.auth, AuthErrorCode.INTERNAL_ERROR);\n\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n\n return accessToken;\n }\n\n getIdTokenResult(forceRefresh?: boolean): Promise {\n return getIdTokenResult(this, forceRefresh);\n }\n\n reload(): Promise {\n return reload(this);\n }\n\n private reloadUserInfo: APIUserInfo | null = null;\n private reloadListener: NextFn | null = null;\n\n _assign(user: UserInternal): void {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n\n _clone(auth: AuthInternal): UserInternal {\n const newUser = new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n newUser.metadata._copy(this.metadata);\n return newUser;\n }\n\n _onReload(callback: NextFn): void {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n\n _notifyReloadListener(userInfo: APIUserInfo): void {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n } else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n\n _startProactiveRefresh(): void {\n this.proactiveRefresh._start();\n }\n\n _stopProactiveRefresh(): void {\n this.proactiveRefresh._stop();\n }\n\n async _updateTokensIfNecessary(\n response: IdTokenResponse | FinalizeMfaResponse,\n reload = false\n ): Promise {\n let tokensRefreshed = false;\n if (\n response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken\n ) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n\n async delete(): Promise {\n if (_isFirebaseServerApp(this.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(this.auth)\n );\n }\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n\n return this.auth.signOut();\n }\n\n toJSON(): PersistedBlob {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n\n get refreshToken(): string {\n return this.stsTokenManager.refreshToken || '';\n }\n\n static _fromJSON(auth: AuthInternal, object: PersistedBlob): UserInternal {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const {\n uid,\n emailVerified,\n isAnonymous,\n providerData,\n stsTokenManager: plainObjectTokenManager\n } = object;\n\n _assert(uid && plainObjectTokenManager, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const stsTokenManager = StsTokenManager.fromJSON(\n this.name,\n plainObjectTokenManager as PersistedBlob\n );\n\n _assert(typeof uid === 'string', auth, AuthErrorCode.INTERNAL_ERROR);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(\n typeof emailVerified === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof isAnonymous === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromGetAccountInfoResponse(\n auth: AuthInternal,\n response: GetAccountInfoResponse,\n idToken: string\n ): Promise {\n const coreAccount = response.users[0];\n _assert(coreAccount.localId !== undefined, AuthErrorCode.INTERNAL_ERROR);\n\n const providerData: UserInfo[] =\n coreAccount.providerUserInfo !== undefined\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const isAnonymous =\n !(coreAccount.email && coreAccount.passwordHash) && !providerData?.length;\n\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromIdToken(idToken);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: coreAccount.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // update the user with data from the GetAccountInfo response.\n const updates: Partial = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(\n coreAccount.createdAt,\n coreAccount.lastLoginAt\n ),\n isAnonymous:\n !(coreAccount.email && coreAccount.passwordHash) &&\n !providerData?.length\n };\n\n Object.assign(user, updates);\n return user;\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 { debugAssert } from './assert';\n\n/**\n * Our API has a lot of one-off constants that are used to do things.\n * Unfortunately we can't export these as classes instantiated directly since\n * the constructor may side effect and therefore can't be proven to be safely\n * culled. Instead, we export these classes themselves as a lowerCamelCase\n * constant, and instantiate them under the hood.\n */\nexport interface SingletonInstantiator {\n new (): T;\n}\n\nconst instanceCache: Map = new Map();\n\nexport function _getInstance(cls: unknown): T {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls) as T | undefined;\n\n if (instance) {\n debugAssert(\n instance instanceof cls,\n 'Instance stored in cache mismatched with class'\n );\n return instance;\n }\n\n instance = new (cls as SingletonInstantiator)();\n instanceCache.set(cls, instance);\n return instance;\n}\n\nexport function _clearInstanceMap(): void {\n instanceCache.clear();\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 { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../persistence';\n\nexport class InMemoryPersistence implements PersistenceInternal {\n static type: 'NONE' = 'NONE';\n readonly type = PersistenceType.NONE;\n storage: Record = {};\n\n async _isAvailable(): Promise {\n return true;\n }\n\n async _set(key: string, value: PersistenceValue): Promise {\n this.storage[key] = value;\n }\n\n async _get(key: string): Promise {\n const value = this.storage[key];\n return value === undefined ? null : (value as T);\n }\n\n async _remove(key: string): Promise {\n delete this.storage[key];\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nexport const inMemoryPersistence: Persistence = InMemoryPersistence;\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 { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { PersistedBlob, PersistenceInternal } from '../persistence';\nimport { UserImpl } from '../user/user_impl';\nimport { _getInstance } from '../util/instantiator';\nimport { inMemoryPersistence } from './in_memory';\n\nexport const enum KeyName {\n AUTH_USER = 'authUser',\n AUTH_EVENT = 'authEvent',\n REDIRECT_USER = 'redirectUser',\n PERSISTENCE_USER = 'persistence'\n}\nexport const enum Namespace {\n PERSISTENCE = 'firebase'\n}\n\nexport function _persistenceKeyName(\n key: string,\n apiKey: ApiKey,\n appName: AppName\n): string {\n return `${Namespace.PERSISTENCE}:${key}:${apiKey}:${appName}`;\n}\n\nexport class PersistenceUserManager {\n private readonly fullUserKey: string;\n private readonly fullPersistenceKey: string;\n private readonly boundEventHandler: () => void;\n\n private constructor(\n public persistence: PersistenceInternal,\n private readonly auth: AuthInternal,\n private readonly userKey: string\n ) {\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\n KeyName.PERSISTENCE_USER,\n config.apiKey,\n name\n );\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n\n setCurrentUser(user: UserInternal): Promise {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n\n async getCurrentUser(): Promise {\n const blob = await this.persistence._get(this.fullUserKey);\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\n }\n\n removeCurrentUser(): Promise {\n return this.persistence._remove(this.fullUserKey);\n }\n\n savePersistenceForRedirect(): Promise {\n return this.persistence._set(\n this.fullPersistenceKey,\n this.persistence.type\n );\n }\n\n async setPersistence(newPersistence: PersistenceInternal): Promise {\n if (this.persistence === newPersistence) {\n return;\n }\n\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n\n this.persistence = newPersistence;\n\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n\n delete(): void {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n\n static async create(\n auth: AuthInternal,\n persistenceHierarchy: PersistenceInternal[],\n userKey = KeyName.AUTH_USER\n ): Promise {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(\n _getInstance(inMemoryPersistence),\n auth,\n userKey\n );\n }\n\n // Eliminate any persistences that are not available\n const availablePersistences = (\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n return undefined;\n })\n )\n ).filter(persistence => persistence) as PersistenceInternal[];\n\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence =\n availablePersistences[0] ||\n _getInstance(inMemoryPersistence);\n\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate: UserInternal | null = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get(key);\n if (blob) {\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n } catch {}\n }\n\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(\n p => p._shouldAllowMigration\n );\n\n // If the persistence does _not_ allow migration, just finish off here\n if (\n !selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length\n ) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n } catch {}\n }\n })\n );\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\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 { isIE, getUA } from '@firebase/util';\n\ninterface NavigatorStandalone extends Navigator {\n standalone?: unknown;\n}\n\ninterface Document {\n documentMode?: number;\n}\n\n/**\n * Enums for Browser name.\n */\nexport const enum BrowserName {\n ANDROID = 'Android',\n BLACKBERRY = 'Blackberry',\n EDGE = 'Edge',\n FIREFOX = 'Firefox',\n IE = 'IE',\n IEMOBILE = 'IEMobile',\n OPERA = 'Opera',\n OTHER = 'Other',\n CHROME = 'Chrome',\n SAFARI = 'Safari',\n SILK = 'Silk',\n WEBOS = 'Webos'\n}\n\n/**\n * Determine the browser for the purposes of reporting usage to the API\n */\nexport function _getBrowserName(userAgent: string): BrowserName | string {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return BrowserName.OPERA;\n } else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return BrowserName.IEMOBILE;\n } else if (ua.includes('msie') || ua.includes('trident/')) {\n return BrowserName.IE;\n } else if (ua.includes('edge/')) {\n return BrowserName.EDGE;\n } else if (_isFirefox(ua)) {\n return BrowserName.FIREFOX;\n } else if (ua.includes('silk/')) {\n return BrowserName.SILK;\n } else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return BrowserName.BLACKBERRY;\n } else if (_isWebOS(ua)) {\n // WebOS default browser.\n return BrowserName.WEBOS;\n } else if (_isSafari(ua)) {\n return BrowserName.SAFARI;\n } else if (\n (ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')\n ) {\n return BrowserName.CHROME;\n } else if (_isAndroid(ua)) {\n // Android stock browser.\n return BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return BrowserName.OTHER;\n}\n\nexport function _isFirefox(ua = getUA()): boolean {\n return /firefox\\//i.test(ua);\n}\n\nexport function _isSafari(userAgent = getUA()): boolean {\n const ua = userAgent.toLowerCase();\n return (\n ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android')\n );\n}\n\nexport function _isChromeIOS(ua = getUA()): boolean {\n return /crios\\//i.test(ua);\n}\n\nexport function _isIEMobile(ua = getUA()): boolean {\n return /iemobile/i.test(ua);\n}\n\nexport function _isAndroid(ua = getUA()): boolean {\n return /android/i.test(ua);\n}\n\nexport function _isBlackBerry(ua = getUA()): boolean {\n return /blackberry/i.test(ua);\n}\n\nexport function _isWebOS(ua = getUA()): boolean {\n return /webos/i.test(ua);\n}\n\nexport function _isIOS(ua = getUA()): boolean {\n return (\n /iphone|ipad|ipod/i.test(ua) ||\n (/macintosh/i.test(ua) && /mobile/i.test(ua))\n );\n}\n\nexport function _isIOS7Or8(ua = getUA()): boolean {\n return (\n /(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua)\n );\n}\n\nexport function _isIOSStandalone(ua = getUA()): boolean {\n return _isIOS(ua) && !!(window.navigator as NavigatorStandalone)?.standalone;\n}\n\nexport function _isIE10(): boolean {\n return isIE() && (document as Document).documentMode === 10;\n}\n\nexport function _isMobileBrowser(ua: string = getUA()): boolean {\n // TODO: implement getBrowserName equivalent for OS.\n return (\n _isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua)\n );\n}\n\nexport function _isIframe(): boolean {\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(window && window !== window.top);\n } catch (e) {\n return false;\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 { SDK_VERSION } from '@firebase/app';\nimport { _getBrowserName } from './browser';\nimport { getUA } from '@firebase/util';\n\nexport const enum ClientImplementation {\n CORE = 'JsCore'\n}\n\n/**\n * @internal\n */\nexport const enum ClientPlatform {\n BROWSER = 'Browser',\n NODE = 'Node',\n REACT_NATIVE = 'ReactNative',\n CORDOVA = 'Cordova',\n WORKER = 'Worker',\n WEB_EXTENSION = 'WebExtension'\n}\n\n/*\n * Determine the SDK version string\n */\nexport function _getClientVersion(\n clientPlatform: ClientPlatform,\n frameworks: readonly string[] = []\n): string {\n let reportedPlatform: string;\n switch (clientPlatform) {\n case ClientPlatform.BROWSER:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case ClientPlatform.WORKER:\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${ClientImplementation.CORE}/${SDK_VERSION}/${reportedFrameworks}`;\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 { AuthInternal } from '../../model/auth';\nimport { Unsubscribe, User } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\n\ninterface MiddlewareEntry {\n (user: User | null): Promise;\n onAbort?: () => void;\n}\n\nexport class AuthMiddlewareQueue {\n private readonly queue: MiddlewareEntry[] = [];\n\n constructor(private readonly auth: AuthInternal) {}\n\n pushCallback(\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n ): Unsubscribe {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback: MiddlewareEntry = (\n user: User | null\n ): Promise =>\n new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n } catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n\n async runMiddleware(nextUser: User | null): Promise {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n\n const onAbortStack: Array<() => void> = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n } catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n } catch (_) {\n /* swallow error */\n }\n }\n\n throw this.auth._errorFactory.create(AuthErrorCode.LOGIN_BLOCKED, {\n originalMessage: (e as Error)?.message\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\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\n/**\n * Request object for fetching the password policy.\n */\nexport interface GetPasswordPolicyRequest {\n tenantId?: string;\n}\n\n/**\n * Response object for fetching the password policy.\n */\nexport interface GetPasswordPolicyResponse {\n customStrengthOptions: {\n minPasswordLength?: number;\n maxPasswordLength?: number;\n containsLowercaseCharacter?: boolean;\n containsUppercaseCharacter?: boolean;\n containsNumericCharacter?: boolean;\n containsNonAlphanumericCharacter?: boolean;\n };\n allowedNonAlphanumericCharacters?: string[];\n enforcementState: string;\n forceUpgradeOnSignin?: boolean;\n schemaVersion: number;\n}\n\n/**\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\n *\n * @param auth Auth object.\n * @param request Password policy request.\n * @returns Password policy response.\n */\nexport async function _getPasswordPolicy(\n auth: Auth,\n request: GetPasswordPolicyRequest = {}\n): Promise {\n return _performApiRequest<\n GetPasswordPolicyRequest,\n GetPasswordPolicyResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PASSWORD_POLICY,\n _addTidIfNecessary(auth, request)\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\nimport { GetPasswordPolicyResponse } from '../../api/password_policy/get_password_policy';\nimport {\n PasswordPolicyCustomStrengthOptions,\n PasswordPolicyInternal,\n PasswordValidationStatusInternal\n} from '../../model/password_policy';\nimport { PasswordValidationStatus } from '../../model/public_types';\n\n// Minimum min password length enforced by the backend, even if no minimum length is set.\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\n\n/**\n * Stores password policy requirements and provides password validation against the policy.\n *\n * @internal\n */\nexport class PasswordPolicyImpl implements PasswordPolicyInternal {\n readonly customStrengthOptions: PasswordPolicyCustomStrengthOptions;\n readonly allowedNonAlphanumericCharacters: string;\n readonly enforcementState: string;\n readonly forceUpgradeOnSignin: boolean;\n readonly schemaVersion: number;\n\n constructor(response: GetPasswordPolicyResponse) {\n // Only include custom strength options defined in the response.\n const responseOptions = response.customStrengthOptions;\n this.customStrengthOptions = {};\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\n this.customStrengthOptions.minPasswordLength =\n responseOptions.minPasswordLength ?? MINIMUM_MIN_PASSWORD_LENGTH;\n if (responseOptions.maxPasswordLength) {\n this.customStrengthOptions.maxPasswordLength =\n responseOptions.maxPasswordLength;\n }\n if (responseOptions.containsLowercaseCharacter !== undefined) {\n this.customStrengthOptions.containsLowercaseLetter =\n responseOptions.containsLowercaseCharacter;\n }\n if (responseOptions.containsUppercaseCharacter !== undefined) {\n this.customStrengthOptions.containsUppercaseLetter =\n responseOptions.containsUppercaseCharacter;\n }\n if (responseOptions.containsNumericCharacter !== undefined) {\n this.customStrengthOptions.containsNumericCharacter =\n responseOptions.containsNumericCharacter;\n }\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\n this.customStrengthOptions.containsNonAlphanumericCharacter =\n responseOptions.containsNonAlphanumericCharacter;\n }\n\n this.enforcementState = response.enforcementState;\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\n this.enforcementState = 'OFF';\n }\n\n // Use an empty string if no non-alphanumeric characters are specified in the response.\n this.allowedNonAlphanumericCharacters =\n response.allowedNonAlphanumericCharacters?.join('') ?? '';\n\n this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ?? false;\n this.schemaVersion = response.schemaVersion;\n }\n\n validatePassword(password: string): PasswordValidationStatus {\n const status: PasswordValidationStatusInternal = {\n isValid: true,\n passwordPolicy: this\n };\n\n // Check the password length and character options.\n this.validatePasswordLengthOptions(password, status);\n this.validatePasswordCharacterOptions(password, status);\n\n // Combine the status into single isValid property.\n status.isValid &&= status.meetsMinPasswordLength ?? true;\n status.isValid &&= status.meetsMaxPasswordLength ?? true;\n status.isValid &&= status.containsLowercaseLetter ?? true;\n status.isValid &&= status.containsUppercaseLetter ?? true;\n status.isValid &&= status.containsNumericCharacter ?? true;\n status.isValid &&= status.containsNonAlphanumericCharacter ?? true;\n\n return status;\n }\n\n /**\n * Validates that the password meets the length options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordLengthOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\n if (minPasswordLength) {\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\n }\n if (maxPasswordLength) {\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\n }\n }\n\n /**\n * Validates that the password meets the character options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordCharacterOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n // Assign statuses for requirements even if the password is an empty string.\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ false,\n /* containsUppercaseCharacter= */ false,\n /* containsNumericCharacter= */ false,\n /* containsNonAlphanumericCharacter= */ false\n );\n\n let passwordChar;\n for (let i = 0; i < password.length; i++) {\n passwordChar = password.charAt(i);\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\n passwordChar <= 'z',\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\n passwordChar <= 'Z',\n /* containsNumericCharacter= */ passwordChar >= '0' &&\n passwordChar <= '9',\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(\n passwordChar\n )\n );\n }\n }\n\n /**\n * Updates the running validation status with the statuses for the character options.\n * Expected to be called each time a character is processed to update each option status\n * based on the current character.\n *\n * @param status Validation status.\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\n * @param containsNumericCharacter Whether the character is a numeric character.\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\n */\n private updatePasswordCharacterOptionsStatuses(\n status: PasswordValidationStatusInternal,\n containsLowercaseCharacter: boolean,\n containsUppercaseCharacter: boolean,\n containsNumericCharacter: boolean,\n containsNonAlphanumericCharacter: boolean\n ): void {\n if (this.customStrengthOptions.containsLowercaseLetter) {\n status.containsLowercaseLetter ||= containsLowercaseCharacter;\n }\n if (this.customStrengthOptions.containsUppercaseLetter) {\n status.containsUppercaseLetter ||= containsUppercaseCharacter;\n }\n if (this.customStrengthOptions.containsNumericCharacter) {\n status.containsNumericCharacter ||= containsNumericCharacter;\n }\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\n status.containsNonAlphanumericCharacter ||=\n containsNonAlphanumericCharacter;\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 {\n _isFirebaseServerApp,\n _FirebaseService,\n FirebaseApp\n} from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport {\n Auth,\n AuthErrorMap,\n AuthSettings,\n EmulatorConfig,\n NextOrObserver,\n Persistence,\n PopupRedirectResolver,\n User,\n UserCredential,\n CompleteFn,\n ErrorFn,\n NextFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../../model/public_types';\nimport {\n createSubscribe,\n ErrorFactory,\n FirebaseError,\n getModularInstance,\n Observer,\n Subscribe\n} from '@firebase/util';\n\nimport { AuthInternal, ConfigInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport {\n AuthErrorCode,\n AuthErrorParams,\n ErrorMapRetriever,\n _DEFAULT_AUTH_ERROR_FACTORY\n} from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport {\n KeyName,\n PersistenceUserManager\n} from '../persistence/persistence_user_manager';\nimport { _reloadWithoutSaving } from '../user/reload';\nimport {\n _assert,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { _getUserLanguage } from '../util/navigator';\nimport { _getClientVersion } from '../util/version';\nimport { HttpHeader } from '../../api';\nimport {\n RevokeTokenRequest,\n TokenType,\n revokeToken\n} from '../../api/authentication/token';\nimport { AuthMiddlewareQueue } from './middleware';\nimport { RecaptchaConfig } from '../../platform_browser/recaptcha/recaptcha';\nimport { _logWarn } from '../util/log';\nimport { _getPasswordPolicy } from '../../api/password_policy/get_password_policy';\nimport { PasswordPolicyInternal } from '../../model/password_policy';\nimport { PasswordPolicyImpl } from './password_policy_impl';\nimport { getAccountInfo } from '../../api/account_management/account';\nimport { UserImpl } from '../user/user_impl';\n\ninterface AsyncAction {\n (): Promise;\n}\n\nexport const enum DefaultConfig {\n TOKEN_API_HOST = 'securetoken.googleapis.com',\n API_HOST = 'identitytoolkit.googleapis.com',\n API_SCHEME = 'https'\n}\n\nexport class AuthImpl implements AuthInternal, _FirebaseService {\n currentUser: User | null = null;\n emulatorConfig: EmulatorConfig | null = null;\n private operations = Promise.resolve();\n private persistenceManager?: PersistenceUserManager;\n private redirectPersistenceManager?: PersistenceUserManager;\n private authStateSubscription = new Subscription(this);\n private idTokenSubscription = new Subscription(this);\n private readonly beforeStateQueue = new AuthMiddlewareQueue(this);\n private redirectUser: UserInternal | null = null;\n private isProactiveRefreshEnabled = false;\n private readonly EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION: number = 1;\n\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n _canInitEmulator = true;\n _isInitialized = false;\n _deleted = false;\n _initializationPromise: Promise | null = null;\n _popupRedirectResolver: PopupRedirectResolverInternal | null = null;\n _errorFactory: ErrorFactory =\n _DEFAULT_AUTH_ERROR_FACTORY;\n _agentRecaptchaConfig: RecaptchaConfig | null = null;\n _tenantRecaptchaConfigs: Record = {};\n _projectPasswordPolicy: PasswordPolicyInternal | null = null;\n _tenantPasswordPolicies: Record = {};\n readonly name: string;\n\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n private lastNotifiedUid: string | null | undefined = undefined;\n\n languageCode: string | null = null;\n tenantId: string | null = null;\n settings: AuthSettings = { appVerificationDisabledForTesting: false };\n\n constructor(\n public readonly app: FirebaseApp,\n private readonly heartbeatServiceProvider: Provider<'heartbeat'>,\n private readonly appCheckServiceProvider: Provider,\n public readonly config: ConfigInternal\n ) {\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n }\n\n _initializeWithPersistence(\n persistenceHierarchy: PersistenceInternal[],\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n\n this.persistenceManager = await PersistenceUserManager.create(\n this,\n persistenceHierarchy\n );\n\n if (this._deleted) {\n return;\n }\n\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n } catch (e) {\n /* Ignore the error */\n }\n }\n\n await this.initializeCurrentUser(popupRedirectResolver);\n\n this.lastNotifiedUid = this.currentUser?.uid || null;\n\n if (this._deleted) {\n return;\n }\n\n this._isInitialized = true;\n });\n\n return this._initializationPromise;\n }\n\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent(): Promise {\n if (this._deleted) {\n return;\n }\n\n const user = await this.assertedPersistence.getCurrentUser();\n\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n\n private async initializeCurrentUserFromIdToken(\n idToken: string\n ): Promise {\n try {\n const response = await getAccountInfo(this, { idToken });\n const user = await UserImpl._fromGetAccountInfoResponse(\n this,\n response,\n idToken\n );\n await this.directlySetCurrentUser(user);\n } catch (err) {\n console.warn(\n 'FirebaseServerApp could not login user with provided authIdToken: ',\n err\n );\n await this.directlySetCurrentUser(null);\n }\n }\n\n private async initializeCurrentUser(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (_isFirebaseServerApp(this.app)) {\n const idToken = this.app.settings.authIdToken;\n if (idToken) {\n // Start the auth operation in the next tick to allow a moment for the customer's app to\n // attach an emulator, if desired.\n return new Promise(resolve => {\n setTimeout(() =>\n this.initializeCurrentUserFromIdToken(idToken).then(\n resolve,\n resolve\n )\n );\n });\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser =\n (await this.assertedPersistence.getCurrentUser()) as UserInternal | null;\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if (\n (!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user\n ) {\n futureCurrentUser = result.user as UserInternal;\n needsTocheckMiddleware = true;\n }\n }\n\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n } catch (e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver!._overrideRedirectResult(this, () =>\n Promise.reject(e)\n );\n }\n }\n\n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n _assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);\n await this.getOrInitRedirectPersistenceManager();\n\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (\n this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId\n ) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n\n private async tryRedirectSignIn(\n redirectResolver: PopupRedirectResolver\n ): Promise {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n\n let result: UserCredential | null = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver!._completeRedirectFn(\n this,\n redirectResolver,\n true\n );\n } catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n\n return result;\n }\n\n private async reloadAndSetCurrentUserOrClear(\n user: UserInternal\n ): Promise {\n try {\n await _reloadWithoutSaving(user);\n } catch (e) {\n if (\n (e as FirebaseError)?.code !==\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n\n return this.directlySetCurrentUser(user);\n }\n\n useDeviceLanguage(): void {\n this.languageCode = _getUserLanguage();\n }\n\n async _delete(): Promise {\n this._deleted = true;\n }\n\n async updateCurrentUser(userExtern: User | null): Promise {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(this)\n );\n }\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? (getModularInstance(userExtern) as UserInternal)\n : null;\n if (user) {\n _assert(\n user.auth.config.apiKey === this.config.apiKey,\n this,\n AuthErrorCode.INVALID_AUTH\n );\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n\n async _updateCurrentUser(\n user: User | null,\n skipBeforeStateCallbacks: boolean = false\n ): Promise {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(\n this.tenantId === user.tenantId,\n this,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n }\n\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n\n return this.queue(async () => {\n await this.directlySetCurrentUser(user as UserInternal | null);\n this.notifyAuthListeners();\n });\n }\n\n async signOut(): Promise {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(this)\n );\n }\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n\n setPersistence(persistence: Persistence): Promise {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(this)\n );\n }\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n\n _getRecaptchaConfig(): RecaptchaConfig | null {\n if (this.tenantId == null) {\n return this._agentRecaptchaConfig;\n } else {\n return this._tenantRecaptchaConfigs[this.tenantId];\n }\n }\n\n async validatePassword(password: string): Promise {\n if (!this._getPasswordPolicyInternal()) {\n await this._updatePasswordPolicy();\n }\n\n // Password policy will be defined after fetching.\n const passwordPolicy: PasswordPolicyInternal =\n this._getPasswordPolicyInternal()!;\n\n // Check that the policy schema version is supported by the SDK.\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\n if (\n passwordPolicy.schemaVersion !==\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION\n ) {\n return Promise.reject(\n this._errorFactory.create(\n AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION,\n {}\n )\n );\n }\n\n return passwordPolicy.validatePassword(password);\n }\n\n _getPasswordPolicyInternal(): PasswordPolicyInternal | null {\n if (this.tenantId === null) {\n return this._projectPasswordPolicy;\n } else {\n return this._tenantPasswordPolicies[this.tenantId];\n }\n }\n\n async _updatePasswordPolicy(): Promise {\n const response = await _getPasswordPolicy(this);\n\n const passwordPolicy: PasswordPolicyInternal = new PasswordPolicyImpl(\n response\n );\n\n if (this.tenantId === null) {\n this._projectPasswordPolicy = passwordPolicy;\n } else {\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\n }\n }\n\n _getPersistence(): string {\n return this.assertedPersistence.persistence.type;\n }\n\n _updateErrorMap(errorMap: AuthErrorMap): void {\n this._errorFactory = new ErrorFactory(\n 'auth',\n 'Firebase',\n (errorMap as ErrorMapRetriever)()\n );\n }\n\n onAuthStateChanged(\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.authStateSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n beforeAuthStateChanged(\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n ): Unsubscribe {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n\n onIdTokenChanged(\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.idTokenSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n authStateReady(): Promise {\n return new Promise((resolve, reject) => {\n if (this.currentUser) {\n resolve();\n } else {\n const unsubscribe = this.onAuthStateChanged(() => {\n unsubscribe();\n resolve();\n }, reject);\n }\n });\n }\n\n /**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n */\n async revokeAccessToken(token: string): Promise {\n if (this.currentUser) {\n const idToken = await this.currentUser.getIdToken();\n // Generalize this to accept other providers once supported.\n const request: RevokeTokenRequest = {\n providerId: 'apple.com',\n tokenType: TokenType.ACCESS_TOKEN,\n token,\n idToken\n };\n if (this.tenantId != null) {\n request.tenantId = this.tenantId;\n }\n await revokeToken(this, request);\n }\n }\n\n toJSON(): object {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n\n async _setRedirectUser(\n user: UserInternal | null,\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(\n popupRedirectResolver\n );\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n\n private async getOrInitRedirectPersistenceManager(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (!this.redirectPersistenceManager) {\n const resolver: PopupRedirectResolverInternal | null =\n (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);\n this.redirectPersistenceManager = await PersistenceUserManager.create(\n this,\n [_getInstance(resolver._redirectPersistence)],\n KeyName.REDIRECT_USER\n );\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n\n return this.redirectPersistenceManager;\n }\n\n async _redirectUserForId(id: string): Promise {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => {});\n }\n\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n\n return null;\n }\n\n async _persistUserIfCurrent(user: UserInternal): Promise {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user: UserInternal): void {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n\n _key(): string {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n\n _startProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n\n _stopProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n\n /** Returns the current user cast as the internal type */\n get _currentUser(): UserInternal {\n return this.currentUser as UserInternal;\n }\n\n private notifyAuthListeners(): void {\n if (!this._isInitialized) {\n return;\n }\n\n this.idTokenSubscription.next(this.currentUser);\n\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n\n private registerStateListener(\n subscription: Subscription,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n if (this._deleted) {\n return () => {};\n }\n\n const cb =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n\n let isUnsubscribed = false;\n\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, AuthErrorCode.INTERNAL_ERROR);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise.then(() => {\n if (isUnsubscribed) {\n return;\n }\n cb(this.currentUser);\n });\n\n if (typeof nextOrObserver === 'function') {\n const unsubscribe = subscription.addObserver(\n nextOrObserver,\n error,\n completed\n );\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n } else {\n const unsubscribe = subscription.addObserver(nextOrObserver);\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n }\n }\n\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n private async directlySetCurrentUser(\n user: UserInternal | null\n ): Promise {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n }\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n\n this.currentUser = user;\n\n if (user) {\n await this.assertedPersistence.setCurrentUser(user);\n } else {\n await this.assertedPersistence.removeCurrentUser();\n }\n }\n\n private queue(action: AsyncAction): Promise {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n\n private get assertedPersistence(): PersistenceUserManager {\n _assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);\n return this.persistenceManager;\n }\n\n private frameworks: string[] = [];\n private clientVersion: string;\n _logFramework(framework: string): void {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(\n this.config.clientPlatform,\n this._getFrameworks()\n );\n }\n _getFrameworks(): readonly string[] {\n return this.frameworks;\n }\n async _getAdditionalHeaders(): Promise> {\n // Additional headers on every request\n const headers: Record = {\n [HttpHeader.X_CLIENT_VERSION]: this.clientVersion\n };\n\n if (this.app.options.appId) {\n headers[HttpHeader.X_FIREBASE_GMPID] = this.app.options.appId;\n }\n\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider\n .getImmediate({\n optional: true\n })\n ?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[HttpHeader.X_FIREBASE_CLIENT] = heartbeatsHeader;\n }\n\n // If the App Check service exists, add the App Check token in the headers\n const appCheckToken = await this._getAppCheckToken();\n if (appCheckToken) {\n headers[HttpHeader.X_FIREBASE_APP_CHECK] = appCheckToken;\n }\n\n return headers;\n }\n\n async _getAppCheckToken(): Promise {\n const appCheckTokenResult = await this.appCheckServiceProvider\n .getImmediate({ optional: true })\n ?.getToken();\n if (appCheckTokenResult?.error) {\n // Context: appCheck.getToken() will never throw even if an error happened.\n // In the error case, a dummy token will be returned along with an error field describing\n // the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n _logWarn(\n `Error while retrieving App Check token: ${appCheckTokenResult.error}`\n );\n }\n return appCheckTokenResult?.token;\n }\n}\n\n/**\n * Method to be used to cast down to our private implmentation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nexport function _castAuth(auth: Auth): AuthInternal {\n return getModularInstance(auth) as AuthInternal;\n}\n\n/** Helper class to wrap subscriber logic */\nclass Subscription {\n private observer: Observer | null = null;\n readonly addObserver: Subscribe = createSubscribe(\n observer => (this.observer = observer)\n );\n\n constructor(readonly auth: AuthInternal) {}\n\n get next(): NextFn {\n _assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.observer.next.bind(this.observer);\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\ninterface ExternalJSProvider {\n loadJS(url: string): Promise;\n recaptchaV2Script: string;\n recaptchaEnterpriseScript: string;\n gapiScript: string;\n}\n\nlet externalJSProvider: ExternalJSProvider = {\n async loadJS() {\n throw new Error('Unable to load external scripts');\n },\n\n recaptchaV2Script: '',\n recaptchaEnterpriseScript: '',\n gapiScript: ''\n};\n\nexport function _setExternalJSProvider(p: ExternalJSProvider): void {\n externalJSProvider = p;\n}\n\nexport function _loadJS(url: string): Promise {\n return externalJSProvider.loadJS(url);\n}\n\nexport function _recaptchaV2ScriptUrl(): string {\n return externalJSProvider.recaptchaV2Script;\n}\n\nexport function _recaptchaEnterpriseScriptUrl(): string {\n return externalJSProvider.recaptchaEnterpriseScript;\n}\n\nexport function _gapiScriptUrl(): string {\n return externalJSProvider.gapiScript;\n}\n\nexport function _generateCallbackName(prefix: string): string {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n", "/* eslint-disable @typescript-eslint/no-require-imports */\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 { isEnterprise, RecaptchaConfig } from './recaptcha';\nimport { getRecaptchaConfig } from '../../api/authentication/recaptcha';\nimport {\n RecaptchaClientType,\n RecaptchaVersion,\n RecaptchaActionName,\n RecaptchaProvider\n} from '../../api';\n\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport * as jsHelpers from '../load_js';\nimport { AuthErrorCode } from '../../core/errors';\n\nexport const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\nexport const FAKE_TOKEN = 'NO_RECAPTCHA';\n\nexport class RecaptchaEnterpriseVerifier {\n /**\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\n */\n readonly type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\n\n private readonly auth: AuthInternal;\n\n /**\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n */\n constructor(authExtern: Auth) {\n this.auth = _castAuth(authExtern);\n }\n\n /**\n * Executes the verification process.\n *\n * @returns A Promise for a token that can be used to assert the validity of a request.\n */\n async verify(\n action: string = 'verify',\n forceRefresh = false\n ): Promise {\n async function retrieveSiteKey(auth: AuthInternal): Promise {\n if (!forceRefresh) {\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\n return auth._agentRecaptchaConfig.siteKey;\n }\n if (\n auth.tenantId != null &&\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined\n ) {\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\n }\n }\n\n return new Promise(async (resolve, reject) => {\n getRecaptchaConfig(auth, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n })\n .then(response => {\n if (response.recaptchaKey === undefined) {\n reject(new Error('recaptcha Enterprise site key undefined'));\n } else {\n const config = new RecaptchaConfig(response);\n if (auth.tenantId == null) {\n auth._agentRecaptchaConfig = config;\n } else {\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\n }\n return resolve(config.siteKey);\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n\n function retrieveRecaptchaToken(\n siteKey: string,\n resolve: (value: string | PromiseLike) => void,\n reject: (reason?: unknown) => void\n ): void {\n const grecaptcha = window.grecaptcha;\n if (isEnterprise(grecaptcha)) {\n grecaptcha.enterprise.ready(() => {\n grecaptcha.enterprise\n .execute(siteKey, { action })\n .then(token => {\n resolve(token);\n })\n .catch(() => {\n resolve(FAKE_TOKEN);\n });\n });\n } else {\n reject(Error('No reCAPTCHA enterprise script loaded.'));\n }\n }\n\n return new Promise((resolve, reject) => {\n retrieveSiteKey(this.auth)\n .then(siteKey => {\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n } else {\n if (typeof window === 'undefined') {\n reject(\n new Error('RecaptchaVerifier is only supported in browser')\n );\n return;\n }\n let url = jsHelpers._recaptchaEnterpriseScriptUrl();\n if (url.length !== 0) {\n url += siteKey;\n }\n jsHelpers\n ._loadJS(url)\n .then(() => {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n })\n .catch(error => {\n reject(error);\n });\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n}\n\nexport async function injectRecaptchaFields(\n auth: AuthInternal,\n request: T,\n action: RecaptchaActionName,\n captchaResp = false\n): Promise {\n const verifier = new RecaptchaEnterpriseVerifier(auth);\n let captchaResponse;\n try {\n captchaResponse = await verifier.verify(action);\n } catch (error) {\n captchaResponse = await verifier.verify(action, true);\n }\n const newRequest = { ...request };\n if (!captchaResp) {\n Object.assign(newRequest, { captchaResponse });\n } else {\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\n }\n Object.assign(newRequest, { 'clientType': RecaptchaClientType.WEB });\n Object.assign(newRequest, {\n 'recaptchaVersion': RecaptchaVersion.ENTERPRISE\n });\n return newRequest;\n}\n\ntype ActionMethod = (\n auth: Auth,\n request: TRequest\n) => Promise;\n\nexport async function handleRecaptchaFlow(\n authInstance: AuthInternal,\n request: TRequest,\n actionName: RecaptchaActionName,\n actionMethod: ActionMethod\n): Promise {\n if (\n authInstance\n ._getRecaptchaConfig()\n ?.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)\n ) {\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return actionMethod(authInstance, request).catch(async error => {\n if (error.code === `auth/${AuthErrorCode.MISSING_RECAPTCHA_TOKEN}`) {\n console.log(\n `${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`\n );\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return Promise.reject(error);\n }\n });\n }\n}\n\nexport async function _initializeRecaptchaConfig(auth: Auth): Promise {\n const authInternal = _castAuth(auth);\n\n const response = await getRecaptchaConfig(authInternal, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n });\n\n const config = new RecaptchaConfig(response);\n if (authInternal.tenantId == null) {\n authInternal._agentRecaptchaConfig = config;\n } else {\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\n }\n\n if (config.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)) {\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\n void verifier.verify();\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 { _getProvider, FirebaseApp } from '@firebase/app';\nimport { deepEqual } from '@firebase/util';\nimport { Auth, Dependencies } from '../../model/public_types';\n\nimport { AuthErrorCode } from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport { _fail } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { AuthImpl } from './auth_impl';\n\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nexport function initializeAuth(app: FirebaseApp, deps?: Dependencies): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n const auth = provider.getImmediate() as AuthImpl;\n const initialOptions = provider.getOptions() as Dependencies;\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n } else {\n _fail(auth, AuthErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const auth = provider.initialize({ options: deps }) as AuthImpl;\n\n return auth;\n}\n\nexport function _initializeAuthInstance(\n auth: AuthImpl,\n deps?: Dependencies\n): void {\n const persistence = deps?.persistence || [];\n const hierarchy = (\n Array.isArray(persistence) ? persistence : [persistence]\n ).map(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\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 */\nimport { Auth } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _castAuth } from './auth_impl';\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nexport function connectAuthEmulator(\n auth: Auth,\n url: string,\n options?: { disableWarnings: boolean }\n): void {\n const authInternal = _castAuth(auth);\n _assert(\n authInternal._canInitEmulator,\n authInternal,\n AuthErrorCode.EMULATOR_CONFIG_FAILED\n );\n\n _assert(\n /^https?:\\/\\//.test(url),\n authInternal,\n AuthErrorCode.INVALID_EMULATOR_SCHEME\n );\n\n const disableWarnings = !!options?.disableWarnings;\n\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\n authInternal.settings.appVerificationDisabledForTesting = true;\n authInternal.emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n\n if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\n\nfunction extractProtocol(url: string): string {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\n\nfunction extractHostAndPort(url: string): {\n host: string;\n port: number | null;\n} {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n } else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\n\nfunction parsePort(portStr: string): number | null {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\n\nfunction emitEmulatorWarning(): void {\n function attachBanner(): void {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info(\n 'WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.'\n );\n }\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n } else {\n attachBanner();\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 { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { debugFail } from '../util/assert';\n\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class AuthCredential {\n /** @internal */\n protected constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n readonly providerId: string,\n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n readonly signInMethod: string\n ) {}\n\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON(): object {\n return debugFail('not implemented');\n }\n\n /** @internal */\n _getIdTokenResponse(_auth: AuthInternal): Promise {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(\n _auth: AuthInternal,\n _idToken: string\n ): Promise {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth: AuthInternal): Promise {\n return debugFail('not implemented');\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 { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from './mfa';\nimport { SignUpRequest, SignUpResponse } from '../authentication/sign_up';\n\nexport interface ResetPasswordRequest {\n oobCode: string;\n newPassword?: string;\n tenantId?: string;\n}\n\nexport interface ResetPasswordResponse {\n email: string;\n newEmail?: string;\n requestType?: ActionCodeOperation;\n mfaInfo?: MfaEnrollment;\n}\n\nexport async function resetPassword(\n auth: Auth,\n request: ResetPasswordRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.RESET_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface UpdateEmailPasswordRequest {\n idToken: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n}\n\nexport interface UpdateEmailPasswordResponse extends IdTokenResponse {}\n\nexport async function updateEmailPassword(\n auth: Auth,\n request: UpdateEmailPasswordRequest\n): Promise {\n return _performApiRequest<\n UpdateEmailPasswordRequest,\n UpdateEmailPasswordResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\n// format as updateEmailPassword.\nexport async function linkEmailPassword(\n auth: Auth,\n request: SignUpRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n request\n );\n}\n\nexport interface ApplyActionCodeRequest {\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface ApplyActionCodeResponse {}\n\nexport async function applyActionCode(\n auth: Auth,\n request: ApplyActionCodeRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n _addTidIfNecessary(auth, request)\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 { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\n\nexport interface SignInWithPasswordRequest {\n returnSecureToken?: boolean;\n email: string;\n password: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignInWithPasswordResponse extends IdTokenResponse {\n email: string;\n displayName: string;\n}\n\nexport async function signInWithPassword(\n auth: Auth,\n request: SignInWithPasswordRequest\n): Promise {\n return _performSignInRequest<\n SignInWithPasswordRequest,\n SignInWithPasswordResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface GetOobCodeRequest {\n email?: string; // Everything except VERIFY_AND_CHANGE_EMAIL\n continueUrl?: string;\n iOSBundleId?: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n androidInstallApp?: boolean;\n androidMinimumVersionCode?: string;\n canHandleCodeInApp?: boolean;\n dynamicLinkDomain?: string;\n tenantId?: string;\n targetProjectid?: string;\n}\n\nexport interface VerifyEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_EMAIL;\n idToken: IdToken;\n}\n\nexport interface PasswordResetRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.PASSWORD_RESET;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface EmailSignInRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.EMAIL_SIGNIN;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface VerifyAndChangeEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n idToken: IdToken;\n newEmail: string;\n}\n\ninterface GetOobCodeResponse {\n email: string;\n}\n\nexport interface VerifyEmailResponse extends GetOobCodeResponse {}\nexport interface PasswordResetResponse extends GetOobCodeResponse {}\nexport interface EmailSignInResponse extends GetOobCodeResponse {}\nexport interface VerifyAndChangeEmailResponse extends GetOobCodeRequest {}\n\nasync function sendOobCode(\n auth: Auth,\n request: GetOobCodeRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_OOB_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function sendEmailVerification(\n auth: Auth,\n request: VerifyEmailRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function sendPasswordResetEmail(\n auth: Auth,\n request: PasswordResetRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n request: EmailSignInRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function verifyAndChangeEmail(\n auth: Auth,\n request: VerifyAndChangeEmailRequest\n): Promise {\n return sendOobCode(auth, request);\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 {\n _performSignInRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithEmailLinkRequest {\n email: string;\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface SignInWithEmailLinkResponse extends IdTokenResponse {\n email: string;\n isNewUser: boolean;\n}\n\nexport async function signInWithEmailLink(\n auth: Auth,\n request: SignInWithEmailLinkRequest\n): Promise {\n return _performSignInRequest<\n SignInWithEmailLinkRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface SignInWithEmailLinkForLinkingRequest\n extends SignInWithEmailLinkRequest {\n idToken: string;\n}\n\nexport async function signInWithEmailLinkForLinking(\n auth: Auth,\n request: SignInWithEmailLinkForLinkingRequest\n): Promise {\n return _performSignInRequest<\n SignInWithEmailLinkForLinkingRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\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 { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { linkEmailPassword } from '../../api/account_management/email_and_password';\nimport {\n signInWithPassword,\n SignInWithPasswordRequest\n} from '../../api/authentication/email_and_password';\nimport {\n signInWithEmailLink,\n signInWithEmailLinkForLinking\n} from '../../api/authentication/email_link';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { SignUpRequest } from '../../api/authentication/sign_up';\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nexport class EmailAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n /** @internal */\n readonly _email: string,\n /** @internal */\n readonly _password: string,\n signInMethod: SignInMethod,\n /** @internal */\n readonly _tenantId: string | null = null\n ) {\n super(ProviderId.PASSWORD, signInMethod);\n }\n\n /** @internal */\n static _fromEmailAndPassword(\n email: string,\n password: string\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n password,\n SignInMethod.EMAIL_PASSWORD\n );\n }\n\n /** @internal */\n static _fromEmailAndCode(\n email: string,\n oobCode: string,\n tenantId: string | null = null\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n oobCode,\n SignInMethod.EMAIL_LINK,\n tenantId\n );\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: object | string): EmailAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === SignInMethod.EMAIL_PASSWORD) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n } else if (obj.signInMethod === SignInMethod.EMAIL_LINK) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n\n /** @internal */\n async _getIdTokenResponse(auth: AuthInternal): Promise {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignInWithPasswordRequest = {\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_IN_WITH_PASSWORD,\n signInWithPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLink(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n async _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignUpRequest = {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n linkEmailPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return this._getIdTokenResponse(auth);\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithIdpRequest {\n requestUri: string;\n postBody?: string;\n sessionId?: string;\n tenantId?: string;\n returnSecureToken: boolean;\n returnIdpCredential?: boolean;\n idToken?: IdToken;\n autoCreate?: boolean;\n pendingToken?: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithIdpResponse extends IdTokenResponse {\n oauthAccessToken?: string;\n oauthTokenSecret?: string;\n nonce?: string;\n oauthIdToken?: string;\n pendingToken?: string;\n}\n\nexport async function signInWithIdp(\n auth: Auth,\n request: SignInWithIdpRequest\n): Promise {\n return _performSignInRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_IDP,\n _addTidIfNecessary(auth, request)\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 { querystring } from '@firebase/util';\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\nexport interface OAuthCredentialParams {\n // OAuth 2 uses either id token or access token\n idToken?: string | null;\n accessToken?: string | null;\n\n // These fields are used with OAuth 1\n oauthToken?: string;\n secret?: string;\n oauthTokenSecret?: string;\n\n // Nonce is only set if pendingToken is not present\n nonce?: string;\n pendingToken?: string;\n\n // Utilities\n providerId: string;\n signInMethod: string;\n}\n\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class OAuthCredential extends AuthCredential {\n /**\n * The OAuth ID token associated with the credential if it belongs to an OIDC provider,\n * such as `google.com`.\n * @readonly\n */\n idToken?: string;\n /**\n * The OAuth access token associated with the credential if it belongs to an\n * {@link OAuthProvider}, such as `facebook.com`, `twitter.com`, etc.\n * @readonly\n */\n accessToken?: string;\n /**\n * The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0\n * provider, such as `twitter.com`.\n * @readonly\n */\n secret?: string;\n\n private nonce?: string;\n private pendingToken: string | null = null;\n\n /** @internal */\n static _fromParams(params: OAuthCredentialParams): OAuthCredential {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n } else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n } else {\n _fail(AuthErrorCode.ARGUMENT_ERROR);\n }\n\n return cred;\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): OAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest }: OAuthCredentialParams = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true\n };\n\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n } else {\n const postBody: Record = {};\n if (this.idToken) {\n postBody['id_token'] = this.idToken;\n }\n if (this.accessToken) {\n postBody['access_token'] = this.accessToken;\n }\n if (this.secret) {\n postBody['oauth_token_secret'] = this.secret;\n }\n\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n\n request.postBody = querystring(postBody);\n }\n\n return request;\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _makeTaggedError,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { AuthErrorCode } from '../../core/errors';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { ServerError, ServerErrorMap } from '../errors';\nimport { Auth } from '../../model/public_types';\n\nexport interface SendPhoneVerificationCodeRequest {\n phoneNumber: string;\n recaptchaToken: string;\n tenantId?: string;\n}\n\nexport interface SendPhoneVerificationCodeResponse {\n sessionInfo: string;\n}\n\nexport async function sendPhoneVerificationCode(\n auth: Auth,\n request: SendPhoneVerificationCodeRequest\n): Promise {\n return _performApiRequest<\n SendPhoneVerificationCodeRequest,\n SendPhoneVerificationCodeResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_VERIFICATION_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberRequest {\n temporaryProof?: string;\n phoneNumber?: string;\n sessionInfo?: string;\n code?: string;\n tenantId?: string;\n}\n\nexport interface LinkWithPhoneNumberRequest\n extends SignInWithPhoneNumberRequest {\n idToken: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberResponse extends IdTokenResponse {\n temporaryProof?: string;\n phoneNumber?: string;\n}\n\nexport async function signInWithPhoneNumber(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise {\n return _performSignInRequest<\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function linkWithPhoneNumber(\n auth: Auth,\n request: LinkWithPhoneNumberRequest\n): Promise {\n const response = await _performSignInRequest<\n LinkWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, response);\n }\n return response;\n}\n\ninterface VerifyPhoneNumberForExistingRequest\n extends SignInWithPhoneNumberRequest {\n operation: 'REAUTH';\n}\n\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_: Partial<\n ServerErrorMap\n> = {\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.USER_DELETED\n};\n\nexport async function verifyPhoneNumberForExisting(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise {\n const apiRequest: VerifyPhoneNumberForExistingRequest = {\n ...request,\n operation: 'REAUTH'\n };\n return _performSignInRequest<\n VerifyPhoneNumberForExistingRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, apiRequest),\n VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_\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 { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport {\n linkWithPhoneNumber,\n signInWithPhoneNumber,\n SignInWithPhoneNumberRequest,\n verifyPhoneNumberForExisting\n} from '../../api/authentication/sms';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nexport interface PhoneAuthCredentialParameters {\n verificationId?: string;\n verificationCode?: string;\n phoneNumber?: string;\n temporaryProof?: string;\n}\n\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nexport class PhoneAuthCredential extends AuthCredential {\n private constructor(private readonly params: PhoneAuthCredentialParameters) {\n super(ProviderId.PHONE, SignInMethod.PHONE);\n }\n\n /** @internal */\n static _fromVerification(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n\n /** @internal */\n static _fromTokenResponse(\n phoneNumber: string,\n temporaryProof: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n return signInWithPhoneNumber(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n return linkWithPhoneNumber(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _makeVerificationRequest(): SignInWithPhoneNumberRequest {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } =\n this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n const obj: Record = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n\n return obj;\n }\n\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json: object | string): PhoneAuthCredential | null {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n\n const { verificationId, verificationCode, phoneNumber, temporaryProof } =\n json as { [key: string]: string };\n if (\n !verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof\n ) {\n return null;\n }\n\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\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 { extractQuerystring, querystringDecode } from '@firebase/util';\nimport { ActionCodeOperation } from '../model/public_types';\nimport { AuthErrorCode } from './errors';\nimport { _assert } from './util/assert';\n\n/**\n * Enums for fields in URL query string.\n *\n * @enum {string}\n */\nconst enum QueryField {\n API_KEY = 'apiKey',\n CODE = 'oobCode',\n CONTINUE_URL = 'continueUrl',\n LANGUAGE_CODE = 'languageCode',\n MODE = 'mode',\n TENANT_ID = 'tenantId'\n}\n\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode: string | null): ActionCodeOperation | null {\n switch (mode) {\n case 'recoverEmail':\n return ActionCodeOperation.RECOVER_EMAIL;\n case 'resetPassword':\n return ActionCodeOperation.PASSWORD_RESET;\n case 'signIn':\n return ActionCodeOperation.EMAIL_SIGNIN;\n case 'verifyEmail':\n return ActionCodeOperation.VERIFY_EMAIL;\n case 'verifyAndChangeEmail':\n return ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n case 'revertSecondFactorAddition':\n return ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION;\n default:\n return null;\n }\n}\n\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url: string): string {\n const link = querystringDecode(extractQuerystring(url))['link'];\n\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))[\n 'deep_link_id'\n ];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nexport class ActionCodeURL {\n /**\n * The API key of the email action link.\n */\n readonly apiKey: string;\n /**\n * The action code of the email action link.\n */\n readonly code: string;\n /**\n * The continue URL of the email action link. Null if not provided.\n */\n readonly continueUrl: string | null;\n /**\n * The language code of the email action link. Null if not provided.\n */\n readonly languageCode: string | null;\n /**\n * The action performed by the email action link. It returns from one of the types from\n * {@link ActionCodeInfo}\n */\n readonly operation: string;\n /**\n * The tenant ID of the email action link. Null if the email action is from the parent project.\n */\n readonly tenantId: string | null;\n\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink: string) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[QueryField.API_KEY] ?? null;\n const code = searchParams[QueryField.CODE] ?? null;\n const operation = parseMode(searchParams[QueryField.MODE] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, AuthErrorCode.ARGUMENT_ERROR);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[QueryField.CONTINUE_URL] ?? null;\n this.languageCode = searchParams[QueryField.LANGUAGE_CODE] ?? null;\n this.tenantId = searchParams[QueryField.TENANT_ID] ?? null;\n }\n\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link: string): ActionCodeURL | null {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nexport function parseActionCodeURL(link: string): ActionCodeURL | null {\n return ActionCodeURL.parseLink(link);\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 { ProviderId, SignInMethod } from '../../model/enums';\nimport { AuthProvider } from '../../model/public_types';\n\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthCredential } from '../credentials/email';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nexport class EmailAuthProvider implements AuthProvider {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n static readonly PROVIDER_ID: 'password' = ProviderId.PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\n static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password' =\n SignInMethod.EMAIL_PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\n static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink' =\n SignInMethod.EMAIL_LINK;\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n readonly providerId = EmailAuthProvider.PROVIDER_ID;\n\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email: string, password: string): EmailAuthCredential {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(\n email: string,\n emailLink: string\n ): EmailAuthCredential {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, AuthErrorCode.ARGUMENT_ERROR);\n\n return EmailAuthCredential._fromEmailAndCode(\n email,\n actionCodeUrl.code,\n actionCodeUrl.tenantId\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 { AuthProvider } from '../../model/public_types';\n\n/**\n * Map of OAuth Custom Parameters.\n *\n * @public\n */\nexport type CustomParameters = Record;\n\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nexport abstract class FederatedAuthProvider implements AuthProvider {\n /** @internal */\n defaultLanguageCode: string | null = null;\n /** @internal */\n private customParameters: CustomParameters = {};\n\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(readonly providerId: string) {}\n\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode: string | null): void {\n this.defaultLanguageCode = languageCode;\n }\n\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider {\n this.customParameters = customOAuthParameters;\n return this;\n }\n\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters(): CustomParameters {\n return this.customParameters;\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\nimport { AuthProvider, UserCredential } from '../../model/public_types';\n\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\nimport { OAuthCredential, OAuthCredentialParams } from '../credentials/oauth';\nimport { UserCredentialInternal } from '../../model/user';\nimport { FirebaseError } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { SignInWithIdpResponse } from '../../../internal';\nimport { FederatedAuthProvider } from './federated';\n\n/**\n * Defines the options for initializing an {@link OAuthCredential}.\n *\n * @remarks\n * For ID tokens with nonce claim, the raw nonce has to also be provided.\n *\n * @public\n */\nexport interface OAuthCredentialOptions {\n /**\n * The OAuth ID token used to initialize the {@link OAuthCredential}.\n */\n idToken?: string;\n /**\n * The OAuth access token used to initialize the {@link OAuthCredential}.\n */\n accessToken?: string;\n /**\n * The raw nonce associated with the ID token.\n *\n * @remarks\n * It is required when an ID token with a nonce field is provided. The SHA-256 hash of the\n * raw nonce must match the nonce field in the ID token.\n */\n rawNonce?: string;\n}\n\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nexport abstract class BaseOAuthProvider\n extends FederatedAuthProvider\n implements AuthProvider\n{\n /** @internal */\n private scopes: string[] = [];\n\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope: string): AuthProvider {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes(): string[] {\n return [...this.scopes];\n }\n}\n\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: object | string): OAuthCredential {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert(\n 'providerId' in obj && 'signInMethod' in obj,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return OAuthCredential._fromParams(obj);\n }\n\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params: OAuthCredentialOptions): OAuthCredential {\n return this._credential({ ...params, nonce: params.rawNonce });\n }\n\n /** An internal credential method that accepts more permissive options */\n private _credential(\n params: Omit\n ): OAuthCredential {\n _assert(params.idToken || params.accessToken, AuthErrorCode.ARGUMENT_ERROR);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static oauthCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce,\n providerId\n } = tokenResponse as SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n\n if (!providerId) {\n return null;\n }\n\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n } catch (e) {\n return null;\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 { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class FacebookAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.FACEBOOK. */\n static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com' =\n SignInMethod.FACEBOOK;\n /** Always set to {@link ProviderId}.FACEBOOK. */\n static readonly PROVIDER_ID: 'facebook.com' = ProviderId.FACEBOOK;\n\n constructor() {\n super(ProviderId.FACEBOOK);\n }\n\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\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 { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class GoogleAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GOOGLE. */\n static readonly GOOGLE_SIGN_IN_METHOD: 'google.com' = SignInMethod.GOOGLE;\n /** Always set to {@link ProviderId}.GOOGLE. */\n static readonly PROVIDER_ID: 'google.com' = ProviderId.GOOGLE;\n\n constructor() {\n super(ProviderId.GOOGLE);\n this.addScope('profile');\n }\n\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(\n idToken?: string | null,\n accessToken?: string | null\n ): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { oauthIdToken, oauthAccessToken } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n } catch {\n return null;\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 { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class GithubAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GITHUB. */\n static readonly GITHUB_SIGN_IN_METHOD: 'github.com' = SignInMethod.GITHUB;\n /** Always set to {@link ProviderId}.GITHUB. */\n static readonly PROVIDER_ID: 'github.com' = ProviderId.GITHUB;\n\n constructor() {\n super(ProviderId.GITHUB);\n }\n\n /**\n * Creates a credential for Github.\n *\n * @param accessToken - Github access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\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/**\n * Represents the SAML credentials returned by an {@link SAMLAuthProvider}.\n *\n * @public\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\n/**\n * @public\n */\nexport class SAMLAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n providerId: string,\n private readonly pendingToken: string\n ) {\n super(providerId, providerId);\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n signInMethod: this.signInMethod,\n providerId: this.providerId,\n pendingToken: this.pendingToken\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): SAMLAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, pendingToken }: Record =\n obj;\n if (\n !providerId ||\n !signInMethod ||\n !pendingToken ||\n providerId !== signInMethod\n ) {\n return null;\n }\n\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n /**\n * Helper static method to avoid exposing the constructor to end users.\n *\n * @internal\n */\n static _create(providerId: string, pendingToken: string): SAMLAuthCredential {\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n return {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true,\n pendingToken: this.pendingToken\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 { FirebaseError } from '@firebase/util';\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredential } from '../../model/public_types';\nimport { UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { SAMLAuthCredential } from '../credentials/saml';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { FederatedAuthProvider } from './federated';\n\nconst SAML_PROVIDER_PREFIX = 'saml.';\n\n/**\n * An {@link AuthProvider} for SAML.\n *\n * @public\n */\nexport class SAMLAuthProvider extends FederatedAuthProvider {\n /**\n * Constructor. The providerId must start with \"saml.\"\n * @param providerId - SAML provider ID.\n */\n constructor(providerId: string) {\n _assert(\n providerId.startsWith(SAML_PROVIDER_PREFIX),\n AuthErrorCode.ARGUMENT_ERROR\n );\n super(providerId);\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\n * successful SAML flow completes.\n *\n * @remarks\n *\n * For example, to get an {@link AuthCredential}, you could write the\n * following code:\n *\n * ```js\n * const userCredential = await signInWithPopup(auth, samlProvider);\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\n * ```\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n /**\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: string | object): AuthCredential {\n const credential = SAMLAuthCredential.fromJSON(json);\n _assert(credential, AuthErrorCode.ARGUMENT_ERROR);\n return credential;\n }\n\n private static samlCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): SAMLAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { pendingToken, providerId } = tokenResponse as SignInWithIdpResponse;\n\n if (!pendingToken || !providerId) {\n return null;\n }\n\n try {\n return SAMLAuthCredential._create(providerId, pendingToken);\n } catch (e) {\n return null;\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/**\n * @license\n * Copyright 2020 Twitter LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nexport class TwitterAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.TWITTER. */\n static readonly TWITTER_SIGN_IN_METHOD: 'twitter.com' = SignInMethod.TWITTER;\n /** Always set to {@link ProviderId}.TWITTER. */\n static readonly PROVIDER_ID: 'twitter.com' = ProviderId.TWITTER;\n\n constructor() {\n super(ProviderId.TWITTER);\n }\n\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token: string, secret: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n } catch {\n return null;\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 {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignUpRequest {\n idToken?: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignUpResponse extends IdTokenResponse {\n displayName?: string;\n email?: string;\n}\n\nexport async function signUp(\n auth: Auth,\n request: SignUpRequest\n): Promise {\n return _performSignInRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n _addTidIfNecessary(auth, request)\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 { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { UserImpl } from './user_impl';\nimport { AuthInternal } from '../../model/auth';\nimport { OperationType, ProviderId } from '../../model/enums';\n\ninterface UserCredentialParams {\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse?: PhoneOrOauthTokenResponse;\n readonly operationType: OperationType;\n}\n\nexport class UserCredentialImpl\n implements UserCredentialInternal, UserCredentialParams\n{\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse: PhoneOrOauthTokenResponse | undefined;\n readonly operationType: OperationType;\n\n constructor(params: UserCredentialParams) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n operationType: OperationType,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise {\n const user = await UserImpl._fromIdTokenResponse(\n auth,\n idTokenResponse,\n isAnonymous\n );\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n\n static async _forOperation(\n user: UserInternal,\n operationType: OperationType,\n response: PhoneOrOauthTokenResponse\n ): Promise {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\n\nfunction providerIdForResponse(\n response: IdTokenResponse\n): ProviderId | string | null {\n if (response.providerId) {\n return response.providerId;\n }\n\n if ('phoneNumber' in response) {\n return ProviderId.PHONE;\n }\n\n return null;\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 { Auth, UserCredential } from '../../model/public_types';\nimport { signUp } from '../../api/authentication/sign_up';\nimport { UserInternal } from '../../model/user';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\n/**\n * Asynchronously signs in as an anonymous user.\n *\n * @remarks\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\n * new anonymous user identity will be created and returned.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport async function signInAnonymously(auth: Auth): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n await authInternal._initializationPromise;\n if (authInternal.currentUser?.isAnonymous) {\n // If an anonymous user is already signed in, no need to sign them in again.\n return new UserCredentialImpl({\n user: authInternal.currentUser as UserInternal,\n providerId: null,\n operationType: OperationType.SIGN_IN\n });\n }\n const response = await signUp(authInternal, {\n returnSecureToken: true\n });\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response,\n true\n );\n await authInternal._updateCurrentUser(userCredential.user);\n return userCredential;\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 { MultiFactorError as MultiFactorErrorPublic } from '../model/public_types';\nimport { FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../model/auth';\nimport { IdTokenResponse } from '../model/id_token';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserInternal } from '../model/user';\nimport { AuthCredential } from '../core/credentials';\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { OperationType } from '../model/enums';\n\nexport type MultiFactorErrorData = MultiFactorErrorPublic['customData'] & {\n _serverResponse: IdTokenMfaResponse;\n};\n\nexport class MultiFactorError\n extends FirebaseError\n implements MultiFactorErrorPublic\n{\n readonly customData: MultiFactorErrorData;\n\n private constructor(\n auth: AuthInternal,\n error: FirebaseError,\n readonly operationType: OperationType,\n readonly user?: UserInternal\n ) {\n super(error.code, error.message);\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 Object.setPrototypeOf(this, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData!._serverResponse as IdTokenMfaResponse,\n operationType\n };\n }\n\n static _fromErrorAndOperation(\n auth: AuthInternal,\n error: FirebaseError,\n operationType: OperationType,\n user?: UserInternal\n ): MultiFactorError {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\n\nexport function _processCredentialSavingMfaContextIfNecessary(\n auth: AuthInternal,\n operationType: OperationType,\n credential: AuthCredential,\n user?: UserInternal\n): Promise {\n const idTokenProvider =\n operationType === OperationType.REAUTHENTICATE\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${AuthErrorCode.MFA_REQUIRED}`) {\n throw MultiFactorError._fromErrorAndOperation(\n auth,\n error,\n operationType,\n user\n );\n }\n\n throw error;\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\nexport interface ProviderAssociatedObject {\n providerId?: string;\n}\n\n/**\n * Takes a set of UserInfo provider data and converts it to a set of names\n */\nexport function providerDataAsNames(\n providerData: T[]\n): Set {\n return new Set(\n providerData\n .map(({ providerId }) => providerId)\n .filter(pid => !!pid) as string[]\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\nimport { User } from '../../model/public_types';\n\nimport { deleteLinkedAccounts } from '../../api/account_management/account';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { providerDataAsNames } from '../util/providers';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { _reloadWithoutSaving } from './reload';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType, ProviderId } from '../../model/enums';\n\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nexport async function unlink(user: User, providerId: string): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n\n userInternal.providerData = userInternal.providerData.filter(pd =>\n providersLeft.has(pd.providerId)\n );\n if (!providersLeft.has(ProviderId.PHONE)) {\n userInternal.phoneNumber = null;\n }\n\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\n\nexport async function _link(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const response = await _logoutIfInvalidated(\n user,\n credential._linkToIdToken(user.auth, await user.getIdToken()),\n bypassAuthState\n );\n return UserCredentialImpl._forOperation(user, OperationType.LINK, response);\n}\n\nexport async function _assertLinkedStatus(\n expected: boolean,\n user: UserInternal,\n provider: string\n): Promise {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n\n const code =\n expected === false\n ? AuthErrorCode.PROVIDER_ALREADY_LINKED\n : AuthErrorCode.NO_SUCH_PROVIDER;\n _assert(providerIds.has(provider) === expected, user.auth, code);\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 { FirebaseError } from '@firebase/util';\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { OperationType } from '../../model/enums';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert, _fail } from '../util/assert';\nimport { _parseToken } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\nexport async function _reauthenticate(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const { auth } = user;\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const operationType = OperationType.REAUTHENTICATE;\n\n try {\n const response = await _logoutIfInvalidated(\n user,\n _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential,\n user\n ),\n bypassAuthState\n );\n _assert(response.idToken, auth, AuthErrorCode.INTERNAL_ERROR);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, AuthErrorCode.USER_MISMATCH);\n\n return UserCredentialImpl._forOperation(user, operationType, response);\n } catch (e) {\n // Convert user deleted error into user mismatch\n if ((e as FirebaseError)?.code === `auth/${AuthErrorCode.USER_DELETED}`) {\n _fail(auth, AuthErrorCode.USER_MISMATCH);\n }\n throw e;\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 { UserCredential, Auth, User } from '../../model/public_types';\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _assertLinkedStatus, _link } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\nexport async function _signInWithCredential(\n auth: AuthInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const operationType = OperationType.SIGN_IN;\n const response = await _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential\n );\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n auth,\n operationType,\n response\n );\n\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function signInWithCredential(\n auth: Auth,\n credential: AuthCredential\n): Promise {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function linkWithCredential(\n user: User,\n credential: AuthCredential\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n\n return _link(userInternal, credential);\n}\n\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\n * or a `TOKEN_EXPIRED` error.\n *\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function reauthenticateWithCredential(\n user: User,\n credential: AuthCredential\n): Promise {\n return _reauthenticate(getModularInstance(user) as UserInternal, credential);\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithCustomTokenRequest {\n token: string;\n returnSecureToken: boolean;\n tenantId?: string;\n}\n\nexport interface SignInWithCustomTokenResponse extends IdTokenResponse {}\n\nexport async function signInWithCustomToken(\n auth: Auth,\n request: SignInWithCustomTokenRequest\n): Promise {\n return _performSignInRequest<\n SignInWithCustomTokenRequest,\n SignInWithCustomTokenResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN,\n _addTidIfNecessary(auth, request)\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 { Auth, UserCredential } from '../../model/public_types';\n\nimport { signInWithCustomToken as getIdTokenResponse } from '../../api/authentication/custom_token';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n/**\n * Asynchronously signs in using a custom token.\n *\n * @remarks\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\n * be generated by an auth backend using the\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\n *\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param customToken - The custom token to sign in with.\n *\n * @public\n */\nexport async function signInWithCustomToken(\n auth: Auth,\n customToken: string\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n const response: IdTokenResponse = await getIdTokenResponse(authInternal, {\n token: customToken,\n returnSecureToken: true\n });\n const cred = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(cred.user);\n return cred;\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 {\n FactorId,\n MultiFactorInfo,\n PhoneMultiFactorInfo,\n TotpMultiFactorInfo\n} from '../model/public_types';\nimport {\n PhoneMfaEnrollment,\n MfaEnrollment,\n TotpMfaEnrollment\n} from '../api/account_management/mfa';\nimport { AuthErrorCode } from '../core/errors';\nimport { _fail } from '../core/util/assert';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorInfoImpl implements MultiFactorInfo {\n readonly uid: string;\n readonly displayName?: string | null;\n readonly enrollmentTime: string;\n\n protected constructor(readonly factorId: FactorId, response: MfaEnrollment) {\n this.uid = response.mfaEnrollmentId;\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\n this.displayName = response.displayName;\n }\n\n static _fromServerResponse(\n auth: AuthInternal,\n enrollment: MfaEnrollment\n ): MultiFactorInfoImpl {\n if ('phoneInfo' in enrollment) {\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n } else if ('totpInfo' in enrollment) {\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n }\n return _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n}\n\nexport class PhoneMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements PhoneMultiFactorInfo\n{\n readonly phoneNumber: string;\n\n private constructor(response: PhoneMfaEnrollment) {\n super(FactorId.PHONE, response);\n this.phoneNumber = response.phoneInfo;\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): PhoneMultiFactorInfoImpl {\n return new PhoneMultiFactorInfoImpl(enrollment as PhoneMfaEnrollment);\n }\n}\nexport class TotpMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements TotpMultiFactorInfo\n{\n private constructor(response: TotpMfaEnrollment) {\n super(FactorId.TOTP, response);\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): TotpMultiFactorInfoImpl {\n return new TotpMultiFactorInfoImpl(enrollment as TotpMfaEnrollment);\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 { ActionCodeSettings, Auth } from '../../model/public_types';\n\nimport { GetOobCodeRequest } from '../../api/authentication/email_and_password';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\nexport function _setActionCodeSettingsOnRequest(\n auth: Auth,\n request: GetOobCodeRequest,\n actionCodeSettings: ActionCodeSettings\n): void {\n _assert(\n actionCodeSettings.url?.length > 0,\n auth,\n AuthErrorCode.INVALID_CONTINUE_URI\n );\n _assert(\n typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\n actionCodeSettings.dynamicLinkDomain.length > 0,\n auth,\n AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN\n );\n\n request.continueUrl = actionCodeSettings.url;\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\n\n if (actionCodeSettings.iOS) {\n _assert(\n actionCodeSettings.iOS.bundleId.length > 0,\n auth,\n AuthErrorCode.MISSING_IOS_BUNDLE_ID\n );\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\n }\n\n if (actionCodeSettings.android) {\n _assert(\n actionCodeSettings.android.packageName.length > 0,\n auth,\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME\n );\n request.androidInstallApp = actionCodeSettings.android.installApp;\n request.androidMinimumVersionCode =\n actionCodeSettings.android.minimumVersion;\n request.androidPackageName = actionCodeSettings.android.packageName;\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 {\n ActionCodeInfo,\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as account from '../../api/account_management/email_and_password';\nimport * as authentication from '../../api/authentication/email_and_password';\nimport { signUp, SignUpRequest } from '../../api/authentication/sign_up';\nimport { MultiFactorInfoImpl } from '../../mfa/mfa_info';\nimport { EmailAuthProvider } from '../providers/email';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport {\n _assert,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../util/assert';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { _castAuth } from '../auth/auth_impl';\nimport { AuthErrorCode } from '../errors';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\n/**\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\n * cached for the project or tenant.\n *\n * @remarks\n * We only fetch the password policy if the password did not meet policy requirements and\n * there is an existing policy cached. A developer must call validatePassword at least\n * once for the cache to be automatically updated.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @private\n */\nasync function recachePasswordPolicy(auth: Auth): Promise {\n const authInternal = _castAuth(auth);\n if (authInternal._getPasswordPolicyInternal()) {\n await authInternal._updatePasswordPolicy();\n }\n}\n\n/**\n * Sends a password reset email to the given email address. This method does not throw an error when\n * there's no user account with the given email address and\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendPasswordResetEmail(\n auth: Auth,\n email: string,\n actionCodeSettings?: ActionCodeSettings\n): Promise {\n const authInternal = _castAuth(auth);\n const request: authentication.PasswordResetRequest = {\n requestType: ActionCodeOperation.PASSWORD_RESET,\n email,\n clientType: RecaptchaClientType.WEB\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\n }\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n authentication.sendPasswordResetEmail\n );\n}\n\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport async function confirmPasswordReset(\n auth: Auth,\n oobCode: string,\n newPassword: string\n): Promise {\n await account\n .resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n })\n .catch(async error => {\n if (\n error.code ===\n `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n // Do not return the email.\n}\n\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function applyActionCode(\n auth: Auth,\n oobCode: string\n): Promise {\n await account.applyActionCode(getModularInstance(auth), { oobCode });\n}\n\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function checkActionCode(\n auth: Auth,\n oobCode: string\n): Promise {\n const authModular = getModularInstance(auth);\n const response = await account.resetPassword(authModular, { oobCode });\n\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, AuthErrorCode.INTERNAL_ERROR);\n switch (operation) {\n case ActionCodeOperation.EMAIL_SIGNIN:\n break;\n case ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL:\n _assert(response.newEmail, authModular, AuthErrorCode.INTERNAL_ERROR);\n break;\n case ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION:\n _assert(response.mfaInfo, authModular, AuthErrorCode.INTERNAL_ERROR);\n // fall through\n default:\n _assert(response.email, authModular, AuthErrorCode.INTERNAL_ERROR);\n }\n\n // The multi-factor info for revert second factor addition\n let multiFactorInfo: MultiFactorInfoImpl | null = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(\n _castAuth(authModular),\n response.mfaInfo\n );\n }\n\n return {\n data: {\n email:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.newEmail\n : response.email) || null,\n previousEmail:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nexport async function verifyPasswordResetCode(\n auth: Auth,\n code: string\n): Promise {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email!;\n}\n\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * This method is not supported on {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nexport async function createUserWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n const request: SignUpRequest = {\n returnSecureToken: true,\n email,\n password,\n clientType: RecaptchaClientType.WEB\n };\n const signUpResponse: Promise = handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n signUp\n );\n const response = await signUpResponse.catch(error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(userCredential.user);\n\n return userCredential;\n}\n\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match. When\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled, this method fails with \"auth/invalid-credential\" in case of an invalid\n * email/password.\n *\n * This method is not supported on {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nexport function signInWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n return signInWithCredential(\n getModularInstance(auth),\n EmailAuthProvider.credential(email, password)\n ).catch(async error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\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 {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as api from '../../api/authentication/email_and_password';\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthProvider } from '../providers/email';\nimport { _getCurrentUrl } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { getModularInstance } from '@firebase/util';\nimport { _castAuth } from '../auth/auth_impl';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\n/**\n * Sends a sign-in email link to the user with the specified email.\n *\n * @remarks\n * The sign-in operation has to always be completed in the app unlike other out of band email\n * actions (password reset and email verifications). This is because, at the end of the flow,\n * the user is expected to be signed in and their Auth state persisted within the app.\n *\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\n * address and the email link supplied in the email sent to the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param authInternal - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n email: string,\n actionCodeSettings: ActionCodeSettings\n): Promise {\n const authInternal = _castAuth(auth);\n const request: api.EmailSignInRequest = {\n requestType: ActionCodeOperation.EMAIL_SIGNIN,\n email,\n clientType: RecaptchaClientType.WEB\n };\n function setActionCodeSettings(\n request: api.EmailSignInRequest,\n actionCodeSettings: ActionCodeSettings\n ): void {\n _assert(\n actionCodeSettings.handleCodeInApp,\n authInternal,\n AuthErrorCode.ARGUMENT_ERROR\n );\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n authInternal,\n request,\n actionCodeSettings\n );\n }\n }\n setActionCodeSettings(request, actionCodeSettings);\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n api.sendSignInLinkToEmail\n );\n}\n\n/**\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\n *\n * @param auth - The {@link Auth} instance.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport function isSignInWithEmailLink(auth: Auth, emailLink: string): boolean {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n return actionCodeUrl?.operation === ActionCodeOperation.EMAIL_SIGNIN;\n}\n\n/**\n * Asynchronously signs in using an email and sign-in email link.\n *\n * @remarks\n * If no link is passed, the link is inferred from the current URL.\n *\n * Fails with an error if the email address is invalid or OTP in email link expires.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport async function signInWithEmailLink(\n auth: Auth,\n email: string,\n emailLink?: string\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authModular = getModularInstance(auth);\n const credential = EmailAuthProvider.credentialWithLink(\n email,\n emailLink || _getCurrentUrl()\n );\n // Check if the tenant ID in the email link matches the tenant ID on Auth\n // instance.\n _assert(\n credential._tenantId === (authModular.tenantId || null),\n authModular,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n return signInWithCredential(authModular, credential);\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface CreateAuthUriRequest {\n identifier: string;\n continueUri: string;\n tenantId?: string;\n}\n\nexport interface CreateAuthUriResponse {\n signinMethods: string[];\n}\n\nexport async function createAuthUri(\n auth: Auth,\n request: CreateAuthUriRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.CREATE_AUTH_URI,\n _addTidIfNecessary(auth, request)\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 {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n User\n} from '../../model/public_types';\n\nimport {\n createAuthUri,\n CreateAuthUriRequest\n} from '../../api/authentication/create_auth_uri';\nimport * as api from '../../api/authentication/email_and_password';\nimport { UserInternal } from '../../model/user';\nimport { _getCurrentUrl, _isHttpOrHttps } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Gets the list of possible sign in methods for the given email address. This method returns an\n * empty list when\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled, irrespective of the number of authentication methods available for the given email.\n *\n * @remarks\n * This is useful to differentiate methods of sign-in for the same provider, eg.\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\n * {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n *\n * Deprecated. Migrating off of this method is recommended as a security best-practice.\n * Learn more in the Identity Platform documentation for\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}.\n * @public\n */\nexport async function fetchSignInMethodsForEmail(\n auth: Auth,\n email: string\n): Promise {\n // createAuthUri returns an error if continue URI is not http or https.\n // For environments like Cordova, Chrome extensions, native frameworks, file\n // systems, etc, use http://localhost as continue URL.\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\n const request: CreateAuthUriRequest = {\n identifier: email,\n continueUri\n };\n\n const { signinMethods } = await createAuthUri(\n getModularInstance(auth),\n request\n );\n\n return signinMethods || [];\n}\n\n/**\n * Sends a verification email to a user.\n *\n * @remarks\n * The verification process is completed by calling {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendEmailVerification(user, actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendEmailVerification(\n user: User,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_EMAIL,\n idToken\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.sendEmailVerification(userInternal.auth, request);\n\n if (email !== user.email) {\n await user.reload();\n }\n}\n\n/**\n * Sends a verification email to a new email address.\n *\n * @remarks\n * The user's email will be updated to the new one after being verified.\n *\n * If you have a custom email action handler, you can complete the verification process by calling\n * {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param newEmail - The new email address to be verified before update.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function verifyBeforeUpdateEmail(\n user: User,\n newEmail: string,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyAndChangeEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n idToken,\n newEmail\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.verifyAndChangeEmail(userInternal.auth, request);\n\n if (email !== user.email) {\n // If the local copy of the email on user is outdated, reload the\n // user.\n await user.reload();\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 { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface UpdateProfileRequest {\n idToken: string;\n displayName?: string | null;\n photoUrl?: string | null;\n returnSecureToken: boolean;\n}\n\nexport interface UpdateProfileResponse extends IdTokenResponse {\n displayName?: string | null;\n photoUrl?: string | null;\n}\n\nexport async function updateProfile(\n auth: Auth,\n request: UpdateProfileRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n request\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 { User } from '../../model/public_types';\n\nimport {\n updateEmailPassword as apiUpdateEmailPassword,\n UpdateEmailPasswordRequest\n} from '../../api/account_management/email_and_password';\nimport { updateProfile as apiUpdateProfile } from '../../api/account_management/profile';\nimport { UserInternal } from '../../model/user';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\n/**\n * Updates a user's profile data.\n *\n * @param user - The user.\n * @param profile - The profile's `displayName` and `photoURL` to update.\n *\n * @public\n */\nexport async function updateProfile(\n user: User,\n {\n displayName,\n photoURL: photoUrl\n }: { displayName?: string | null; photoURL?: string | null }\n): Promise {\n if (displayName === undefined && photoUrl === undefined) {\n return;\n }\n\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await userInternal.getIdToken();\n const profileRequest = {\n idToken,\n displayName,\n photoUrl,\n returnSecureToken: true\n };\n const response = await _logoutIfInvalidated(\n userInternal,\n apiUpdateProfile(userInternal.auth, profileRequest)\n );\n\n userInternal.displayName = response.displayName || null;\n userInternal.photoURL = response.photoUrl || null;\n\n // Update the password provider as well\n const passwordProvider = userInternal.providerData.find(\n ({ providerId }) => providerId === ProviderId.PASSWORD\n );\n if (passwordProvider) {\n passwordProvider.displayName = userInternal.displayName;\n passwordProvider.photoURL = userInternal.photoURL;\n }\n\n await userInternal._updateTokensIfNecessary(response);\n}\n\n/**\n * Updates the user's email address.\n *\n * @remarks\n * An email will be sent to the original email address (if it was set) that allows to revoke the\n * email address change, in order to protect them from account hijacking.\n *\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newEmail - The new email address.\n *\n * Throws \"auth/operation-not-allowed\" error when\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled.\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\n *\n * @public\n */\nexport function updateEmail(user: User, newEmail: string): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(userInternal.auth)\n );\n }\n return updateEmailOrPassword(userInternal, newEmail, null);\n}\n\n/**\n * Updates the user's password.\n *\n * @remarks\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport function updatePassword(user: User, newPassword: string): Promise {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n null,\n newPassword\n );\n}\n\nasync function updateEmailOrPassword(\n user: UserInternal,\n email: string | null,\n password: string | null\n): Promise {\n const { auth } = user;\n const idToken = await user.getIdToken();\n const request: UpdateEmailPasswordRequest = {\n idToken,\n returnSecureToken: true\n };\n\n if (email) {\n request.email = email;\n }\n\n if (password) {\n request.password = password;\n }\n\n const response = await _logoutIfInvalidated(\n user,\n apiUpdateEmailPassword(auth, request)\n );\n await user._updateTokensIfNecessary(response, /* reload */ true);\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 { AdditionalUserInfo, UserCredential } from '../../model/public_types';\nimport { IdTokenResponse, IdTokenResponseKind } from '../../model/id_token';\nimport { _parseToken } from './id_token_result';\nimport { UserCredentialInternal } from '../../model/user';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Parse the `AdditionalUserInfo` from the ID token response.\n *\n */\nexport function _fromIdTokenResponse(\n idTokenResponse?: IdTokenResponse\n): AdditionalUserInfo | null {\n if (!idTokenResponse) {\n return null;\n }\n const { providerId } = idTokenResponse;\n const profile = idTokenResponse.rawUserInfo\n ? JSON.parse(idTokenResponse.rawUserInfo)\n : {};\n const isNewUser =\n idTokenResponse.isNewUser ||\n idTokenResponse.kind === IdTokenResponseKind.SignupNewUser;\n if (!providerId && idTokenResponse?.idToken) {\n const signInProvider = _parseToken(idTokenResponse.idToken)?.firebase?.[\n 'sign_in_provider'\n ];\n if (signInProvider) {\n const filteredProviderId =\n signInProvider !== ProviderId.ANONYMOUS &&\n signInProvider !== ProviderId.CUSTOM\n ? (signInProvider as ProviderId)\n : null;\n // Uses generic class in accordance with the legacy SDK.\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\n }\n }\n if (!providerId) {\n return null;\n }\n switch (providerId) {\n case ProviderId.FACEBOOK:\n return new FacebookAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GITHUB:\n return new GithubAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GOOGLE:\n return new GoogleAdditionalUserInfo(isNewUser, profile);\n case ProviderId.TWITTER:\n return new TwitterAdditionalUserInfo(\n isNewUser,\n profile,\n idTokenResponse.screenName || null\n );\n case ProviderId.CUSTOM:\n case ProviderId.ANONYMOUS:\n return new GenericAdditionalUserInfo(isNewUser, null);\n default:\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\n }\n}\n\nclass GenericAdditionalUserInfo implements AdditionalUserInfo {\n constructor(\n readonly isNewUser: boolean,\n readonly providerId: ProviderId | string | null,\n readonly profile: Record = {}\n ) {}\n}\n\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\n constructor(\n isNewUser: boolean,\n providerId: ProviderId,\n profile: Record,\n readonly username: string | null\n ) {\n super(isNewUser, providerId, profile);\n }\n}\n\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record) {\n super(isNewUser, ProviderId.FACEBOOK, profile);\n }\n}\n\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(isNewUser: boolean, profile: Record) {\n super(\n isNewUser,\n ProviderId.GITHUB,\n profile,\n typeof profile?.login === 'string' ? profile?.login : null\n );\n }\n}\n\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record) {\n super(isNewUser, ProviderId.GOOGLE, profile);\n }\n}\n\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(\n isNewUser: boolean,\n profile: Record,\n screenName: string | null\n ) {\n super(isNewUser, ProviderId.TWITTER, profile, screenName);\n }\n}\n\n/**\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\n *\n * @param userCredential - The user credential.\n *\n * @public\n */\nexport function getAdditionalUserInfo(\n userCredential: UserCredential\n): AdditionalUserInfo | null {\n const { user, _tokenResponse } = userCredential as UserCredentialInternal;\n if (user.isAnonymous && !_tokenResponse) {\n // Handle the special case where signInAnonymously() gets called twice.\n // No network call is made so there's nothing to actually fill this in\n return {\n providerId: null,\n isNewUser: false,\n profile: null\n };\n }\n\n return _fromIdTokenResponse(_tokenResponse);\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 } from '@firebase/util';\nimport {\n Auth,\n NextOrObserver,\n Persistence,\n User,\n CompleteFn,\n ErrorFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../model/public_types';\nimport { _initializeRecaptchaConfig } from '../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { _castAuth } from '../core/auth/auth_impl';\n\nexport {\n debugErrorMap,\n prodErrorMap,\n AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as AuthErrorCodes\n} from './errors';\n\n// Non-optional auth methods.\n/**\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\n * `Auth` session and applies this type of persistence for future sign-in requests, including\n * sign-in with redirect requests.\n *\n * @remarks\n * This makes it easy for a user signing in to specify whether their session should be\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\n * that are shared by other users or have sensitive data.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * setPersistence(auth, browserSessionPersistence);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param persistence - The {@link Persistence} to use.\n * @returns A `Promise` that resolves once the persistence change has completed\n *\n * @public\n */\nexport function setPersistence(\n auth: Auth,\n persistence: Persistence\n): Promise {\n return getModularInstance(auth).setPersistence(persistence);\n}\n\n/**\n * Loads the reCAPTCHA configuration into the `Auth` instance.\n *\n * @remarks\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\n * verification flow should be triggered for each auth provider, into the\n * current Auth session.\n *\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\n * auth flows.\n *\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * initializeRecaptchaConfig(auth);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function initializeRecaptchaConfig(auth: Auth): Promise {\n return _initializeRecaptchaConfig(auth);\n}\n\n/**\n * Validates the password against the password policy configured for the project or tenant.\n *\n * @remarks\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\n * policy configured for the project. Otherwise, this method will use the policy configured\n * for the tenant. If a password policy has not been configured, then the default policy\n * configured for all projects will be used.\n *\n * If an auth flow fails because a submitted password does not meet the password policy\n * requirements and this method has previously been called, then this method will use the\n * most recent policy available when called again.\n *\n * @example\n * ```javascript\n * validatePassword(auth, 'some-password');\n * ```\n *\n * @param auth The {@link Auth} instance.\n * @param password The password to validate.\n *\n * @public\n */\nexport async function validatePassword(\n auth: Auth,\n password: string\n): Promise {\n const authInternal = _castAuth(auth);\n return authInternal.validatePassword(password);\n}\n\n/**\n * Adds an observer for changes to the signed-in user's ID token.\n *\n * @remarks\n * This includes sign-in, sign-out, and token refresh events.\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onIdTokenChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onIdTokenChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Adds a blocking callback that runs before an auth state change\n * sets a new user.\n *\n * @param auth - The {@link Auth} instance.\n * @param callback - callback triggered before new user value is set.\n * If this throws, it blocks the user from being set.\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\n * callback throws, allowing you to undo any side effects.\n */\nexport function beforeAuthStateChanged(\n auth: Auth,\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n): Unsubscribe {\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\n}\n/**\n * Adds an observer for changes to the user's sign-in state.\n *\n * @remarks\n * To keep the old behavior, see {@link onIdTokenChanged}.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onAuthStateChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onAuthStateChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Sets the current language to the default device/browser preference.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function useDeviceLanguage(auth: Auth): void {\n getModularInstance(auth).useDeviceLanguage();\n}\n/**\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\n * {@link Auth} instance.\n *\n * @remarks\n * A new instance copy of the user provided will be made and set as currentUser.\n *\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\n * like other sign in methods.\n *\n * The operation fails with an error if the user to be updated belongs to a different Firebase\n * project.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param user - The new {@link User}.\n *\n * @public\n */\nexport function updateCurrentUser(\n auth: Auth,\n user: User | null\n): Promise {\n return getModularInstance(auth).updateCurrentUser(user);\n}\n/**\n * Signs out the current user.\n *\n * @remarks\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function signOut(auth: Auth): Promise {\n return getModularInstance(auth).signOut();\n}\n\n/**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n *\n * @param auth - The {@link Auth} instance.\n * @param token - The Apple OAuth access token.\n *\n * @public\n */\nexport function revokeAccessToken(auth: Auth, token: string): Promise {\n const authInternal = _castAuth(auth);\n return authInternal.revokeAccessToken(token);\n}\n\nexport { initializeAuth } from './auth/initialize';\nexport { connectAuthEmulator } from './auth/emulator';\n\n// credentials\nexport { AuthCredential } from './credentials';\nexport { EmailAuthCredential } from './credentials/email';\nexport { OAuthCredential } from './credentials/oauth';\nexport { PhoneAuthCredential } from './credentials/phone';\n\n// persistence\nexport { inMemoryPersistence } from './persistence/in_memory';\n\n// providers\nexport { EmailAuthProvider } from './providers/email';\nexport { FacebookAuthProvider } from './providers/facebook';\nexport { CustomParameters } from './providers/federated';\nexport { GoogleAuthProvider } from './providers/google';\nexport { GithubAuthProvider } from './providers/github';\nexport { OAuthProvider, OAuthCredentialOptions } from './providers/oauth';\nexport { SAMLAuthProvider } from './providers/saml';\nexport { TwitterAuthProvider } from './providers/twitter';\n\n// strategies\nexport { signInAnonymously } from './strategies/anonymous';\nexport {\n signInWithCredential,\n linkWithCredential,\n reauthenticateWithCredential\n} from './strategies/credential';\nexport { signInWithCustomToken } from './strategies/custom_token';\nexport {\n sendPasswordResetEmail,\n confirmPasswordReset,\n applyActionCode,\n checkActionCode,\n verifyPasswordResetCode,\n createUserWithEmailAndPassword,\n signInWithEmailAndPassword\n} from './strategies/email_and_password';\nexport {\n sendSignInLinkToEmail,\n isSignInWithEmailLink,\n signInWithEmailLink\n} from './strategies/email_link';\nexport {\n fetchSignInMethodsForEmail,\n sendEmailVerification,\n verifyBeforeUpdateEmail\n} from './strategies/email';\n\n// core\nexport { ActionCodeURL, parseActionCodeURL } from './action_code_url';\n\n// user\nexport {\n updateProfile,\n updateEmail,\n updatePassword\n} from './user/account_info';\nexport { getIdToken, getIdTokenResult } from './user/id_token_result';\nexport { unlink } from './user/link_unlink';\nexport { getAdditionalUserInfo } from './user/additional_user_info';\n\n// Non-optional user methods.\nexport { reload } from './user/reload';\n/**\n * Deletes and signs out the user.\n *\n * @remarks\n * Important: this is a security-sensitive operation that requires the user to have recently\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function deleteUser(user: User): Promise {\n return getModularInstance(user).delete();\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 { UserInternal } from '../model/user';\nimport { MultiFactorSession } from '../model/public_types';\n\nexport const enum MultiFactorSessionType {\n ENROLL = 'enroll',\n SIGN_IN = 'signin'\n}\n\ninterface SerializedMultiFactorSession {\n multiFactorSession: {\n idToken?: string;\n pendingCredential?: string;\n };\n}\n\nexport class MultiFactorSessionImpl implements MultiFactorSession {\n private constructor(\n readonly type: MultiFactorSessionType,\n readonly credential: string,\n readonly user?: UserInternal\n ) {}\n\n static _fromIdtoken(\n idToken: string,\n user?: UserInternal\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.ENROLL,\n idToken,\n user\n );\n }\n\n static _fromMfaPendingCredential(\n mfaPendingCredential: string\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.SIGN_IN,\n mfaPendingCredential\n );\n }\n\n toJSON(): SerializedMultiFactorSession {\n const key =\n this.type === MultiFactorSessionType.ENROLL\n ? 'idToken'\n : 'pendingCredential';\n return {\n multiFactorSession: {\n [key]: this.credential\n }\n };\n }\n\n static fromJSON(\n obj: Partial\n ): MultiFactorSessionImpl | null {\n if (obj?.multiFactorSession) {\n if (obj.multiFactorSession?.pendingCredential) {\n return MultiFactorSessionImpl._fromMfaPendingCredential(\n obj.multiFactorSession.pendingCredential\n );\n } else if (obj.multiFactorSession?.idToken) {\n return MultiFactorSessionImpl._fromIdtoken(\n obj.multiFactorSession.idToken\n );\n }\n }\n return null;\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 {\n Auth,\n MultiFactorResolver,\n UserCredential,\n MultiFactorError\n} from '../model/public_types';\n\nimport { _castAuth } from '../core/auth/auth_impl';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserCredentialImpl } from '../core/user/user_credential_impl';\nimport { _assert, _fail } from '../core/util/assert';\nimport { UserCredentialInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorError as MultiFactorErrorInternal } from './mfa_error';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../model/enums';\n\nexport class MultiFactorResolverImpl implements MultiFactorResolver {\n private constructor(\n readonly session: MultiFactorSessionImpl,\n readonly hints: MultiFactorInfoImpl[],\n private readonly signInResolver: (\n assertion: MultiFactorAssertionImpl\n ) => Promise\n ) {}\n\n /** @internal */\n static _fromError(\n authExtern: Auth,\n error: MultiFactorErrorInternal\n ): MultiFactorResolverImpl {\n const auth = _castAuth(authExtern);\n const serverResponse = error.customData._serverResponse;\n const hints = (serverResponse.mfaInfo || []).map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(auth, enrollment)\n );\n\n _assert(\n serverResponse.mfaPendingCredential,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(\n serverResponse.mfaPendingCredential\n );\n\n return new MultiFactorResolverImpl(\n session,\n hints,\n async (\n assertion: MultiFactorAssertionImpl\n ): Promise => {\n const mfaResponse = await assertion._process(auth, session);\n // Clear out the unneeded fields from the old login response\n delete serverResponse.mfaInfo;\n delete serverResponse.mfaPendingCredential;\n\n // Use in the new token & refresh token in the old response\n const idTokenResponse = {\n ...serverResponse,\n idToken: mfaResponse.idToken,\n refreshToken: mfaResponse.refreshToken\n };\n\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\n switch (error.operationType) {\n case OperationType.SIGN_IN:\n const userCredential =\n await UserCredentialImpl._fromIdTokenResponse(\n auth,\n error.operationType,\n idTokenResponse\n );\n await auth._updateCurrentUser(userCredential.user);\n return userCredential;\n case OperationType.REAUTHENTICATE:\n _assert(error.user, auth, AuthErrorCode.INTERNAL_ERROR);\n return UserCredentialImpl._forOperation(\n error.user,\n error.operationType,\n idTokenResponse\n );\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n );\n }\n\n async resolveSignIn(\n assertionExtern: MultiFactorAssertionImpl\n ): Promise {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n return this.signInResolver(assertion);\n }\n}\n\n/**\n * Provides a {@link MultiFactorResolver} suitable for completion of a\n * multi-factor flow.\n *\n * @param auth - The {@link Auth} instance.\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\n * reauthentication operation.\n *\n * @public\n */\nexport function getMultiFactorResolver(\n auth: Auth,\n error: MultiFactorError\n): MultiFactorResolver {\n const authModular = getModularInstance(auth);\n const errorInternal = error as MultiFactorErrorInternal;\n _assert(\n error.customData.operationType,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n errorInternal.customData._serverResponse?.mfaPendingCredential,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { SignInWithPhoneNumberRequest } from '../authentication/sms';\nimport { FinalizeMfaResponse } from '../authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\n\n/**\n * MFA Info as returned by the API.\n */\ninterface BaseMfaEnrollment {\n mfaEnrollmentId: string;\n enrolledAt: number;\n displayName?: string;\n}\n\n/**\n * An MFA provided by SMS verification.\n */\nexport interface PhoneMfaEnrollment extends BaseMfaEnrollment {\n phoneInfo: string;\n}\n\n/**\n * An MFA provided by TOTP (Time-based One Time Password).\n */\nexport interface TotpMfaEnrollment extends BaseMfaEnrollment {}\n\n/**\n * MfaEnrollment can be any subtype of BaseMfaEnrollment, currently only PhoneMfaEnrollment and TotpMfaEnrollment are supported.\n */\nexport type MfaEnrollment = PhoneMfaEnrollment | TotpMfaEnrollment;\n\nexport interface StartPhoneMfaEnrollmentRequest {\n idToken: string;\n phoneEnrollmentInfo: {\n phoneNumber: string;\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaEnrollmentResponse {\n phoneSessionInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startEnrollPhoneMfa(\n auth: AuthInternal,\n request: StartPhoneMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n StartPhoneMfaEnrollmentRequest,\n StartPhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaEnrollmentRequest {\n idToken: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollPhoneMfa(\n auth: AuthInternal,\n request: FinalizePhoneMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n FinalizePhoneMfaEnrollmentRequest,\n FinalizePhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface StartTotpMfaEnrollmentRequest {\n idToken: string;\n totpEnrollmentInfo: {};\n tenantId?: string;\n}\n\nexport interface StartTotpMfaEnrollmentResponse {\n totpSessionInfo: {\n sharedSecretKey: string;\n verificationCodeLength: number;\n hashingAlgorithm: string;\n periodSec: number;\n sessionInfo: string;\n finalizeEnrollmentTime: number;\n };\n}\n\nexport function startEnrollTotpMfa(\n auth: AuthInternal,\n request: StartTotpMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n StartTotpMfaEnrollmentRequest,\n StartTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface TotpVerificationInfo {\n sessionInfo: string;\n verificationCode: string;\n}\nexport interface FinalizeTotpMfaEnrollmentRequest {\n idToken: string;\n totpVerificationInfo: TotpVerificationInfo;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizeTotpMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollTotpMfa(\n auth: AuthInternal,\n request: FinalizeTotpMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n FinalizeTotpMfaEnrollmentRequest,\n FinalizeTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface WithdrawMfaRequest {\n idToken: string;\n mfaEnrollmentId: string;\n tenantId?: string;\n}\n\nexport interface WithdrawMfaResponse extends FinalizeMfaResponse {}\n\nexport function withdrawMfa(\n auth: AuthInternal,\n request: WithdrawMfaRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.WITHDRAW_MFA,\n _addTidIfNecessary(auth, request)\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 */\nimport {\n MultiFactorAssertion,\n MultiFactorInfo,\n MultiFactorSession,\n MultiFactorUser,\n User\n} from '../model/public_types';\n\nimport { withdrawMfa } from '../api/account_management/mfa';\nimport { _logoutIfInvalidated } from '../core/user/invalidation';\nimport { UserInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\n\nexport class MultiFactorUserImpl implements MultiFactorUser {\n enrolledFactors: MultiFactorInfo[] = [];\n\n private constructor(readonly user: UserInternal) {\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment)\n );\n }\n });\n }\n\n static _fromUser(user: UserInternal): MultiFactorUserImpl {\n return new MultiFactorUserImpl(user);\n }\n\n async getSession(): Promise {\n return MultiFactorSessionImpl._fromIdtoken(\n await this.user.getIdToken(),\n this.user\n );\n }\n\n async enroll(\n assertionExtern: MultiFactorAssertion,\n displayName?: string | null\n ): Promise {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n const session = (await this.getSession()) as MultiFactorSessionImpl;\n const finalizeMfaResponse = await _logoutIfInvalidated(\n this.user,\n assertion._process(this.user.auth, session, displayName)\n );\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n\n async unenroll(infoOrUid: MultiFactorInfo | string): Promise {\n const mfaEnrollmentId =\n typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n try {\n const idTokenResponse = await _logoutIfInvalidated(\n this.user,\n withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n })\n );\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(\n ({ uid }) => uid !== mfaEnrollmentId\n );\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n await this.user.reload();\n } catch (e) {\n throw e;\n }\n }\n}\n\nconst multiFactorUserCache = new WeakMap();\n\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nexport function multiFactor(user: User): MultiFactorUser {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(\n userModular,\n MultiFactorUserImpl._fromUser(userModular as UserInternal)\n );\n }\n return multiFactorUserCache.get(userModular)!;\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 */\nimport { Persistence } from '../../model/public_types';\n\nexport const enum PersistenceType {\n SESSION = 'SESSION',\n LOCAL = 'LOCAL',\n NONE = 'NONE'\n}\n\nexport type PersistedBlob = Record;\n\nexport interface Instantiator {\n (blob: PersistedBlob): T;\n}\n\nexport type PersistenceValue = PersistedBlob | string;\n\nexport const STORAGE_AVAILABLE_KEY = '__sak';\n\nexport interface StorageEventListener {\n (value: PersistenceValue | null): void;\n}\n\nexport interface PersistenceInternal extends Persistence {\n type: PersistenceType;\n _isAvailable(): Promise;\n _set(key: string, value: PersistenceValue): Promise;\n _get(key: string): Promise;\n _remove(key: string): Promise;\n _addListener(key: string, listener: StorageEventListener): void;\n _removeListener(key: string, listener: StorageEventListener): void;\n // Should this persistence allow migration up the chosen hierarchy?\n _shouldAllowMigration?: boolean;\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 {\n PersistenceValue,\n STORAGE_AVAILABLE_KEY,\n PersistenceType\n} from '../../core/persistence';\n\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\n\nexport abstract class BrowserPersistenceClass {\n protected constructor(\n protected readonly storageRetriever: () => Storage,\n readonly type: PersistenceType\n ) {}\n\n _isAvailable(): Promise {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n _set(key: string, value: PersistenceValue): Promise {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n\n _get(key: string): Promise {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n\n _remove(key: string): Promise {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n\n protected get storage(): Storage {\n return this.storageRetriever();\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 { Persistence } from '../../model/public_types';\n\nimport { getUA } from '@firebase/util';\nimport {\n _isSafari,\n _isIOS,\n _isIframe,\n _isMobileBrowser,\n _isIE10\n} from '../../core/util/browser';\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nfunction _iframeCannotSyncWebStorage(): boolean {\n const ua = getUA();\n return _isSafari(ua) || _isIOS(ua);\n}\n\n// The polling period in case events are not supported\nexport const _POLLING_INTERVAL_MS = 1000;\n\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\nclass BrowserLocalPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'LOCAL' = 'LOCAL';\n\n constructor() {\n super(() => window.localStorage, PersistenceType.LOCAL);\n }\n\n private readonly boundEventHandler = (\n event: StorageEvent,\n poll?: boolean\n ): void => this.onStorageEvent(event, poll);\n private readonly listeners: Record> = {};\n private readonly localCache: Record = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n\n // Safari or iOS browser and embedded in an iframe.\n private readonly safariLocalStorageNotSynced =\n _iframeCannotSyncWebStorage() && _isIframe();\n // Whether to use polling instead of depending on window events\n private readonly fallbackToPolling = _isMobileBrowser();\n readonly _shouldAllowMigration = true;\n\n private forAllChangedKeys(\n cb: (key: string, oldValue: string | null, newValue: string | null) => void\n ): void {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n\n private onStorageEvent(event: StorageEvent, poll = false): void {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys(\n (key: string, _oldValue: string | null, newValue: string | null) => {\n this.notifyListeners(key, newValue);\n }\n );\n return;\n }\n\n const key = event.key;\n\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n\n // Safari embedded iframe. Storage event will trigger with the delta\n // changes but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced) {\n // Get current iframe page value.\n const storedValue = this.storage.getItem(key);\n // Value not synchronized, synchronize manually.\n if (event.newValue !== storedValue) {\n if (event.newValue !== null) {\n // Value changed from current value.\n this.storage.setItem(key, event.newValue);\n } else {\n // Current value deleted.\n this.storage.removeItem(key);\n }\n } else if (this.localCache[key] === event.newValue && !poll) {\n // Already detected and processed, do not trigger listeners again.\n return;\n }\n }\n\n const triggerListeners = (): void => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n this.notifyListeners(key, storedValue);\n };\n\n const storedValue = this.storage.getItem(key);\n if (\n _isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue\n ) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n }\n\n private notifyListeners(key: string, value: string | null): void {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys(\n (key: string, oldValue: string | null, newValue: string | null) => {\n this.onStorageEvent(\n new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }),\n /* poll */ true\n );\n }\n );\n }, _POLLING_INTERVAL_MS);\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n private attachListener(): void {\n window.addEventListener('storage', this.boundEventHandler);\n }\n\n private detachListener(): void {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in some mobile browsers. A localStorage change in the foreground window\n // will not be detected in the background window via the storage event.\n // This was detected in iOS 7.x mobile browsers\n if (this.fallbackToPolling) {\n this.startPolling();\n } else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n\n // Update local cache on base operations:\n\n async _set(key: string, value: PersistenceValue): Promise {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n\n async _get(key: string): Promise {\n const value = await super._get(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n\n async _remove(key: string): Promise {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserLocalPersistence: Persistence = BrowserLocalPersistence;\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 { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nclass BrowserSessionPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'SESSION' = 'SESSION';\n\n constructor() {\n super(() => window.sessionStorage, PersistenceType.SESSION);\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserSessionPersistence: Persistence = BrowserSessionPersistence;\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/** TODO: remove this once tslib has a polyfill for Promise.allSettled */\ninterface PromiseFulfilledResult {\n fulfilled: true;\n value: T;\n}\n\ninterface PromiseRejectedResult {\n fulfilled: false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any;\n}\n\nexport type PromiseSettledResult =\n | PromiseFulfilledResult\n | PromiseRejectedResult;\n\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nexport function _allSettled(\n promises: Array>\n): Promise>> {\n return Promise.all(\n promises.map(async promise => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n } as PromiseFulfilledResult;\n } catch (reason) {\n return {\n fulfilled: false,\n reason\n } as PromiseRejectedResult;\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\nimport {\n ReceiverHandler,\n _EventType,\n _ReceiverResponse,\n SenderMessageEvent,\n _Status,\n _SenderRequest\n} from './index';\nimport { _allSettled } from './promise';\n\n/**\n * Interface class for receiving messages.\n *\n */\nexport class Receiver {\n private static readonly receivers: Receiver[] = [];\n private readonly boundEventHandler: EventListener;\n\n private readonly handlersMap: {\n // Typescript doesn't have existential types :(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [eventType: string]: Set>;\n } = {};\n\n constructor(private readonly eventTarget: EventTarget) {\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget: EventTarget): Receiver {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n const existingInstance = this.receivers.find(receiver =>\n receiver.isListeningto(eventTarget)\n );\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n\n private isListeningto(eventTarget: EventTarget): boolean {\n return this.eventTarget === eventTarget;\n }\n\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n private async handleEvent<\n T extends _ReceiverResponse,\n S extends _SenderRequest\n >(event: Event): Promise {\n const messageEvent = event as MessageEvent>;\n const { eventId, eventType, data } = messageEvent.data;\n\n const handlers: Set> | undefined =\n this.handlersMap[eventType];\n if (!handlers?.size) {\n return;\n }\n\n messageEvent.ports[0].postMessage({\n status: _Status.ACK,\n eventId,\n eventType\n });\n\n const promises = Array.from(handlers).map(async handler =>\n handler(messageEvent.origin, data)\n );\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: _Status.DONE,\n eventId,\n eventType,\n response\n });\n }\n\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe(\n eventType: _EventType,\n eventHandler: ReceiverHandler\n ): void {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n\n this.handlersMap[eventType].add(eventHandler);\n }\n\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe(\n eventType: _EventType,\n eventHandler?: ReceiverHandler\n ): void {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\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\nexport function _generateEventId(prefix = '', digits = 10): string {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\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 { _generateEventId } from '../../core/util/event_id';\nimport {\n _SenderRequest,\n _EventType,\n ReceiverMessageEvent,\n _MessageError,\n SenderMessageEvent,\n _Status,\n _ReceiverMessageResponse,\n _ReceiverResponse,\n _TimeoutDuration\n} from './index';\n\ninterface MessageHandler {\n messageChannel: MessageChannel;\n onMessage: EventListenerOrEventListenerObject;\n}\n\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nexport class Sender {\n private readonly handlers = new Set();\n\n constructor(private readonly target: ServiceWorker) {}\n\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n private removeMessageHandler(handler: MessageHandler): void {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener(\n 'message',\n handler.onMessage\n );\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send(\n eventType: _EventType,\n data: S,\n timeout = _TimeoutDuration.ACK\n ): Promise<_ReceiverMessageResponse> {\n const messageChannel =\n typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(_MessageError.CONNECTION_UNAVAILABLE);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer: any;\n let handler: MessageHandler;\n return new Promise<_ReceiverMessageResponse>((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(_MessageError.UNSUPPORTED_EVENT));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event: Event): void {\n const messageEvent = event as MessageEvent>;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case _Status.ACK:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(_MessageError.TIMEOUT));\n }, _TimeoutDuration.COMPLETION);\n break;\n case _Status.DONE:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(_MessageError.INVALID_RESPONSE));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage(\n {\n eventType,\n eventId,\n data\n } as SenderMessageEvent,\n [messageChannel.port2]\n );\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\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\nimport { Recaptcha, GreCAPTCHATopLevel } from './recaptcha/recaptcha';\n\n/**\n * A specialized window type that melds the normal window type plus the\n * various bits we need. The three different blocks that are &'d together\n * cant be defined in the same block together.\n */\nexport type AuthWindow = {\n // Standard window types\n [T in keyof Window]: Window[T];\n} & {\n // Any known / named properties we want to add\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n ___jsl?: Record;\n gapi?: typeof gapi;\n} & {\n // A final catch-all for callbacks (which will have random names) that\n // we will stick on the window.\n [callback: string]: (...args: unknown[]) => void;\n};\n\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nexport function _window(): AuthWindow {\n return window as unknown as AuthWindow;\n}\n\nexport function _setWindowLocation(url: string): void {\n _window().location.href = url;\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 { _window } from '../auth_window';\n\nexport function _isWorker(): boolean {\n return (\n typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function'\n );\n}\n\nexport async function _getActiveServiceWorker(): Promise {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n } catch {\n return null;\n }\n}\n\nexport function _getServiceWorkerController(): ServiceWorker | null {\n return navigator?.serviceWorker?.controller || null;\n}\n\nexport function _getWorkerGlobalScope(): ServiceWorker | null {\n return _isWorker() ? (self as unknown as ServiceWorker) : null;\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 { Persistence } from '../../model/public_types';\nimport {\n PersistedBlob,\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener,\n STORAGE_AVAILABLE_KEY\n} from '../../core/persistence/';\nimport {\n _EventType,\n _PingResponse,\n KeyChangedResponse,\n KeyChangedRequest,\n PingRequest,\n _TimeoutDuration\n} from '../messagechannel/index';\nimport { Receiver } from '../messagechannel/receiver';\nimport { Sender } from '../messagechannel/sender';\nimport {\n _isWorker,\n _getActiveServiceWorker,\n _getServiceWorkerController,\n _getWorkerGlobalScope\n} from '../util/worker';\n\nexport const DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n\ninterface DBObject {\n [DB_DATA_KEYPATH]: string;\n value: PersistedBlob;\n}\n\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\n *\n */\nclass DBPromise {\n constructor(private readonly request: IDBRequest) {}\n\n toPromise(): Promise {\n return new Promise((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\n\nfunction getObjectStore(db: IDBDatabase, isReadWrite: boolean): IDBObjectStore {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\n\nexport async function _clearDatabase(db: IDBDatabase): Promise {\n const objectStore = getObjectStore(db, true);\n return new DBPromise(objectStore.clear()).toPromise();\n}\n\nexport function _deleteDatabase(): Promise {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise(request).toPromise();\n}\n\nexport function _openDatabase(): Promise {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n } catch (e) {\n reject(e);\n }\n });\n\n request.addEventListener('success', async () => {\n const db: IDBDatabase = request.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n } else {\n resolve(db);\n }\n });\n });\n}\n\nexport async function _putObject(\n db: IDBDatabase,\n key: string,\n value: PersistenceValue | string\n): Promise {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise(request).toPromise();\n}\n\nasync function getObject(\n db: IDBDatabase,\n key: string\n): Promise {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise(request).toPromise();\n return data === undefined ? null : data.value;\n}\n\nexport function _deleteObject(db: IDBDatabase, key: string): Promise {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise(request).toPromise();\n}\n\nexport const _POLLING_INTERVAL_MS = 800;\nexport const _TRANSACTION_RETRY_COUNT = 3;\n\nclass IndexedDBLocalPersistence implements InternalPersistence {\n static type: 'LOCAL' = 'LOCAL';\n\n type = PersistenceType.LOCAL;\n db?: IDBDatabase;\n readonly _shouldAllowMigration = true;\n\n private readonly listeners: Record> = {};\n private readonly localCache: Record = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n private pendingWrites = 0;\n\n private receiver: Receiver | null = null;\n private sender: Sender | null = null;\n private serviceWorkerReceiverAvailable = false;\n private activeServiceWorker: ServiceWorker | null = null;\n // Visible for testing only\n readonly _workerInitializationPromise: Promise;\n\n constructor() {\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(\n () => {},\n () => {}\n );\n }\n\n async _openDb(): Promise {\n if (this.db) {\n return this.db;\n }\n this.db = await _openDatabase();\n return this.db;\n }\n\n async _withRetries(op: (db: IDBDatabase) => Promise): Promise {\n let numAttempts = 0;\n\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n } catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.db) {\n this.db.close();\n this.db = undefined;\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n private async initializeServiceWorkerMessaging(): Promise {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n\n /**\n * As the worker we should listen to events from the main window.\n */\n private async initializeReceiver(): Promise {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope()!);\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\n _EventType.KEY_CHANGED,\n async (_origin: string, data: KeyChangedRequest) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n }\n );\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\n _EventType.PING,\n async (_origin: string, _data: PingRequest) => {\n return [_EventType.KEY_CHANGED];\n }\n );\n }\n\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n private async initializeSender(): Promise {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send<_PingResponse, PingRequest>(\n _EventType.PING,\n {},\n _TimeoutDuration.LONG_ACK\n );\n if (!results) {\n return;\n }\n if (\n results[0]?.fulfilled &&\n results[0]?.value.includes(_EventType.KEY_CHANGED)\n ) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n private async notifyServiceWorker(key: string): Promise {\n if (\n !this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker\n ) {\n return;\n }\n try {\n await this.sender._send(\n _EventType.KEY_CHANGED,\n { key },\n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? _TimeoutDuration.LONG_ACK\n : _TimeoutDuration.ACK\n );\n } catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n\n async _isAvailable(): Promise {\n try {\n if (!indexedDB) {\n return false;\n }\n const db = await _openDatabase();\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n return true;\n } catch {}\n return false;\n }\n\n private async _withPendingWrite(write: () => Promise): Promise {\n this.pendingWrites++;\n try {\n await write();\n } finally {\n this.pendingWrites--;\n }\n }\n\n async _set(key: string, value: PersistenceValue): Promise {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n\n async _get(key: string): Promise {\n const obj = (await this._withRetries((db: IDBDatabase) =>\n getObject(db, key)\n )) as T;\n this.localCache[key] = obj;\n return obj;\n }\n\n async _remove(key: string): Promise {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n\n private async _poll(): Promise {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db: IDBDatabase) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise(getAllRequest).toPromise();\n });\n\n if (!result) {\n return [];\n }\n\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n\n const keys = [];\n const keysInResult = new Set();\n if (result.length !== 0) {\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value as PersistenceValue);\n keys.push(key);\n }\n }\n }\n\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n\n private notifyListeners(\n key: string,\n newValue: PersistenceValue | null\n ): void {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(\n async () => this._poll(),\n _POLLING_INTERVAL_MS\n );\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n }\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nexport const indexedDBLocalPersistence: Persistence = IndexedDBLocalPersistence;\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 {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from '../account_management/mfa';\nimport { SignInWithIdpResponse } from './idp';\nimport {\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n} from './sms';\n\nexport interface FinalizeMfaResponse {\n idToken: string;\n refreshToken: string;\n}\n\n/**\n * @internal\n */\nexport interface IdTokenMfaResponse extends IdTokenResponse {\n mfaPendingCredential?: string;\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface StartPhoneMfaSignInRequest {\n mfaPendingCredential: string;\n mfaEnrollmentId: string;\n phoneSignInInfo: {\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaSignInResponse {\n phoneResponseInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startSignInPhoneMfa(\n auth: Auth,\n request: StartPhoneMfaSignInRequest\n): Promise {\n return _performApiRequest<\n StartPhoneMfaSignInRequest,\n StartPhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaSignInRequest {\n mfaPendingCredential: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n tenantId?: string;\n}\n\n// TOTP MFA Sign in only has a finalize phase. Phone MFA has a start phase to initiate sending an\n// SMS and a finalize phase to complete sign in. With TOTP, the user already has the OTP in the\n// TOTP/Authenticator app.\nexport interface FinalizeTotpMfaSignInRequest {\n mfaPendingCredential: string;\n totpVerificationInfo: { verificationCode: string };\n tenantId?: string;\n mfaEnrollmentId: string;\n}\n\nexport interface FinalizePhoneMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport interface FinalizeTotpMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport function finalizeSignInPhoneMfa(\n auth: Auth,\n request: FinalizePhoneMfaSignInRequest\n): Promise {\n return _performApiRequest<\n FinalizePhoneMfaSignInRequest,\n FinalizePhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport function finalizeSignInTotpMfa(\n auth: Auth,\n request: FinalizeTotpMfaSignInRequest\n): Promise {\n return _performApiRequest<\n FinalizeTotpMfaSignInRequest,\n FinalizeTotpMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport type PhoneOrOauthTokenResponse =\n | SignInWithPhoneNumberResponse\n | SignInWithIdpResponse\n | IdTokenResponse;\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 { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport { RecaptchaParameters } from '../../model/public_types';\nimport {\n Recaptcha,\n GreCAPTCHATopLevel,\n GreCAPTCHARenderOption,\n GreCAPTCHA\n} from './recaptcha';\n\nexport const _SOLVE_TIME_MS = 500;\nexport const _EXPIRATION_TIME_MS = 60_000;\nexport const _WIDGET_ID_START = 1_000_000_000_000;\n\nexport interface Widget {\n getResponse: () => string | null;\n delete: () => void;\n execute: () => void;\n}\n\nexport class MockReCaptcha implements Recaptcha {\n private counter = _WIDGET_ID_START;\n _widgets = new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n render(\n container: string | HTMLElement,\n parameters?: RecaptchaParameters\n ): number {\n const id = this.counter;\n this._widgets.set(\n id,\n new MockWidget(container, this.auth.name, parameters || {})\n );\n this.counter++;\n return id;\n }\n\n reset(optWidgetId?: number): void {\n const id = optWidgetId || _WIDGET_ID_START;\n void this._widgets.get(id)?.delete();\n this._widgets.delete(id);\n }\n\n getResponse(optWidgetId?: number): string {\n const id = optWidgetId || _WIDGET_ID_START;\n return this._widgets.get(id)?.getResponse() || '';\n }\n\n async execute(optWidgetId?: number | string): Promise {\n const id: number = (optWidgetId as number) || _WIDGET_ID_START;\n void this._widgets.get(id)?.execute();\n return '';\n }\n}\n\nexport class MockGreCAPTCHATopLevel implements GreCAPTCHATopLevel {\n enterprise: GreCAPTCHA = new MockGreCAPTCHA();\n ready(callback: () => void): void {\n callback();\n }\n\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey: string,\n _options: { action: string }\n ): Promise {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container: string | HTMLElement,\n _parameters: GreCAPTCHARenderOption\n ): string {\n return '';\n }\n}\n\nexport class MockGreCAPTCHA implements GreCAPTCHA {\n ready(callback: () => void): void {\n callback();\n }\n\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey: string,\n _options: { action: string }\n ): Promise {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container: string | HTMLElement,\n _parameters: GreCAPTCHARenderOption\n ): string {\n return '';\n }\n}\n\nexport class MockWidget {\n private readonly container: HTMLElement;\n private readonly isVisible: boolean;\n private timerId: number | null = null;\n private deleted = false;\n private responseToken: string | null = null;\n private readonly clickHandler = (): void => {\n this.execute();\n };\n\n constructor(\n containerOrId: string | HTMLElement,\n appName: string,\n private readonly params: RecaptchaParameters\n ) {\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, AuthErrorCode.ARGUMENT_ERROR, { appName });\n\n this.container = container;\n this.isVisible = this.params.size !== 'invisible';\n if (this.isVisible) {\n this.execute();\n } else {\n this.container.addEventListener('click', this.clickHandler);\n }\n }\n\n getResponse(): string | null {\n this.checkIfDeleted();\n return this.responseToken;\n }\n\n delete(): void {\n this.checkIfDeleted();\n this.deleted = true;\n if (this.timerId) {\n clearTimeout(this.timerId);\n this.timerId = null;\n }\n this.container.removeEventListener('click', this.clickHandler);\n }\n\n execute(): void {\n this.checkIfDeleted();\n if (this.timerId) {\n return;\n }\n\n this.timerId = window.setTimeout(() => {\n this.responseToken = generateRandomAlphaNumericString(50);\n const { callback, 'expired-callback': expiredCallback } = this.params;\n if (callback) {\n try {\n callback(this.responseToken);\n } catch (e) {}\n }\n\n this.timerId = window.setTimeout(() => {\n this.timerId = null;\n this.responseToken = null;\n if (expiredCallback) {\n try {\n expiredCallback();\n } catch (e) {}\n }\n\n if (this.isVisible) {\n this.execute();\n }\n }, _EXPIRATION_TIME_MS);\n }, _SOLVE_TIME_MS);\n }\n\n private checkIfDeleted(): void {\n if (this.deleted) {\n throw new Error('reCAPTCHA mock was already deleted!');\n }\n }\n}\n\nfunction generateRandomAlphaNumericString(len: number): string {\n const chars = [];\n const allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < len; i++) {\n chars.push(\n allowedChars.charAt(Math.floor(Math.random() * allowedChars.length))\n );\n }\n return chars.join('');\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 { querystring } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as jsHelpers from '../load_js';\nimport { Recaptcha, isV2 } from './recaptcha';\nimport { MockReCaptcha } from './recaptcha_mock';\n\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nexport const _JSLOAD_CALLBACK = jsHelpers._generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\n\n/**\n * We need to mark this interface as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport interface ReCaptchaLoader {\n load(auth: AuthInternal, hl?: string): Promise;\n clearedOneInstance(): void;\n}\n\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nexport class ReCaptchaLoaderImpl implements ReCaptchaLoader {\n private hostLanguage = '';\n private counter = 0;\n /**\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\n * `window.grecaptcha.render()` will not. Another load will add it.\n */\n private readonly librarySeparatelyLoaded = !!_window().grecaptcha?.render;\n\n load(auth: AuthInternal, hl = ''): Promise {\n _assert(isHostLanguageValid(hl), auth, AuthErrorCode.ARGUMENT_ERROR);\n\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\n return Promise.resolve(_window().grecaptcha! as Recaptcha);\n }\n return new Promise((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, NETWORK_TIMEOUT_DELAY.get());\n\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n\n const recaptcha = _window().grecaptcha as Recaptcha;\n\n if (!recaptcha || !isV2(recaptcha)) {\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n return;\n }\n\n // Wrap the greptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n\n const url = `${jsHelpers._recaptchaV2ScriptUrl()}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n\n jsHelpers._loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n });\n });\n }\n\n clearedOneInstance(): void {\n this.counter--;\n }\n\n private shouldResolveImmediately(hl: string): boolean {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (\n !!_window().grecaptcha?.render &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded)\n );\n }\n}\n\nfunction isHostLanguageValid(hl: string): boolean {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\n\nexport class MockReCaptchaLoaderImpl implements ReCaptchaLoader {\n async load(auth: AuthInternal): Promise {\n return new MockReCaptcha(auth);\n }\n\n clearedOneInstance(): void {}\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 { Auth, RecaptchaParameters } from '../../model/public_types';\nimport { getRecaptchaParams } from '../../api/authentication/recaptcha';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { _isHttpOrHttps } from '../../core/util/location';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport { _isWorker } from '../util/worker';\nimport { Recaptcha } from './recaptcha';\nimport {\n MockReCaptchaLoaderImpl,\n ReCaptchaLoader,\n ReCaptchaLoaderImpl\n} from './recaptcha_loader';\n\nexport const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\n\nconst DEFAULT_PARAMS: RecaptchaParameters = {\n theme: 'light',\n type: 'image'\n};\n\ntype TokenCallback = (token: string) => void;\n\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @remarks\n * `RecaptchaVerifier` does not work in a Node.js environment.\n *\n * @public\n */\nexport class RecaptchaVerifier implements ApplicationVerifierInternal {\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n readonly type = RECAPTCHA_VERIFIER_TYPE;\n private destroyed = false;\n private widgetId: number | null = null;\n private readonly container: HTMLElement;\n private readonly isInvisible: boolean;\n private readonly tokenChangeListeners = new Set();\n private renderPromise: Promise | null = null;\n private readonly auth: AuthInternal;\n\n /** @internal */\n readonly _recaptchaLoader: ReCaptchaLoader;\n private recaptcha: Recaptcha | null = null;\n\n /**\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n */\n constructor(\n authExtern: Auth,\n containerOrId: HTMLElement | string,\n private readonly parameters: RecaptchaParameters = {\n ...DEFAULT_PARAMS\n }\n ) {\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify(): Promise {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n\n return new Promise(resolve => {\n const tokenChange = (token: string): void => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render(): Promise {\n try {\n this.assertNotDestroyed();\n } catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n\n if (this.renderPromise) {\n return this.renderPromise;\n }\n\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n\n return this.renderPromise;\n }\n\n /** @internal */\n _reset(): void {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear(): void {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n\n private validateStartingState(): void {\n _assert(!this.parameters.sitekey, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n this.isInvisible || !this.container.hasChildNodes(),\n this.auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n }\n\n private makeTokenCallback(\n existing: TokenCallback | string | undefined\n ): TokenCallback {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n } else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n\n private assertNotDestroyed(): void {\n _assert(!this.destroyed, this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n\n private async makeRenderPromise(): Promise {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n\n this.widgetId = this.getAssertedRecaptcha().render(\n container,\n this.parameters\n );\n }\n\n return this.widgetId;\n }\n\n private async init(): Promise {\n _assert(\n _isHttpOrHttps() && !_isWorker(),\n this.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(\n this.auth,\n this.auth.languageCode || undefined\n );\n\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.parameters.sitekey = siteKey;\n }\n\n private getAssertedRecaptcha(): Recaptcha {\n _assert(this.recaptcha, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.recaptcha;\n }\n}\n\nfunction domReady(): Promise {\n let resolver: (() => void) | null = null;\n return new Promise(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n\n throw e;\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 {\n ApplicationVerifier,\n Auth,\n ConfirmationResult,\n PhoneInfoOptions,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { startEnrollPhoneMfa } from '../../api/account_management/mfa';\nimport { startSignInPhoneMfa } from '../../api/authentication/mfa';\nimport { sendPhoneVerificationCode } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assertLinkedStatus, _link } from '../../core/user/link_unlink';\nimport {\n _assert,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport {\n linkWithCredential,\n reauthenticateWithCredential,\n signInWithCredential\n} from '../../core/strategies/credential';\nimport {\n MultiFactorSessionImpl,\n MultiFactorSessionType\n} from '../../mfa/mfa_session';\nimport { UserInternal } from '../../model/user';\nimport { RECAPTCHA_VERIFIER_TYPE } from '../recaptcha/recaptcha_verifier';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\ninterface OnConfirmationCallback {\n (credential: PhoneAuthCredential): Promise;\n}\n\nclass ConfirmationResultImpl implements ConfirmationResult {\n constructor(\n readonly verificationId: string,\n private readonly onConfirmation: OnConfirmationCallback\n ) {}\n\n confirm(verificationCode: string): Promise {\n const authCredential = PhoneAuthCredential._fromVerification(\n this.verificationId,\n verificationCode\n );\n return this.onConfirmation(authCredential);\n }\n}\n\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function signInWithPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(\n authInternal,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n signInWithCredential(authInternal, cred)\n );\n}\n\n/**\n * Links the user account with the given phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function linkWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(false, userInternal, ProviderId.PHONE);\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n linkWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function reauthenticateWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(userInternal.auth)\n );\n }\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n reauthenticateWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nexport async function _verifyPhoneNumber(\n auth: AuthInternal,\n options: PhoneInfoOptions | string,\n verifier: ApplicationVerifierInternal\n): Promise {\n const recaptchaToken = await verifier.verify();\n\n try {\n _assert(\n typeof recaptchaToken === 'string',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n verifier.type === RECAPTCHA_VERIFIER_TYPE,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n let phoneInfoOptions: PhoneInfoOptions;\n\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n } else {\n phoneInfoOptions = options;\n }\n\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session as MultiFactorSessionImpl;\n\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(\n session.type === MultiFactorSessionType.ENROLL,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollPhoneMfa(auth, {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n }\n });\n return response.phoneSessionInfo.sessionInfo;\n } else {\n _assert(\n session.type === MultiFactorSessionType.SIGN_IN,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const mfaEnrollmentId =\n phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, AuthErrorCode.MISSING_MFA_INFO);\n const response = await startSignInPhoneMfa(auth, {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n recaptchaToken\n }\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n } else {\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n });\n return sessionInfo;\n }\n } finally {\n verifier._reset();\n }\n}\n\n/**\n * Updates the user's phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nexport async function updatePhoneNumber(\n user: User,\n credential: PhoneAuthCredential\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(userInternal.auth)\n );\n }\n await _link(userInternal, credential);\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 {\n Auth,\n PhoneInfoOptions,\n ApplicationVerifier,\n UserCredential\n} from '../../model/public_types';\n\nimport { SignInWithPhoneNumberResponse } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal as ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal as AuthInternal } from '../../model/auth';\nimport { UserCredentialInternal as UserCredentialInternal } from '../../model/user';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { _verifyPhoneNumber } from '../strategies/phone';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthCredential } from '../../core';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @remarks\n * `PhoneAuthProvider` does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nexport class PhoneAuthProvider {\n /** Always set to {@link ProviderId}.PHONE. */\n static readonly PROVIDER_ID: 'phone' = ProviderId.PHONE;\n /** Always set to {@link SignInMethod}.PHONE. */\n static readonly PHONE_SIGN_IN_METHOD: 'phone' = SignInMethod.PHONE;\n\n /** Always set to {@link ProviderId}.PHONE. */\n readonly providerId = PhoneAuthProvider.PROVIDER_ID;\n private readonly auth: AuthInternal;\n\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth: Auth) {\n this.auth = _castAuth(auth);\n }\n\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - For abuse prevention, this method also requires a\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\n * {@link RecaptchaVerifier}.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow..\n */\n verifyPhoneNumber(\n phoneOptions: PhoneInfoOptions | string,\n applicationVerifier: ApplicationVerifier\n ): Promise {\n return _verifyPhoneNumber(\n this.auth,\n phoneOptions,\n getModularInstance(applicationVerifier as ApplicationVerifierInternal)\n );\n }\n\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return PhoneAuthCredential._fromVerification(\n verificationId,\n verificationCode\n );\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n const credential = userCredential as UserCredentialInternal;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return PhoneAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): AuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } =\n tokenResponse as SignInWithPhoneNumberResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(\n phoneNumber,\n temporaryProof\n );\n }\n return null;\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 { PopupRedirectResolver } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { _getInstance } from './instantiator';\n\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nexport function _withDefaultResolver(\n auth: AuthInternal,\n resolverOverride: PopupRedirectResolver | undefined\n): PopupRedirectResolverInternal {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n\n _assert(auth._popupRedirectResolver, auth, AuthErrorCode.ARGUMENT_ERROR);\n\n return auth._popupRedirectResolver;\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 {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _link as _linkUser } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { _assert } from '../util/assert';\nimport { _signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { ProviderId } from '../../model/enums';\n\nexport interface IdpTaskParams {\n auth: AuthInternal;\n requestUri: string;\n sessionId?: string;\n tenantId?: string;\n postBody?: string;\n pendingToken?: string;\n user?: UserInternal;\n bypassAuthState?: boolean;\n}\n\nexport type IdpTask = (\n params: IdpTaskParams\n) => Promise;\n\nclass IdpCredential extends AuthCredential {\n constructor(readonly params: IdpTaskParams) {\n super(ProviderId.CUSTOM, ProviderId.CUSTOM);\n }\n\n _getIdTokenResponse(auth: AuthInternal): Promise {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n private _buildIdpRequest(idToken?: string): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n\n if (idToken) {\n request.idToken = idToken;\n }\n\n return request;\n }\n}\n\nexport function _signIn(\n params: IdpTaskParams\n): Promise {\n return _signInWithCredential(\n params.auth,\n new IdpCredential(params),\n params.bypassAuthState\n ) as Promise;\n}\n\nexport function _reauth(\n params: IdpTaskParams\n): Promise {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _reauthenticate(\n user,\n new IdpCredential(params),\n params.bypassAuthState\n );\n}\n\nexport async function _link(\n params: IdpTaskParams\n): Promise {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _linkUser(user, new IdpCredential(params), params.bypassAuthState);\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 { FirebaseError } from '@firebase/util';\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { debugAssert, _fail } from '../util/assert';\nimport {\n _link,\n _reauth,\n _signIn,\n IdpTask,\n IdpTaskParams\n} from '../strategies/idp';\nimport { AuthInternal } from '../../model/auth';\n\ninterface PendingPromise {\n resolve: (cred: UserCredentialInternal | null) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nexport abstract class AbstractPopupRedirectOperation\n implements AuthEventConsumer\n{\n private pendingPromise: PendingPromise | null = null;\n private eventManager: EventManager | null = null;\n readonly filter: AuthEventType[];\n\n abstract eventId: string | null;\n\n constructor(\n protected readonly auth: AuthInternal,\n filter: AuthEventType | AuthEventType[],\n protected readonly resolver: PopupRedirectResolverInternal,\n protected user?: UserInternal,\n protected readonly bypassAuthState = false\n ) {\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n\n abstract onExecution(): Promise;\n\n execute(): Promise {\n return new Promise(\n async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n } catch (e) {\n this.reject(e as Error);\n }\n }\n );\n }\n\n async onAuthEvent(event: AuthEvent): Promise {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n\n const params: IdpTaskParams = {\n auth: this.auth,\n requestUri: urlResponse!,\n sessionId: sessionId!,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n\n try {\n this.resolve(await this.getIdpTask(type)(params));\n } catch (e) {\n this.reject(e as Error);\n }\n }\n\n onError(error: FirebaseError): void {\n this.reject(error);\n }\n\n private getIdpTask(type: AuthEventType): IdpTask {\n switch (type) {\n case AuthEventType.SIGN_IN_VIA_POPUP:\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n return _signIn;\n case AuthEventType.LINK_VIA_POPUP:\n case AuthEventType.LINK_VIA_REDIRECT:\n return _link;\n case AuthEventType.REAUTH_VIA_POPUP:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return _reauth;\n default:\n _fail(this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n protected resolve(cred: UserCredentialInternal | null): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n\n protected reject(error: Error): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n\n private unregisterAndCleanUp(): void {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n\n this.pendingPromise = null;\n this.cleanUp();\n }\n\n abstract cleanUp(): void;\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 {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _assert,\n debugAssert,\n _createError,\n _assertInstanceOf\n} from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport { AuthPopup } from '../util/popup';\nimport { AbstractPopupRedirectOperation } from '../../core/strategies/abstract_popup_redirect_operation';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\n/*\n * The event timeout is the same on mobile and desktop, no need for Delay. Set this to 8s since\n * blocking functions can take upto 7s to complete sign in, as documented in:\n * https://cloud.google.com/identity-platform/docs/blocking-functions#understanding_blocking_functions\n * https://firebase.google.com/docs/auth/extend-with-blocking-functions#understanding_blocking_functions\n */\nexport const enum _Timeout {\n AUTH_EVENT = 8000\n}\nexport const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function signInWithPopup(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _createError(auth, AuthErrorCode.OPERATION_NOT_SUPPORTED)\n );\n }\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(\n authInternal,\n AuthEventType.SIGN_IN_VIA_POPUP,\n provider,\n resolverInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function reauthenticateWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _createError(userInternal.auth, AuthErrorCode.OPERATION_NOT_SUPPORTED)\n );\n }\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.REAUTH_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function linkWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.LINK_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n // Only one popup is ever shown at once. The lifecycle of the current popup\n // can be managed / cancelled by the constructor.\n private static currentPopupAction: PopupOperation | null = null;\n private authWindow: AuthPopup | null = null;\n private pollId: number | null = null;\n\n constructor(\n auth: AuthInternal,\n filter: AuthEventType,\n private readonly provider: AuthProvider,\n resolver: PopupRedirectResolverInternal,\n user?: UserInternal\n ) {\n super(auth, filter, resolver, user);\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n\n PopupOperation.currentPopupAction = this;\n }\n\n async executeNotNull(): Promise {\n const result = await this.execute();\n _assert(result, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return result;\n }\n\n async onExecution(): Promise {\n debugAssert(\n this.filter.length === 1,\n 'Popup operations only handle one event'\n );\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(\n this.auth,\n this.provider,\n this.filter[0], // There's always one, see constructor\n eventId\n );\n this.authWindow.associatedEvent = eventId;\n\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(\n _createError(this.auth, AuthErrorCode.WEB_STORAGE_UNSUPPORTED)\n );\n }\n });\n\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n\n get eventId(): string | null {\n return this.authWindow?.associatedEvent || null;\n }\n\n cancel(): void {\n this.reject(_createError(this.auth, AuthErrorCode.EXPIRED_POPUP_REQUEST));\n }\n\n cleanUp(): void {\n if (this.authWindow) {\n this.authWindow.close();\n }\n\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n\n private pollUserCancellation(): void {\n const poll = (): void => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight. This is specifically true for\n // Firefox or if the opener is in an iframe, in which case the oauth\n // helper closes the popup.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(\n _createError(this.auth, AuthErrorCode.POPUP_CLOSED_BY_USER)\n );\n }, _Timeout.AUTH_EVENT);\n return;\n }\n\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n\n poll();\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 { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserCredentialInternal } from '../../model/user';\nimport { PersistenceInternal } from '../persistence';\nimport { _persistenceKeyName } from '../persistence/persistence_user_manager';\nimport { _getInstance } from '../util/instantiator';\nimport { AbstractPopupRedirectOperation } from './abstract_popup_redirect_operation';\n\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap: Map<\n string,\n () => Promise\n> = new Map();\n\nexport class RedirectAction extends AbstractPopupRedirectOperation {\n eventId = null;\n\n constructor(\n auth: AuthInternal,\n resolver: PopupRedirectResolverInternal,\n bypassAuthState = false\n ) {\n super(\n auth,\n [\n AuthEventType.SIGN_IN_VIA_REDIRECT,\n AuthEventType.LINK_VIA_REDIRECT,\n AuthEventType.REAUTH_VIA_REDIRECT,\n AuthEventType.UNKNOWN\n ],\n resolver,\n undefined,\n bypassAuthState\n );\n }\n\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute(): Promise {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(\n this.resolver,\n this.auth\n );\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n } catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n\n return readyOutcome();\n }\n\n async onAuthEvent(event: AuthEvent): Promise {\n if (event.type === AuthEventType.SIGN_IN_VIA_REDIRECT) {\n return super.onAuthEvent(event);\n } else if (event.type === AuthEventType.UNKNOWN) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n } else {\n this.resolve(null);\n }\n }\n }\n\n async onExecution(): Promise {}\n\n cleanUp(): void {}\n}\n\nexport async function _getAndClearPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\n\nexport async function _setPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\n\nexport function _clearRedirectOutcomes(): void {\n redirectOutcomeMap.clear();\n}\n\nexport function _overrideRedirectResult(\n auth: AuthInternal,\n result: () => Promise\n): void {\n redirectOutcomeMap.set(auth._key(), result);\n}\n\nfunction resolverPersistence(\n resolver: PopupRedirectResolverInternal\n): PersistenceInternal {\n return _getInstance(resolver._redirectPersistence);\n}\n\nfunction pendingRedirectKey(auth: AuthInternal): string {\n return _persistenceKeyName(\n PENDING_REDIRECT_KEY,\n auth.config.apiKey,\n auth.name\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 {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { _assertLinkedStatus } from '../../core/user/link_unlink';\nimport {\n _assertInstanceOf,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../../core/util/assert';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport {\n RedirectAction,\n _setPendingRedirectStatus\n} from '../../core/strategies/redirect';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link signInWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _signInWithRedirect(auth, provider, resolver) as Promise;\n}\n\nexport async function _signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await authInternal._initializationPromise;\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n\n return resolverInternal._openRedirect(\n authInternal,\n provider,\n AuthEventType.SIGN_IN_VIA_REDIRECT\n );\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link reauthenticateWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Reauthenticate using a redirect.\n * await reauthenticateWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _reauthenticateWithRedirect(\n user,\n provider,\n resolver\n ) as Promise;\n}\nexport async function _reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(userInternal.auth)\n );\n }\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.REAUTH_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link linkWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _linkWithRedirect(user, provider, resolver) as Promise;\n}\nexport async function _linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.LINK_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns `null`.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function getRedirectResult(\n auth: Auth,\n resolver?: PopupRedirectResolver\n): Promise {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\n\nexport async function _getRedirectResult(\n auth: Auth,\n resolverExtern?: PopupRedirectResolver,\n bypassAuthState = false\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user as UserInternal);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n\n return result;\n}\n\nasync function prepareUserForRedirect(user: UserInternal): Promise {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\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 {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager\n} from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { AuthInternal } from '../../model/auth';\nimport { _createError } from '../util/assert';\n\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\n\nexport class AuthEventManager implements EventManager {\n private readonly cachedEventUids: Set = new Set();\n private readonly consumers: Set = new Set();\n protected queuedRedirectEvent: AuthEvent | null = null;\n protected hasHandledPotentialRedirect = false;\n private lastProcessedEventTime = Date.now();\n\n constructor(private readonly auth: AuthInternal) {}\n\n registerConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.add(authEventConsumer);\n\n if (\n this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)\n ) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n\n unregisterConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.delete(authEventConsumer);\n }\n\n onEvent(event: AuthEvent): boolean {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n\n this.hasHandledPotentialRedirect = true;\n\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n\n return handled;\n }\n\n private sendToConsumer(event: AuthEvent, consumer: AuthEventConsumer): void {\n if (event.error && !isNullRedirectEvent(event)) {\n const code =\n (event.error.code?.split('auth/')[1] as AuthErrorCode) ||\n AuthErrorCode.INTERNAL_ERROR;\n consumer.onError(_createError(this.auth, code));\n } else {\n consumer.onAuthEvent(event);\n }\n }\n\n private isEventForConsumer(\n event: AuthEvent,\n consumer: AuthEventConsumer\n ): boolean {\n const eventIdMatches =\n consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n\n private hasEventBeenHandled(event: AuthEvent): boolean {\n if (\n Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS\n ) {\n this.cachedEventUids.clear();\n }\n\n return this.cachedEventUids.has(eventUid(event));\n }\n\n private saveEventToCache(event: AuthEvent): void {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\n\nfunction eventUid(e: AuthEvent): string {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\n\nfunction isNullRedirectEvent({ type, error }: AuthEvent): boolean {\n return (\n type === AuthEventType.UNKNOWN &&\n error?.code === `auth/${AuthErrorCode.NO_AUTH_EVENT}`\n );\n}\n\nfunction isRedirectEvent(event: AuthEvent): boolean {\n switch (event.type) {\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n case AuthEventType.LINK_VIA_REDIRECT:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return true;\n case AuthEventType.UNKNOWN:\n return isNullRedirectEvent(event);\n default:\n return false;\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 { _performApiRequest, Endpoint, HttpMethod } from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface GetProjectConfigRequest {\n androidPackageName?: string;\n iosBundleId?: string;\n}\n\nexport interface GetProjectConfigResponse {\n authorizedDomains: string[];\n}\n\nexport async function _getProjectConfig(\n auth: Auth,\n request: GetProjectConfigRequest = {}\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PROJECT_CONFIG,\n request\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 { _getProjectConfig } from '../../api/project_config/get_project_config';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from './assert';\nimport { _getCurrentUrl } from './location';\n\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\n\nexport async function _validateOrigin(auth: AuthInternal): Promise {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n\n const { authorizedDomains } = await _getProjectConfig(auth);\n\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n } catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, AuthErrorCode.INVALID_ORIGIN);\n}\n\nfunction matchDomain(expected: string): boolean {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (\n protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', '')\n );\n }\n\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n\n if (IP_ADDRESS_REGEX.test(expected)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return hostname === expected;\n }\n\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',\n 'i'\n );\n return re.test(hostname);\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 { AuthErrorCode } from '../../core/errors';\nimport { _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as js from '../load_js';\n\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\n\n/**\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfunction resetUnloadedGapiModules(): void {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(beacon.H)) {\n // Requested modules.\n beacon.H[hint].r = beacon.H[hint].r || [];\n // Loaded modules.\n beacon.H[hint].L = beacon.H[hint].L || [];\n // Set requested modules to a copy of the loaded modules.\n beacon.H[hint].r = [...beacon.H[hint].L];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\n\nfunction loadGapi(auth: AuthInternal): Promise {\n return new Promise((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe(): void {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n resetUnloadedGapiModules();\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n } else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\n } else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n const cbName = js._generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n } else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }\n };\n // Load GApi loader.\n return js\n ._loadJS(`${js._gapiScriptUrl()}?onload=${cbName}`)\n .catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\n\nlet cachedGApiLoader: Promise | null = null;\nexport function _loadGapi(auth: AuthInternal): Promise {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\nexport function _resetLoader(): void {\n cachedGApiLoader = null;\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 { SDK_VERSION } from '@firebase/app';\nimport { querystring } from '@firebase/util';\nimport { DefaultConfig } from '../../../internal';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _emulatorUrl } from '../../core/util/emulator';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as gapiLoader from './gapi';\n\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\n\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [DefaultConfig.API_HOST, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\n\nfunction getIframeUrl(auth: AuthInternal): string {\n const config = auth.config;\n _assert(config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n\n const params: Record = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\n\nexport async function _openIframe(\n auth: AuthInternal\n): Promise {\n const context = await gapiLoader._loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, AuthErrorCode.INTERNAL_ERROR);\n return context.open(\n {\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n },\n (iframe: gapi.iframes.Iframe) =>\n new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n\n const networkError = _createError(\n auth,\n AuthErrorCode.NETWORK_REQUEST_FAILED\n );\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve(): void {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\n }\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\n reject(networkError);\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\nimport { getUA } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport {\n _isChromeIOS,\n _isFirefox,\n _isIOSStandalone\n} from '../../core/util/browser';\nimport { AuthInternal } from '../../model/auth';\n\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\n\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\n\nconst FIREFOX_EMPTY_URL = 'http://localhost';\n\nexport class AuthPopup {\n associatedEvent: string | null = null;\n\n constructor(readonly window: Window | null) {}\n\n close(): void {\n if (this.window) {\n try {\n this.window.close();\n } catch (e) {}\n }\n }\n}\n\nexport function _open(\n auth: AuthInternal,\n url?: string,\n name?: string,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n): AuthPopup {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n\n const options: { [key: string]: string } = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\n\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n const ua = getUA().toLowerCase();\n\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options.scrollbars = 'yes';\n }\n\n const optionsString = Object.entries(options).reduce(\n (accum, [key, value]) => `${accum}${key}=${value},`,\n ''\n );\n\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, AuthErrorCode.POPUP_BLOCKED);\n\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n\n return new AuthPopup(newWin);\n}\n\nfunction openAsNewWindowIOS(url: string, target: string): void {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 1,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 1,\n null\n );\n el.dispatchEvent(click);\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 { SDK_VERSION } from '@firebase/app';\nimport { AuthProvider } from '../../model/public_types';\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { isEmpty, querystring } from '@firebase/util';\nimport { _emulatorUrl } from './emulator';\nimport { FederatedAuthProvider } from '../providers/federated';\nimport { BaseOAuthProvider } from '../providers/oauth';\n\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n\n/**\n * Fragment name for the App Check token that gets passed to the widget\n *\n * @internal\n */\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ntype WidgetParams = {\n apiKey: ApiKey;\n appName: AppName;\n authType: AuthEventType;\n redirectUrl?: string;\n v: string;\n providerId?: string;\n scopes?: string;\n customParameters?: string;\n eventId?: string;\n tid?: string;\n} & { [key: string]: string | undefined };\n\nexport async function _getRedirectUrl(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n redirectUrl?: string,\n eventId?: string,\n additionalParams?: Record\n): Promise {\n _assert(auth.config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n _assert(auth.config.apiKey, auth, AuthErrorCode.INVALID_API_KEY);\n\n const params: WidgetParams = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n\n // TODO: maybe set eid as endipointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n\n const paramsDict = params as Record;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n\n // Sets the App Check token to pass to the widget\n const appCheckToken = await auth._getAppCheckToken();\n const appCheckTokenFragment = appCheckToken\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\n : '';\n\n // Start at index 1 to skip the leading '&' in the query string\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(\n 1\n )}${appCheckTokenFragment}`;\n}\n\nfunction getHandlerBase({ config }: AuthInternal): string {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\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 { AuthProvider, PopupRedirectResolver } from '../model/public_types';\n\nimport { AuthEventManager } from '../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../core/errors';\nimport { _assert, debugAssert, _fail } from '../core/util/assert';\nimport { _generateEventId } from '../core/util/event_id';\nimport { _getCurrentUrl } from '../core/util/location';\nimport { _validateOrigin } from '../core/util/validate_origin';\nimport { AuthInternal } from '../model/auth';\nimport {\n AuthEventType,\n EventManager,\n GapiAuthEvent,\n GapiOutcome,\n PopupRedirectResolverInternal\n} from '../model/popup_redirect';\nimport { _setWindowLocation } from './auth_window';\nimport { _openIframe } from './iframe/iframe';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { _open, AuthPopup } from './util/popup';\nimport { _getRedirectResult } from './strategies/redirect';\nimport { _getRedirectUrl } from '../core/util/handler';\nimport { _isIOS, _isMobileBrowser, _isSafari } from '../core/util/browser';\nimport { _overrideRedirectResult } from '../core/strategies/redirect';\n\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\n\ninterface WebStorageSupportMessage extends gapi.iframes.Message {\n [index: number]: Record;\n}\n\ninterface ManagerOrPromise {\n manager?: EventManager;\n promise?: Promise;\n}\n\nclass BrowserPopupRedirectResolver implements PopupRedirectResolverInternal {\n private readonly eventManagers: Record = {};\n private readonly iframes: Record = {};\n private readonly originValidationPromises: Record> = {};\n\n readonly _redirectPersistence = browserSessionPersistence;\n\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise {\n debugAssert(\n this.eventManagers[auth._key()]?.manager,\n '_initialize() not called before _openPopup()'\n );\n\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n return _open(auth, url, _generateEventId());\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise {\n await this._originValidation(auth);\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n _setWindowLocation(url);\n return new Promise(() => {});\n }\n\n _initialize(auth: AuthInternal): Promise {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n } else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n\n return promise;\n }\n\n private async initAndGetManager(auth: AuthInternal): Promise {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register(\n 'authEvent',\n (iframeEvent: GapiAuthEvent | null) => {\n _assert(iframeEvent?.authEvent, auth, AuthErrorCode.INVALID_AUTH_EVENT);\n // TODO: Consider splitting redirect and popup events earlier on\n\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? GapiOutcome.ACK : GapiOutcome.ERROR };\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n\n _isIframeWebStorageSupported(\n auth: AuthInternal,\n cb: (supported: boolean) => unknown\n ): void {\n const iframe = this.iframes[auth._key()];\n iframe.send(\n WEB_STORAGE_SUPPORT_KEY,\n { type: WEB_STORAGE_SUPPORT_KEY },\n result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n }\n\n _originValidation(auth: AuthInternal): Promise {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n get _shouldInitProactively(): boolean {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n\n _completeRedirectFn = _getRedirectResult;\n\n _overrideRedirectResult = _overrideRedirectResult;\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @public\n */\nexport const browserPopupRedirectResolver: PopupRedirectResolver =\n BrowserPopupRedirectResolver;\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 */\nimport { FactorId, MultiFactorAssertion } from '../model/public_types';\nimport { debugFail } from '../core/util/assert';\nimport { MultiFactorSessionImpl, MultiFactorSessionType } from './mfa_session';\nimport { FinalizeMfaResponse } from '../api/authentication/mfa';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorAssertionImpl implements MultiFactorAssertion {\n protected constructor(readonly factorId: FactorId) {}\n\n _process(\n auth: AuthInternal,\n session: MultiFactorSessionImpl,\n displayName?: string | null\n ): Promise {\n switch (session.type) {\n case MultiFactorSessionType.ENROLL:\n return this._finalizeEnroll(auth, session.credential, displayName);\n case MultiFactorSessionType.SIGN_IN:\n return this._finalizeSignIn(auth, session.credential);\n default:\n return debugFail('unexpected MultiFactorSessionType');\n }\n }\n\n abstract _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise;\n abstract _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise;\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 */\nimport {\n FactorId,\n PhoneMultiFactorAssertion\n} from '../../../model/public_types';\n\nimport { MultiFactorAssertionImpl } from '../../../mfa/mfa_assertion';\nimport { AuthInternal } from '../../../model/auth';\nimport { finalizeEnrollPhoneMfa } from '../../../api/account_management/mfa';\nimport { PhoneAuthCredential } from '../../../core/credentials/phone';\nimport {\n finalizeSignInPhoneMfa,\n FinalizeMfaResponse\n} from '../../../api/authentication/mfa';\n\n/**\n * {@inheritdoc PhoneMultiFactorAssertion}\n *\n * @public\n */\nexport class PhoneMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements PhoneMultiFactorAssertion\n{\n private constructor(private readonly credential: PhoneAuthCredential) {\n super(FactorId.PHONE);\n }\n\n /** @internal */\n static _fromCredential(\n credential: PhoneAuthCredential\n ): PhoneMultiFactorAssertionImpl {\n return new PhoneMultiFactorAssertionImpl(credential);\n }\n\n /** @internal */\n _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise {\n return finalizeEnrollPhoneMfa(auth, {\n idToken,\n displayName,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise {\n return finalizeSignInPhoneMfa(auth, {\n mfaPendingCredential,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n}\n\n/**\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\n *\n * @public\n */\nexport class PhoneMultiFactorGenerator {\n private constructor() {}\n\n /**\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}\n */\n static assertion(credential: PhoneAuthCredential): PhoneMultiFactorAssertion {\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\n }\n\n /**\n * The identifier of the phone second factor: `phone`.\n */\n static FACTOR_ID = 'phone';\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 */\nimport {\n TotpMultiFactorAssertion,\n MultiFactorSession,\n FactorId\n} from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport {\n finalizeEnrollTotpMfa,\n startEnrollTotpMfa,\n StartTotpMfaEnrollmentResponse,\n TotpVerificationInfo\n} from '../../api/account_management/mfa';\nimport {\n FinalizeMfaResponse,\n finalizeSignInTotpMfa\n} from '../../api/authentication/mfa';\nimport { MultiFactorAssertionImpl } from '../../mfa/mfa_assertion';\nimport { MultiFactorSessionImpl } from '../mfa_session';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\n\n/**\n * Provider for generating a {@link TotpMultiFactorAssertion}.\n *\n * @public\n */\nexport class TotpMultiFactorGenerator {\n /**\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\n * the TOTP (time-based one-time password) second factor.\n * This assertion is used to complete enrollment in TOTP second factor.\n *\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\n * @param oneTimePassword One-time password from TOTP App.\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\n * {@link MultiFactorUser.enroll}.\n */\n static assertionForEnrollment(\n secret: TotpSecret,\n oneTimePassword: string\n ): TotpMultiFactorAssertion {\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\n }\n\n /**\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\n * This assertion is used to complete signIn with TOTP as the second factor.\n *\n * @param enrollmentId identifies the enrolled TOTP second factor.\n * @param oneTimePassword One-time password from TOTP App.\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}.\n */\n static assertionForSignIn(\n enrollmentId: string,\n oneTimePassword: string\n ): TotpMultiFactorAssertion {\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(\n enrollmentId,\n oneTimePassword\n );\n }\n\n /**\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\n * Used for generating a QR code URL or inputting into a TOTP app.\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\n *\n * @param session The {@link MultiFactorSession} that the user is part of.\n * @returns A promise to {@link TotpSecret}.\n */\n static async generateSecret(\n session: MultiFactorSession\n ): Promise {\n const mfaSession = session as MultiFactorSessionImpl;\n _assert(\n typeof mfaSession.user?.auth !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollTotpMfa(mfaSession.user.auth, {\n idToken: mfaSession.credential,\n totpEnrollmentInfo: {}\n });\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(\n response,\n mfaSession.user.auth\n );\n }\n\n /**\n * The identifier of the TOTP second factor: `totp`.\n */\n static FACTOR_ID: 'totp' = FactorId.TOTP;\n}\n\nexport class TotpMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements TotpMultiFactorAssertion\n{\n constructor(\n readonly otp: string,\n readonly enrollmentId?: string,\n readonly secret?: TotpSecret\n ) {\n super(FactorId.TOTP);\n }\n\n /** @internal */\n static _fromSecret(\n secret: TotpSecret,\n otp: string\n ): TotpMultiFactorAssertionImpl {\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\n }\n\n /** @internal */\n static _fromEnrollmentId(\n enrollmentId: string,\n otp: string\n ): TotpMultiFactorAssertionImpl {\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\n }\n\n /** @internal */\n async _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise {\n _assert(\n typeof this.secret !== 'undefined',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return finalizeEnrollTotpMfa(auth, {\n idToken,\n displayName,\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\n });\n }\n\n /** @internal */\n async _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise {\n _assert(\n this.enrollmentId !== undefined && this.otp !== undefined,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n const totpVerificationInfo = { verificationCode: this.otp };\n return finalizeSignInTotpMfa(auth, {\n mfaPendingCredential,\n mfaEnrollmentId: this.enrollmentId,\n totpVerificationInfo\n });\n }\n}\n\n/**\n * Provider for generating a {@link TotpMultiFactorAssertion}.\n *\n * Stores the shared secret key and other parameters to generate time-based OTPs.\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\n * @public\n */\nexport class TotpSecret {\n /**\n * Shared secret key/seed used for enrolling in TOTP MFA and generating OTPs.\n */\n readonly secretKey: string;\n /**\n * Hashing algorithm used.\n */\n readonly hashingAlgorithm: string;\n /**\n * Length of the one-time passwords to be generated.\n */\n readonly codeLength: number;\n /**\n * The interval (in seconds) when the OTP codes should change.\n */\n readonly codeIntervalSeconds: number;\n /**\n * The timestamp (UTC string) by which TOTP enrollment should be completed.\n */\n // This can be used by callers to show a countdown of when to enter OTP code by.\n readonly enrollmentCompletionDeadline: string;\n\n // The public members are declared outside the constructor so the docs can be generated.\n private constructor(\n secretKey: string,\n hashingAlgorithm: string,\n codeLength: number,\n codeIntervalSeconds: number,\n enrollmentCompletionDeadline: string,\n private readonly sessionInfo: string,\n private readonly auth: AuthInternal\n ) {\n this.secretKey = secretKey;\n this.hashingAlgorithm = hashingAlgorithm;\n this.codeLength = codeLength;\n this.codeIntervalSeconds = codeIntervalSeconds;\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\n }\n\n /** @internal */\n static _fromStartTotpMfaEnrollmentResponse(\n response: StartTotpMfaEnrollmentResponse,\n auth: AuthInternal\n ): TotpSecret {\n return new TotpSecret(\n response.totpSessionInfo.sharedSecretKey,\n response.totpSessionInfo.hashingAlgorithm,\n response.totpSessionInfo.verificationCodeLength,\n response.totpSessionInfo.periodSec,\n new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),\n response.totpSessionInfo.sessionInfo,\n auth\n );\n }\n\n /** @internal */\n _makeTotpVerificationInfo(otp: string): TotpVerificationInfo {\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\n }\n\n /**\n * Returns a QR code URL as described in\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\n * If the optional parameters are unspecified, an accountName of and issuer of are used.\n *\n * @param accountName the name of the account/app along with a user identifier.\n * @param issuer issuer of the TOTP (likely the app name).\n * @returns A QR code URL string.\n */\n generateQrCodeUrl(accountName?: string, issuer?: string): string {\n let useDefaults = false;\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\n useDefaults = true;\n }\n if (useDefaults) {\n if (_isEmptyString(accountName)) {\n accountName = this.auth.currentUser?.email || 'unknownuser';\n }\n if (_isEmptyString(issuer)) {\n issuer = this.auth.name;\n }\n }\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\n }\n}\n\n/** @internal */\nfunction _isEmptyString(input?: string): boolean {\n return typeof input === 'undefined' || input?.length === 0;\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 { Unsubscribe } from '@firebase/util';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\n\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\ninterface TokenListener {\n (tok: string | null): unknown;\n}\n\nexport class AuthInterop implements FirebaseAuthInternal {\n private readonly internalListeners: Map =\n new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n getUid(): string | null {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n\n async getToken(\n forceRefresh?: boolean\n ): Promise<{ accessToken: string } | null> {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n\n addAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(\n (user as UserInternal | null)?.stsTokenManager.accessToken || null\n );\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n\n removeAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n\n private assertAuthConfigured(): void {\n _assert(\n this.auth._initializationPromise,\n AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n );\n }\n\n private updateProactiveRefresh(): void {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n } else {\n this.auth._stopProactiveRefresh();\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 { _registerComponent, registerVersion } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\n\nimport { name, version } from '../../../package.json';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _getClientVersion, ClientPlatform } from '../util/version';\nimport { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';\nimport { AuthInterop } from './firebase_internal';\nimport { ConfigInternal } from '../../model/auth';\nimport { Dependencies } from '../../model/public_types';\nimport { _initializeAuthInstance } from './initialize';\n\nexport const enum _ComponentName {\n AUTH = 'auth',\n AUTH_INTERNAL = 'auth-internal'\n}\n\nfunction getVersionForPlatform(\n clientPlatform: ClientPlatform\n): string | undefined {\n switch (clientPlatform) {\n case ClientPlatform.NODE:\n return 'node';\n case ClientPlatform.REACT_NATIVE:\n return 'rn';\n case ClientPlatform.WORKER:\n return 'webworker';\n case ClientPlatform.CORDOVA:\n return 'cordova';\n case ClientPlatform.WEB_EXTENSION:\n return 'web-extension';\n default:\n return undefined;\n }\n}\n\n/** @internal */\nexport function registerAuth(clientPlatform: ClientPlatform): void {\n _registerComponent(\n new Component(\n _ComponentName.AUTH,\n (container, { options: deps }: { options?: Dependencies }) => {\n const app = container.getProvider('app').getImmediate()!;\n const heartbeatServiceProvider =\n container.getProvider<'heartbeat'>('heartbeat');\n const appCheckServiceProvider =\n container.getProvider<'app-check-internal'>('app-check-internal');\n const { apiKey, authDomain } = app.options;\n\n _assert(\n apiKey && !apiKey.includes(':'),\n AuthErrorCode.INVALID_API_KEY,\n { appName: app.name }\n );\n\n const config: ConfigInternal = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: DefaultConfig.API_HOST,\n tokenApiHost: DefaultConfig.TOKEN_API_HOST,\n apiScheme: DefaultConfig.API_SCHEME,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n\n const authInstance = new AuthImpl(\n app,\n heartbeatServiceProvider,\n appCheckServiceProvider,\n config\n );\n _initializeAuthInstance(authInstance, deps);\n\n return authInstance;\n },\n ComponentType.PUBLIC\n )\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback(\n (container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\n _ComponentName.AUTH_INTERNAL\n );\n authInternalProvider.initialize();\n }\n )\n );\n\n _registerComponent(\n new Component(\n _ComponentName.AUTH_INTERNAL,\n container => {\n const auth = _castAuth(\n container.getProvider(_ComponentName.AUTH).getImmediate()!\n );\n return (auth => new AuthInterop(auth))(auth);\n },\n ComponentType.PRIVATE\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\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, getApp, _getProvider } from '@firebase/app';\n\nimport {\n initializeAuth,\n beforeAuthStateChanged,\n onIdTokenChanged,\n connectAuthEmulator\n} from '..';\nimport { registerAuth } from '../core/auth/register';\nimport { ClientPlatform } from '../core/util/version';\nimport { browserLocalPersistence } from './persistence/local_storage';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { indexedDBLocalPersistence } from './persistence/indexed_db';\nimport { browserPopupRedirectResolver } from './popup_redirect';\nimport { Auth, User } from '../model/public_types';\nimport { getDefaultEmulatorHost, getExperimentalSetting } from '@firebase/util';\nimport { _setExternalJSProvider } from './load_js';\nimport { _createError } from '../core/util/assert';\nimport { AuthErrorCode } from '../core/errors';\n\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\nconst authIdTokenMaxAge =\n getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\n\nlet lastPostedIdToken: string | undefined | null = null;\n\nconst mintCookieFactory = (url: string) => async (user: User | null) => {\n const idTokenResult = user && (await user.getIdTokenResult());\n const idTokenAge =\n idTokenResult &&\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1_000;\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\n return;\n }\n // Specifically trip null => undefined when logged out, to delete any existing cookie\n const idToken = idTokenResult?.token;\n if (lastPostedIdToken === idToken) {\n return;\n }\n lastPostedIdToken = idToken;\n await fetch(url, {\n method: idToken ? 'POST' : 'DELETE',\n headers: idToken\n ? {\n 'Authorization': `Bearer ${idToken}`\n }\n : {}\n });\n};\n\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nexport function getAuth(app: FirebaseApp = getApp()): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n\n const auth = initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n\n const authTokenSyncPath = getExperimentalSetting('authTokenSyncURL');\n // Only do the Cookie exchange in a secure context\n if (\n authTokenSyncPath &&\n typeof isSecureContext === 'boolean' &&\n isSecureContext\n ) {\n // Don't allow urls (XSS possibility), only paths on the same domain\n const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);\n if (location.origin === authTokenSyncUrl.origin) {\n const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());\n beforeAuthStateChanged(auth, mintCookie, () =>\n mintCookie(auth.currentUser)\n );\n onIdTokenChanged(auth, user => mintCookie(user));\n }\n }\n\n const authEmulatorHost = getDefaultEmulatorHost('auth');\n if (authEmulatorHost) {\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\n }\n\n return auth;\n}\n\nfunction getScriptParentElement(): HTMLDocument | HTMLHeadElement {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n\n_setExternalJSProvider({\n loadJS(url: string): Promise {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(AuthErrorCode.INTERNAL_ERROR);\n error.customData = e as unknown as Record;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n },\n\n gapiScript: 'https://apis.google.com/js/api.js',\n recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',\n recaptchaEnterpriseScript:\n 'https://www.google.com/recaptcha/enterprise.js?render='\n});\n\nregisterAuth(ClientPlatform.BROWSER);\n", "/**\n * Authentication for data storage.\n */\nimport { init } from './firebaseService.js';\nimport { getAuth, GoogleAuthProvider, signInWithRedirect, onAuthStateChanged, signOut as fbSignOut } from 'firebase/auth';\n\nlet isAuthConfigured = false;\nlet currentUser = null;\nlet emitter = null;\n\n/**\n * Get current user.\n * @returns {User|null}\n */\nconst getUser = function () {\n return currentUser;\n};\n/**\n * Is current user logged in.\n * @returns {Boolean}\n */\nconst isAuthed = function () {\n return getUser() !== null;\n};\n/**\n * @param {Error} error Error usually from firebase\n * @param {String} method Method it happened it.\n */\nconst handleError = function (error, method) {\n const errorCode = error.code || '';\n const errorMessage = error.message || '';\n const message = `${method} auth error ${errorCode}: ${errorMessage}`;\n console.log(message);\n if (emitter) {\n emitter.trigger('error:display', message);\n }\n};\n\n/**\n * Trigger a signin (Google only).\n */\nconst signIn = async function () {\n if (!isAuthConfigured) {\n return;\n }\n try {\n const auth = getAuth();\n const provider = new GoogleAuthProvider();\n await signInWithRedirect(auth, provider);\n } catch (error) {\n handleError(error, 'signIn');\n }\n};\n/**\n *\n * @param {EventEmitter} em\n */\nconst monitorAuth = function (em) {\n // local reference to EventEmitter\n emitter = em;\n try {\n init();\n const auth = getAuth();\n isAuthConfigured = true;\n\n onAuthStateChanged(auth, user => {\n if (user != null) {\n console.log('Auth state changed to have a user.');\n currentUser = user;\n emitter.trigger('auth:signin');\n } else {\n console.log('Auth state changed to no user.');\n currentUser = null;\n emitter.trigger('auth:signout');\n }\n });\n\n emitter.trigger('auth:enabled');\n } catch (error) {\n handleError(error, 'monitorAuth');\n }\n};\n/**\n * Sign out.\n */\nconst signOut = function () {\n if (!isAuthConfigured) {\n return;\n }\n const auth = getAuth();\n fbSignOut(auth).then(() => {\n // Don't really need to do anything here\n // The observer catches the change the triggers any events.\n }).catch((error) => {\n handleError(error, 'signOut');\n });\n};\n\nexport {\n getUser,\n signIn,\n monitorAuth,\n signOut,\n isAuthed\n};\n", "import { getFirestore, collection, doc, getDoc, getDocs, setDoc, deleteDoc } from 'firebase/firestore';\nimport { getUser } from './AuthService.js';\n\n/**\n * Get Firebase userid if user is authed.\n * @returns {String|null}\n * @throws Error\n */\nconst getUserId = function () {\n const user = getUser();\n if (!user || !user.uid) {\n throw new Error('User not authed.');\n }\n return user.uid;\n};\n/**\n * Get document reference for a single character\n * @param {String} userId Firebase user id\n * @param {String} key Character key\n * @returns {DocumentReference}\n */\nconst getRefForKey = function (userId, key) {\n const db = getFirestore();\n return doc(db, `/users/${userId}/characters`, key);\n};\n/**\n * Get collection reference for user's characters.\n * @param {String} userId Firebase user id\n * @returns {CollectionReference}\n */\nconst getRefForCollection = function (userId) {\n const db = getFirestore();\n return collection(db, `/users/${userId}/characters`);\n};\n/**\n * Get single character.\n * @param {String} key Character key.\n * @returns {Object|null}\n * @throws Error\n */\nconst get = async function (key) {\n const userId = getUserId();\n if (!userId) {\n return null;\n }\n const docRef = getRefForKey(userId, key);\n try {\n const docSnap = await getDoc(docRef);\n if (docSnap.exists()) {\n return docSnap.data();\n } else {\n return null;\n }\n } catch (err) {\n console.log(`Database.get error: ${err}`);\n throw new Error(`Database.get error: ${err}`);\n }\n};\n/**\n * Save single character.\n * @param {String} key Character key.\n * @param {Object} char_obj Character data.\n * @returns {Boolean}\n * @throws Error\n */\nconst set = async function (key, char_obj) {\n const userId = getUserId();\n if (!userId) {\n return false;\n }\n const docRef = getRefForKey(userId, key);\n try {\n await setDoc(docRef, char_obj);\n } catch (err) {\n console.log(`Database.set error: ${err}`);\n throw new Error(`Database.set error: ${err}`);\n }\n return true;\n};\n/**\n * Get all characters for current user.\n * @returns {Object[]}\n * @throws Error\n */\nconst getAll = async function () {\n const userId = getUserId();\n if (!userId) {\n return [];\n }\n const char_obj = [];\n try {\n const querySnapshot = await getDocs(getRefForCollection(userId));\n querySnapshot.forEach((doc) => {\n char_obj.push(doc.data());\n });\n } catch (err) {\n console.log(`Database.getAll error: ${err}`);\n throw new Error(`Database.getAll error: ${err}`);\n }\n return char_obj;\n};\n/**\n * Remove a character from the remote.\n * @param {String} key\n * @returns {Boolean}\n * @throws Error\n */\nconst remove = async function (key) {\n const userId = getUserId();\n if (!userId) {\n return false;\n }\n const docRef = getRefForKey(userId, key);\n try {\n await deleteDoc(docRef);\n } catch (err) {\n console.log(`Database.remove error: ${err}`);\n throw new Error(`Database.remove error: ${err}`);\n }\n return true;\n};\n\nexport default {\n get,\n set,\n getAll,\n remove\n};\n", "// Simple tabs.\nclass Tabs {\n /**\n * @param {Element} tablist UL element for the tabs.\n */\n constructor (tablist) {\n this.tablist = tablist;\n this.tabs = [];\n this.panes = [];\n if (!tablist) {\n return;\n }\n this.tabs = tablist.querySelectorAll('a[role=tab]');\n this.panes = tablist.parentNode.querySelectorAll('section[role=tabpanel]');\n Array.from(this.tabs).forEach((tab) => {\n tab.addEventListener('click', this.changeTab.bind(this));\n });\n }\n /**\n * Switch to a specific pane.\n * @param {String} paneId Html id of pane to switch to.\n */\n switchToPane (paneId) {\n let newIndex = -1;\n if (paneId) {\n newIndex = Array.prototype.findIndex.call(this.panes, (el) => {\n return el.id === paneId;\n });\n } else {\n // next one.\n const oldTab = this.tablist.querySelector('[aria-selected=true]');\n const oldIndex = Array.prototype.indexOf.call(this.tabs, oldTab);\n newIndex = oldIndex + 1;\n if (newIndex >= this.tabs.length) {\n newIndex = 0;\n }\n }\n if (newIndex !== -1) {\n this.tabs[newIndex].click();\n }\n }\n /**\n * Handler: Change tabs on tab click.\n * @param {Event} ev Click event.\n */\n changeTab (ev) {\n ev.preventDefault();\n const oldTab = this.tablist.querySelector('[aria-selected=true]');\n if (!oldTab) {\n return;\n }\n const oldIndex = Array.prototype.indexOf.call(this.tabs, oldTab);\n const newTab = ev.currentTarget;\n const newIndex = Array.prototype.indexOf.call(this.tabs, newTab);\n if (oldIndex === newIndex) {\n return;\n }\n oldTab.setAttribute('aria-selected', false);\n newTab.setAttribute('aria-selected', true);\n const oldPane = this.panes[oldIndex];\n if (oldPane) {\n oldPane.hidden = true;\n }\n const newPane = this.panes[newIndex];\n if (!newPane) {\n return;\n }\n newPane.hidden = false;\n // Focus on first field.\n newPane.querySelector('[data-name]').focus();\n }\n}\n\nexport default Tabs;\n", "/* eslint-disable no-case-declarations */\nimport Tabs from './Tabs.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n

    \n

    \n
    \n`;\nclass SheetView extends HTMLElement {\n /**\n * @param {EventEmitter} emitter\n * @param {Node} templateNode Cloned node from child element.\n */\n constructor ({\n emitter = null,\n templateNode = null\n }) {\n super();\n this.emitter = emitter;\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n // Append child node template to header.\n if (templateNode) {\n this.shadowRoot.appendChild(templateNode);\n }\n // Selector hook so we can always find regardless of child class.\n this.dataset.sheetview = 'true';\n }\n\n connectedCallback () {\n this.mainTabs = new Tabs(this.shadowRoot.querySelector('ul[role=tablist]'));\n // Listen for events emitted from the components\n this.shadowRoot.addEventListener('fieldChange', this._handleFieldChange.bind(this));\n Array.from(this.shadowRoot.querySelectorAll('input[type=number]')).forEach((el) => {\n el.addEventListener('change', this._numberInputChange.bind(this));\n });\n\n this.emitter.on('tab:switch', this.switchToPane, this);\n }\n\n disconnectedCallback () {\n // Listen for events emitted from the components\n this.shadowRoot.removeEventListener('fieldChange', this._handleFieldChange.bind(this));\n Array.from(this.shadowRoot.querySelectorAll('input[type=number]')).forEach((el) => {\n el.removeEventListener('change', this._numberInputChange.bind(this));\n });\n\n this.emitter.off('tab:switch', this.switchToPane, this);\n\n // Remove footer links.\n const nav = document.querySelector('footer-nav');\n nav.removeLinks();\n }\n /**\n * Override in child to check correct class is set.\n * @param {Character} character\n */\n _validateCharacter (character) {\n throw new Error('Invalid character type for this view.');\n }\n /**\n * @param {Character}\n */\n set character (character) {\n this._validateCharacter(character);\n this.cur_character = character;\n this.emitter.trigger('character:set');\n // render character.\n this.renderCharacter();\n }\n /**\n * @returns {Character}\n */\n get character () {\n return this.cur_character;\n }\n /**\n * Change the main tab pane.\n * @param {String} targetPane\n */\n switchToPane (targetPane) {\n if (!this.mainTabs) {\n return;\n }\n this.mainTabs.switchToPane(targetPane);\n }\n /**\n * Handle setting custom fields.\n * @param {HTMLElement} el Editable element of some type\n * @param {String} fieldName Character field\n * @param {String} subFieldName Character Subfield\n * @param {Any} charValue Character's value for field/subfield.\n * @returns {Boolean}\n */\n _renderCustomFields (el, fieldName, subFieldName, charValue) {\n return false;\n }\n /**\n * Any actions to perform after rendering all the fields.\n */\n _renderCustomPost () {\n }\n /**\n * Take character data and fill it into the page\n */\n renderCharacter () {\n if (this.cur_character === null) {\n return;\n }\n\n this.shadowRoot.querySelector('[data-name=\"charname\"]').content = this.cur_character.charname;\n\n const fields = Array.from(this.shadowRoot.querySelectorAll('*[data-name]'));\n fields.forEach((el) => {\n const f = el.getAttribute('data-name');\n if (typeof this.cur_character[f] === 'undefined') {\n return;\n }\n const subf = el.getAttribute('data-subfield');\n const charValue = (subf) ? this.cur_character[f][subf] : this.cur_character[f];\n switch (el.tagName) {\n case 'INPUT':\n case 'TEXTAREA':\n case 'SELECT':\n // Make sure numbers default to 0.\n // this is especially relevant for spell slots.\n if (el.getAttribute('type') === 'number') {\n el.value = charValue || 0;\n } else {\n el.value = charValue || '';\n }\n // For spell slot input we need to trigger the display or not of spells\n const event = new Event('change');\n el.dispatchEvent(event);\n break;\n case 'SIMPLE-LIST':\n el.clear();\n const listItems = charValue || [];\n if (listItems.length > 0) {\n listItems.forEach((item) => {\n if (item.length === 0) {\n return;\n }\n el.addItem(item);\n });\n }\n el.addItem();\n break;\n case 'NOTE-LIST':\n el.clear();\n const noteItems = charValue || [];\n if (noteItems.length > 0) {\n noteItems.forEach((item) => {\n if (item.length === 0) {\n return;\n }\n el.addItem(item);\n });\n }\n el.addItem();\n break;\n case 'TABLE-EDITABLE':\n el.clear();\n const rowItems = charValue || [];\n if (rowItems.length > 0) {\n rowItems.forEach((item) => {\n if (item.length === 0) {\n return;\n }\n el.addRow(item);\n });\n }\n el.addRow();\n break;\n case 'FIELD-EDITABLE':\n el.content = charValue || '';\n break;\n\n default:\n // Custom fields by character type\n if (!this._renderCustomFields(\n el,\n f,\n subf,\n charValue\n )) {\n // Try for basic content editable.\n if (el.getAttribute('content-editable') === 'true') {\n el.innerHTML = charValue || '';\n }\n }\n }\n });\n\n this._renderCustomPost();\n\n this.emitter.trigger('dialog:save:hide');\n }\n /**\n * Trigger the event to show there are unsaved changes.\n */\n _showUnsavedDialog () {\n this.emitter.trigger('dialog:save:show');\n }\n /**\n * Compare two properties to see if they are different\n * For objects/arrays we need to account for them being different objects\n * that have the same properties and values.\n * @param {String|Number|Array|Object|Boolean} valold Existing property value\n * @param {String|Number|Array|Object|Boolean} valnew New property value\n * @return {Boolean}\n */\n _sameValues (valold, valnew) {\n // for efficiency we could do typeof checks\n // and only use JSON for objects...\n return JSON.stringify(valold) === JSON.stringify(valnew);\n }\n /**\n * Handle field change for those that need special handling.\n * in child\n * @param {CustomEvent} ev\n * @param {String} field Field name\n * @param {String} subfield Subfield name\n * @returns {Boolean} On true return from the parent handler.\n */\n _customFieldChange (ev, field, subfield) {\n return false;\n }\n /**\n * When a field is changed in the UI.\n * Update the character and trigger save dialog\n * Only if the value is actually different.\n * @param {CustomEvent} ev\n */\n _handleFieldChange (ev) {\n const field = ev.detail.field || '';\n const subfield = ev.detail.subfield || '';\n if (!field) {\n return;\n }\n const cur_character = this.cur_character;\n if (typeof cur_character[field] === 'undefined') {\n return;\n }\n\n if (this._customFieldChange(ev, field, subfield)) {\n return;\n }\n\n const newValue = ev.detail.value;\n if (subfield) {\n if (typeof cur_character[field] !== 'object' || Array.isArray(cur_character[field])) {\n return;\n }\n const currentVal = cur_character[field][subfield];\n if (!this._sameValues(currentVal, newValue)) {\n cur_character[field][subfield] = ev.detail.value;\n this._showUnsavedDialog();\n }\n return;\n }\n const currentVal = cur_character[field];\n if (!this._sameValues(currentVal, newValue)) {\n cur_character[field] = newValue;\n this._showUnsavedDialog();\n }\n }\n\n _customNumberInputChange () {\n }\n /**\n * Handle input[name=number] changes.\n * @param {Event} ev\n */\n _numberInputChange (ev) {\n const field = ev.target.dataset.name;\n const subfield = ev.target.dataset.subfield;\n if (typeof this.cur_character[field][subfield] === 'undefined') {\n return;\n }\n const newValue = parseInt(ev.target.value, 10);\n this.cur_character[field][subfield] = newValue;\n this.emitter.trigger('dialog:save:show');\n\n this._customNumberInputChange(ev);\n }\n\n navigateTo (id) {\n const el = this.shadowRoot.querySelector(id);\n if (el) {\n el.scrollIntoView();\n // Focus only works sometimes depending on the element...\n // @todo fix that.\n el.focus();\n }\n }\n}\n\nif (!window.customElements.get('sheet-view')) {\n window.customElements.define('sheet-view', SheetView);\n}\n\nexport default SheetView;\n", "/* eslint-disable no-case-declarations */\nimport Character5e from '../models/Character5e.js';\nimport Weapon from '../models/Weapon.js';\nimport SheetView from './SheetView.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n
    \n
    \n
    \n
    \n
    Class
    \n
    \n
    \n
    Race
    \n
    \n
    \n
    Background
    \n
    \n
    \n
    Alignment
    \n
    \n
    \n
    Level
    \n
    \n
    \n
    Experience
    \n
    \n
    \n
    Proficiency Bonus
    \n
    \n
    \n
    Inspiration
    \n
    \n
    \n
    Speed
    \n
    \n
    \n
    Hit Dice
    \n
    \n / \n
    \n
    \n
    \n
    Armor Class
    \n
    \n
    \n
    Hit Points
    \n
    \n / \n
    \n
    \n
    \n
    Death Save Success/Fail
    \n
    \n \n /\n \n
    \n
    \n
    \n
    Class Points
    \n
    \n / \n
    \n
    \n
    \n
    \n\n
    \n

    Attributes

    \n
    \n Str\n Dex\n Con\n Int\n Wis\n Cha\n
    \n\n

    Skills

    \n
    \n Acrobatics (Dex)\n Animal Handling (Wis)\n Arcana (Int)\n Athletics (Str)\n Deception (Cha)\n History (Int)\n Insight (Wis)\n Intimidation (Cha)\n Investigation (Int)\n Medicine (Wis)\n Nature (Int)\n Perception (Wis)\n Performance (Cha)\n Persuasion (Cha)\n Religion (Int)\n Sleight of Hand (Dex)\n Stealth (Dex)\n Survival (Wis)\n
    \n
    \n\n
    \n

    Dice Roller

    \n \n \n \n \n \n \n \n \n

    Weapons & Attacks

    \n \n\n

    Features & Traits

    \n \n\n

    Other Proficiencies

    \n \n\n

    Equipment

    \n \n\n
    \n
    \n
    CP
    \n
    SP
    \n
    \n
    \n
    GP
    \n
    PP
    \n
    \n
    \n
    \n\n
    \n

    Spells

    \n\n
    \n
    \n
    Spell Ability
    \n
    \n
    \n
    Spell Save DC
    \n
    \n
    \n
    Spell Attack Bonus
    \n
    \n
    \n\n \n

    Spell Slots

    \n\n
    \n
    \n
    1st
    \n
    \n \n /\n \n
    \n
    2nd
    \n
    \n \n /\n \n
    \n
    \n
    \n
    3rd
    \n
    \n \n /\n \n
    \n
    4th
    \n
    \n \n /\n \n
    \n
    \n
    \n
    5th
    \n
    \n \n /\n \n
    \n
    6th
    \n
    \n \n /\n \n
    \n
    \n
    \n
    7th
    \n
    \n \n /\n \n
    \n
    8th
    \n
    \n \n /\n \n
    \n
    \n
    \n
    9th
    \n
    \n \n /\n \n
    \n
    \n
    \n
    \n\n
    \n

    Cantrips

    \n \n
    \n \n \n \n \n \n \n \n \n \n
    \n\n\n`;\nclass Character5eSheet extends SheetView {\n /**\n * @param {EventEmitter} emitter\n */\n constructor ({\n emitter\n }) {\n super({\n emitter,\n templateNode: template.content.cloneNode(true)\n });\n this.spellButtons = [];\n }\n\n connectedCallback () {\n super.connectedCallback();\n // Listen for events emitted from the components\n this.shadowRoot.addEventListener('attributeChange', this._handleAttributeChange.bind(this));\n this.shadowRoot.addEventListener('saveChange', this._handleSaveChange.bind(this));\n\n this.emitter.on('character:skill:update', this._updateSkillMod, this);\n this.emitter.on('character:proficiency:update', this._updateProficiency, this);\n this.emitter.on('character:attribute:update', this._updateAttributeMods, this);\n this.emitter.on('character:save:update', this._updateSaveMods, this);\n this.emitter.on('character:set', this._addSpellButtonEvents, this);\n this.emitter.on('character:update:spells', this._updateSpellList, this);\n\n // Set footer links.\n const nav = document.querySelector('footer-nav');\n if (nav) {\n nav.setLinks([\n { label: 'Attributes', tab: 'pane-stats', href: '#page-attributes' },\n { label: 'Skills', tab: 'pane-stats', href: '#page-skills' },\n { label: 'Spells', tab: 'pane-stats', href: '#page-spells' },\n { label: 'Notes', tab: 'pane-notes', href: '#page-notes_adv' }\n ]);\n }\n }\n\n disconnectedCallback () {\n super.disconnectedCallback();\n // Listen for events emitted from the components\n this.shadowRoot.removeEventListener('attributeChange', this._handleAttributeChange.bind(this));\n this.shadowRoot.removeEventListener('saveChange', this._handleSaveChange.bind(this));\n\n this.emitter.off('character:skill:update', this._updateSkillMod, this);\n this.emitter.off('character:proficiency:update', this._updateProficiency, this);\n this.emitter.off('character:attribute:update', this._updateAttributeMods, this);\n this.emitter.off('character:save:update', this._updateSaveMods, this);\n this.emitter.off('character:set', this._addSpellButtonEvents, this);\n this.emitter.off('character:update:spells', this._updateSpellList, this);\n }\n\n _updateSpellList () {\n const fields = this.shadowRoot.querySelectorAll('[data-name=\"spells\"]');\n\n fields.forEach((el) => {\n const f = el.dataset.name || '';\n \n if (typeof this.cur_character[f] === 'undefined' || f === '') {\n return;\n };\n\n const subf = el.dataset.subfield || '';\n const charValue = (subf !== '') ? this.cur_character[f][subf] : this.cur_character[f];\n // spells added the the current character\n const listItems = charValue || [];\n \n el.clear();\n\n listItems.forEach((item) => {\n if (!item) {\n return;\n };\n el.addItem(item);\n });\n\n if (listItems.length === 0) el.addItem();\n });\n };\n\n /**\n * @param {Character5e}\n */\n _validateCharacter (character) {\n if (!(character instanceof Character5e)) {\n throw new Error('Invalid character type for this view.');\n }\n }\n\n _renderCustomFields (el, fieldName, subFieldName, charValue) {\n switch (el.tagName) {\n case 'SKILL-LISTING':\n el.skillValue = charValue || 0;\n el.skillMod = this.cur_character.getSkillMod(subFieldName);\n return true;\n case 'ATTR-LISTING':\n el.attributeScore = charValue || 10;\n el.attributeMod = this.cur_character.attributeMod(fieldName);\n el.saveProficiency = this.cur_character.saves[fieldName];\n el.saveMod = this.cur_character.saveMod(fieldName);\n return true;\n }\n return false;\n }\n\n _renderCustomPost () {\n this.shadowRoot.querySelector('[data-name=\"proficiency\"]').innerHTML = this.cur_character.proficiency;\n }\n\n _customFieldChange (ev, field, subfield) {\n if (field === 'skills') {\n const currentVal = this.character.getSkill(subfield);\n if (!this._sameValues(currentVal, ev.detail.value)) {\n this.character.setSkill(subfield, ev.detail.value);\n this._showUnsavedDialog();\n }\n return true;\n }\n if (field === 'weapons') {\n const currentVal = this.character[field];\n const newValue = ev.detail.value.map((object) => {\n return new Weapon(object);\n });\n if (!this._sameValues(currentVal, newValue)) {\n this.character[field] = newValue;\n this._showUnsavedDialog();\n }\n return true;\n }\n }\n /**\n * Update a skill's modifier in the UI.\n * @param {String} skill\n * @param {String} modifier\n */\n _updateSkillMod (skill, modifier) {\n const el = this.shadowRoot.querySelector(`skill-listing[data-subfield=\"${skill}\"]`);\n if (!el) {\n return;\n }\n el.skillMod = modifier;\n }\n /**\n * Update the proficiency modifier in the UI.\n */\n _updateProficiency () {\n const proficiency = this.cur_character.proficiency;\n this.shadowRoot.querySelector('[data-name=\"proficiency\"]').innerHTML = proficiency;\n\n Array.from(this.shadowRoot.querySelectorAll('skill-listing')).forEach((el) => {\n const skill = el.skillName;\n el.skillMod = this.cur_character.getSkillMod(skill);\n });\n\n Array.from(this.shadowRoot.querySelectorAll('attr-listing')).forEach((el) => {\n const attr = el.attributeName;\n el.saveMod = this.cur_character.saveMod(attr);\n });\n }\n /**\n * Update an attribute's modifier in the UI.\n * @param {String} attribute\n */\n _updateAttributeMods (attribute) {\n const el = this.shadowRoot.querySelector(`attr-listing[data-name=${attribute}]`);\n if (!el) {\n return;\n }\n el.attributeMod = this.cur_character.attributeMod(attribute);\n el.saveMod = this.cur_character.saveMod(attribute);\n }\n /**\n * Update a save modifier in the UI.\n * @param {String} attribute\n */\n _updateSaveMods (attribute) {\n const el = this.shadowRoot.querySelector(`attr-listing[data-name=${attribute}]`);\n if (!el) {\n return;\n }\n el.saveMod = this.cur_character.saveMod(attribute);\n }\n /**\n * Handle input[name=number] changes.\n * @param {Event} ev\n */\n _customNumberInputChange (ev) {\n const field = ev.target.dataset.name;\n const subfield = ev.target.dataset.subfield;\n const newValue = parseInt(ev.target.value, 10);\n if (field === 'spell_slots') {\n const spellList = this.shadowRoot.querySelector(`[data-name=\"spells\"][data-subfield=\"${subfield}\"]`);\n if (!newValue) {\n // this covers 0 and NaN\n spellList.parentNode.hidden = true;\n } else {\n spellList.parentNode.hidden = false;\n }\n }\n }\n /**\n * When an attribute is changed in the UI.\n * @param {CustomEvent} ev\n */\n _handleAttributeChange (ev) {\n const field = ev.detail.field || '';\n if (!field) {\n return;\n }\n this.cur_character.setAttribute(field, ev.detail.value);\n this._showUnsavedDialog();\n }\n /**\n * When a save is (un)checked in the UI.\n * @param {CustomEvent} ev\n */\n _handleSaveChange (ev) {\n const field = ev.detail.field || '';\n if (!field) {\n return;\n }\n this.cur_character.setSaveProficiency(field, ev.detail.value);\n this._showUnsavedDialog();\n }\n}\n\nif (!window.customElements.get('sheet-view-5e')) {\n window.customElements.define('sheet-view-5e', Character5eSheet);\n}\n\nexport default Character5eSheet;\n", "import CharacterVagabonds from '../models/CharacterVagabonds.js';\nimport SheetView from './SheetView';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n\n
    \n
    \n
    \n
    \n
    Conflict Approach
    \n
    \n
    \n
    Goal
    \n
    \n
    \n
    Gimmick
    \n
    \n
    \n
    Background
    \n
    \n
    \n
    Foreground
    \n
    \n
    \n
    Weakness
    \n
    \n
    \n
    Core Flaw
    \n
    \n
    \n
    Level
    \n
    \n
    \n
    Experience
    \n
    \n
    \n
    Initiative
    \n
    \n
    \n
    Armor
    \n
    \n
    \n
    Hit Points
    \n
    \n / \n
    \n
    \n
    \n
    Injuries
    \n
    \n \n
    \n
    \n
    \n
    Coins
    \n
    \n
    \n
    Level Traits/Tags
    \n
    \n \n
    \n
    \n
    \n
    Lineage
    \n
    \n
    \n
    \n\n
    \n

    Dice Roller

    \n \n \n \n

    Techniques

    \n \n\n

    Inventory

    \n \n
    \n
    \n\n\n`;\n\nclass CharacterVagabondsSheet extends SheetView {\n /**\n * @param {EventEmitter} emitter\n */\n constructor ({\n emitter\n }) {\n super({\n emitter,\n templateNode: template.content.cloneNode(true)\n });\n }\n\n connectedCallback () {\n super.connectedCallback();\n\n // Set footer links.\n const nav = document.querySelector('footer-nav');\n if (nav) {\n nav.setLinks([\n { label: 'Attributes', tab: 'pane-stats', href: '#page-attributes' },\n { label: 'Notes', tab: 'pane-notes', href: '#page-notes' }\n\n ]);\n }\n }\n\n disconnectedCallback () {\n super.disconnectedCallback();\n }\n /**\n * Override in child to check correct class is set.\n * @param {CharacterVagabonds} character\n */\n _validateCharacter (character) {\n if (!(character instanceof CharacterVagabonds)) {\n throw new Error('Invalid character type for this view.');\n }\n }\n}\n\nif (!window.customElements.get('sheet-view-vagabonds')) {\n window.customElements.define('sheet-view-vagabonds', CharacterVagabondsSheet);\n}\n\nexport default CharacterVagabondsSheet;\n", "{\n \"name\": \"character-sheet-app\",\n \"version\": \"4.5.2\",\n \"description\": \"Online character sheet for Tabletop Role-Playing Games\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/derikb/character-sheet-app.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/derikb/character-sheet-app/issues\"\n },\n \"homepage\": \"https://github.com/derikb/character-sheet-app#readme\",\n \"keywords\": [\n \"d&d\",\n \"rpg\",\n \"ttrpg\",\n \"character sheet\"\n ],\n \"author\": \"Derik A Badman\",\n \"license\": \"GPL-3.0\",\n \"dependencies\": {\n \"firebase\": \"^10.1.0\",\n \"rpg-table-randomizer\": \"^1.3.2\"\n },\n \"devDependencies\": {\n \"@stylistic/eslint-plugin-js\": \"^2.1.0\",\n \"commit-and-tag-version\": \"^12.0.0\",\n \"esbuild\": \"^0.21\",\n \"eslint\": \"^9.4.0\",\n \"globals\": \"^15.3.0\",\n \"normalize.css\": \"^8.0.1\"\n },\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"start\": \"esbuild --serve=8080 --servedir=./dist ./src/styles.css ./src/index.js ./src/service_worker.js --outdir=./dist --loader:.svg=dataurl --loader:.html=file --bundle\",\n \"build\": \"esbuild ./src/styles.css ./src/index.js ./src/service_worker.js --outdir=./dist --loader:.svg=dataurl --loader:.html=file --minify --sourcemap --bundle\",\n \"release\": \"commit-and-tag-version -a\",\n \"eslint\": \"eslint ./src\"\n },\n \"commit-and-tag-version\": {\n \"scripts\": {\n \"postbump\": \"npm run build && git add ./dist/service_worker.js ./dist/service_worker.js.map ./dist/index.js ./dist/index.js.map ./dist/styles.css ./dist/styles.css.map\"\n },\n \"bumpFiles\": [\n \"package.json\",\n \"package-lock.json\"\n ]\n }\n}\n", "/**\n * Service for retrieving, saving, deleting characters.\n * For now LocalStorage only, but potentially adaptable to different stores.\n */\nimport Character from '../models/Character.js';\nimport Character5e from '../models/Character5e.js';\nimport CharacterVagabonds from '../models/CharacterVagabonds.js';\nimport Storage from './Storage.js';\nimport Database from './Database.js';\nimport { isAuthed } from './AuthService.js';\nimport Character5eSheet from '../views/Character5eSheet.js';\nimport CharacterVagabondsSheet from '../views/CharacterVagabondsSheet.js';\nimport SheetView from '../views/SheetView.js';\nimport { version } from '../../package.json';\n\n/**\n * Compare character version against another version.\n * For any future version based data manipulation.\n *\n * @param {String} charVersion Character semver version number.\n * @param {String} compareVersion Another semver version to compare against.\n * @returns {Boolean} True if charVersion is higher/newert than the compare version.\n */\nconst isCharVersionNewer = function (charVersion, compareVersion) {\n // bacwards compatible\n if (charVersion === '') {\n return false;\n }\n return charVersion.localeCompare(compareVersion, undefined, { numeric: true }) > 0;\n};\n\n/**\n * Currently loaded character data is here\n * @prop {Character|null}\n */\nlet cur_character = null;\n/**\n * @prop {String} appVersion Current app version.\n */\nconst appVersion = version;\n/**\n * Return UTC datetime string for right now\n * @return {String}\n */\nconst currentTimestamp = function () {\n const d = new Date();\n return d.toUTCString();\n};\n/**\n * Get a unique 7 character key to use for a new character.\n * @returns {String}\n */\nconst generateCharacterKey = function () {\n let key = (`${Math.random().toString(36)}00000000000000000`).slice(2, 9);\n while (getCharacter(key) !== null) {\n key = (`${Math.random().toString(36)}00000000000000000`).slice(2, 9);\n }\n return key;\n};\n\n/**\n * Options for games characters can be created for.\n * @todo probably should have a constant file for these.\n * @returns {String[]}\n */\nconst getGameOptions = function () {\n return [\n 'Character5e',\n 'CharacterVagabonds'\n ];\n};\n\n/**\n * Get a Character of appropriate class.\n * @param {String} type className for model.\n * @param {Object} obj Character data.\n * @returns {Character}\n */\nconst characterFactory = function (type, obj) {\n switch (type) {\n // Backwards compatible\n // and default\n case undefined:\n case '':\n case 'Character5e':\n return new Character5e(obj);\n case 'CharacterVagabonds':\n return new CharacterVagabonds(obj);\n default:\n return new Character(obj);\n }\n};\n\n/**\n * Return a new character for a key.\n * @param {String} key\n * @param {String} type Model className\n * @returns {Character}\n */\nconst newCharacter = function (key, type = 'Character5e') {\n return characterFactory(type, { key });\n};\n/**\n * Get a single character model.\n * @param {String} key Character's key.\n * @returns {Character|null}\n */\nconst getCharacter = function (key) {\n if (!key) {\n return null;\n }\n const char_obj = Storage.get(key);\n if (!char_obj || !char_obj.key) {\n return null;\n }\n return characterFactory(char_obj.className, char_obj);\n};\n/**\n * Get a single character model.\n * @param {String} key Character's key.\n * @returns {Character|null}\n * @throws Error\n */\nconst getCharacterRemote = async function (key) {\n if (!key) {\n return null;\n }\n const char_obj = await Database.get(key);\n if (!char_obj || !char_obj.key) {\n return null;\n }\n return characterFactory(char_obj.className, char_obj);\n};\n/**\n * Save a single character.\n * @param {Character} character\n * @returns {Boolean}\n */\nconst saveCharacter = function (character) {\n // Update saved timestamp\n character.updated = currentTimestamp();\n character.version = appVersion;\n return Storage.set(character.key, character);\n};\n/**\n * Save a single character to the remote.\n * @param {Character} character\n * @returns {Boolean}\n * @throws Error\n */\nconst saveCharacterRemote = async function (character) {\n // Update saved timestamp\n // character.updated = currentTimestamp();\n return await Database.set(character.key, character.toJSON());\n};\n/**\n * Remove a character from the store.\n * @param {String} key\n */\nconst removeCharacterLocal = function (key) {\n Storage.remove(key);\n};\n/**\n * Remove a character from the remote.\n * @param {String} key\n * @throws Error\n */\nconst removeCharacterRemote = async function (key) {\n return Database.remove(key);\n};\n/**\n * Get all characters saved locally.\n * @returns {Character[]}\n */\nconst getAllCharactersLocal = function () {\n const characters = [];\n Storage.getAll().forEach((char_obj) => {\n characters.push(\n characterFactory(char_obj.className, char_obj)\n );\n });\n return characters;\n};\n/**\n * Get all characters saved to the remote database.\n * @returns {Map} entries are Character keyed to the key property.\n * @throws Error\n */\nconst getAllCharactersRemote = async function () {\n const characters = new Map();\n if (!isAuthed()) {\n return [];\n }\n const char_objects = await Database.getAll();\n char_objects.forEach((char_obj) => {\n const char = characterFactory(char_obj.className, char_obj);\n characters.set(char.key, char);\n });\n return characters;\n};\n/**\n * Import/save a character from an obj and return the model.\n * @param {Object} char_obj Character data from backup (we hope).\n * @returns {Character}\n * @throws {Error}\n */\nconst importCharacter = function (char_obj) {\n if (typeof char_obj !== 'object' || !char_obj.key) {\n throw new Error(`Data appears to be invalid. Try removing any text that isn't part of the backup (i.e. email introduction).`);\n }\n const newCharacter = characterFactory(char_obj.className, char_obj);\n // do we have this char key already\n const existingCharacter = getCharacter(char_obj.key);\n if (existingCharacter && existingCharacter.charname !== '' && existingCharacter.charname !== newCharacter.charname) {\n // existing key but different name\n if (!newCharacter.key_prev) {\n newCharacter.key_prev = newCharacter.key;\n newCharacter.key = generateCharacterKey();\n } else {\n const temp_key = newCharacter.key_prev;\n newCharacter.key_prev = newCharacter.key;\n newCharacter.key = temp_key;\n }\n }\n saveCharacter(newCharacter);\n return newCharacter;\n};\n/**\n * Set prefix for LocalStorage keys.\n * @param {String} prefix\n */\nconst setLocalStoragePrefix = function (prefix) {\n if (!prefix) {\n throw Error('LocalStorage prefix is empty.');\n }\n Storage.setPrefix(prefix);\n};\n\n/**\n * Set current character based on key.\n * Returns null if key is not locally set.\n * @param {String} key\n * @param {String} type Type of character to create.\n * @param {Boolean} createOnEmpty Create new character if the key isn't found.\n * @returns {Character|null}\n */\nconst setCurrentCharacter = function (key, type, createOnEmpty = false) {\n let char = getCharacter(key);\n if (!char) {\n if (!createOnEmpty) {\n return null;\n }\n char = newCharacter(key, type);\n }\n cur_character = char;\n return cur_character;\n};\n\n/**\n * Get character currently displayed.\n * @returns {Character|null}\n */\nconst getCurrentCharacter = function () {\n return cur_character;\n};\n/**\n * Just the key for the current character.\n * @returns {String}\n */\nconst getCurrentCharacterKey = function () {\n return !cur_character ? '' : cur_character.key;\n};\n/**\n * Save the current character locally.\n */\nconst saveCurrentCharacter = function () {\n if (!cur_character) {\n throw new Error('No character is set.');\n }\n if (cur_character.charname === '') {\n throw new Error('Your character must have name to save!');\n }\n saveCharacter(cur_character);\n};\n/**\n * Get the right view for a character\n * @param {Character} character\n * @param {EventEmitter} emitter\n * @returns {SheetView}\n */\nconst getSheetView = function (character, emitter) {\n let view = null;\n switch (character.className) {\n // Backwards compatible\n case undefined:\n case 'Character5e':\n view = new Character5eSheet({ emitter });\n break;\n case 'CharacterVagabonds':\n view = new CharacterVagabondsSheet({ emitter });\n break;\n default:\n view = new SheetView({ emitter });\n break;\n }\n return view;\n};\n\nexport {\n getGameOptions,\n generateCharacterKey,\n getCharacter,\n getCharacterRemote,\n saveCharacter,\n saveCharacterRemote,\n removeCharacterLocal,\n removeCharacterRemote,\n getAllCharactersLocal,\n getAllCharactersRemote,\n importCharacter,\n setLocalStoragePrefix,\n getCurrentCharacter,\n setCurrentCharacter,\n getCurrentCharacterKey,\n saveCurrentCharacter,\n getSheetView\n};\n", "/**\n * Handing keyboard shortcuts.\n */\nclass ShortCutKeys {\n /**\n * @param {EventEmitter} emitter\n */\n constructor (emitter) {\n this.emitter = emitter;\n this.shortcuts = {};\n document.addEventListener('keydown', this.checkShortCuts.bind(this));\n }\n /**\n * Add a shortcut that triggers an event.\n * @param {String} keys Key Combo use 'Ctrl+' and 'Shift+' to indicate those keys.\n * @param {String} event Event to emit.\n */\n addShortCut (keys, event) {\n this.shortcuts[keys] = event;\n }\n /**\n * Generate the key combo as a string.\n * @param {String} key Key pressed.\n * @param {Boolean} withControl Was control pressed.\n * @param {Boolean} withShift Was shift pressed.\n */\n getKeyCode (key, withControl, withShift) {\n let code = '';\n if (withControl) {\n code += 'Ctrl+';\n }\n if (withShift) {\n code += 'Shift+';\n }\n code += key;\n return code;\n }\n /**\n * Handler: Keydown event.\n * @param {KeyboardEvent} ev Keydown\n */\n checkShortCuts (ev) {\n let withControl = false;\n let withShift = false;\n if (ev.ctrlKey) {\n withControl = true;\n }\n if (ev.shiftKey) {\n withShift = true;\n }\n const key = ev.key;\n const code = this.getKeyCode(key, withControl, withShift);\n const event = this.shortcuts[code] || null;\n if (event) {\n ev.preventDefault();\n ev.stopPropagation();\n this.emitter.trigger(event);\n }\n }\n}\n\nexport default ShortCutKeys;\n", "/**\n * Manager:\n * Interface for save/backup/restore of data...\n */\nimport { generateCharacterKey, getCharacter, removeCharacterLocal, importCharacter, setLocalStoragePrefix, setCurrentCharacter, saveCurrentCharacter, getCurrentCharacterKey, getSheetView, getAllCharactersLocal } from '../services/CharacterService.js';\nimport ShortCutKeys from './ShortCutKeys.js';\nimport { monitorAuth } from '../services/AuthService.js';\n\nconst Manager = {\n /** @prop {EventEmitter} */\n emitter: null,\n /**\n * App name used in character model app property\n */\n appname: '',\n /**\n * Unsaved dialog\n */\n dialog_unsaved: document.querySelector('.alert-unsaved'),\n /**\n * Undo delete dialog\n */\n dialog_undo: document.querySelector('.alert-delete'),\n /**\n * Start a new character and change the hash.\n */\n triggerNewCharacter: function (char_type = '') {\n const key = generateCharacterKey();\n this.loadCharacter(key, char_type)\n .then(() => {\n window.location.hash = `#${key}`;\n })\n .catch((err) => {\n console.log(err);\n });\n },\n /**\n * Change the character based on a hash change\n * or maybe I should process the event in the handler and pass it here if necessary...\n */\n changeCharacter: function () {\n const urlhash = window.location.hash.substring(1);\n // No need if the character is already loaded.\n const cur_character_key = getCurrentCharacterKey();\n if (cur_character_key && urlhash === cur_character_key) {\n return;\n }\n this.loadCharacter(urlhash);\n },\n /**\n * Load character data based on a key\n * @param {String} key Character identifier\n * @param {String} char_type Character class type.\n */\n loadCharacter: async function (key, char_type = '') {\n this.hideUnsavedDialog();\n // Set character or creates one.\n const cur_character = setCurrentCharacter(key, char_type, true);\n cur_character.emitter = this.emitter;\n // Load up correct view\n const sheetView = getSheetView(cur_character, this.emitter);\n document.querySelector('main').innerHTML = '';\n document.querySelector('main').appendChild(\n sheetView\n );\n sheetView.character = cur_character;\n this.emitter.trigger('loaddialog:close');\n this.emitter.trigger('newdialog:close');\n },\n /**\n * Save character data\n */\n saveCharacter: function () {\n // For fields saved on blur we need to trigger it on the active field.\n // Fields that save on change will already have saved.\n if (document.activeElement) {\n const event = new Event('blur');\n document.activeElement.dispatchEvent(event);\n }\n try {\n saveCurrentCharacter();\n } catch (e) {\n this.emitter.trigger('error:display', e.message);\n return;\n }\n this.hideUnsavedDialog();\n },\n /**\n * Save a file of the current character\n * Falls back to showing the data for copy/pasting\n */\n downloadBackup: function (form) {\n const data = [];\n const names = [];\n const checks = Array.from(form.querySelectorAll('input[type=checkbox]:checked'));\n checks.forEach((ch) => {\n const character = getCharacter(ch.value);\n data.push(character);\n names.push(character.charname);\n });\n\n const format = form.querySelector('input[name=format]:checked').value;\n const date = new Date();\n\n if (format === 'email') {\n const body = `Below is the backup data for your character(s) ${names.join(', ')}.\n\nTo use this data, go to: ${window.location.href} and click the \"Restore Backup\" button. Then paste the text below into the box.\n\n---\n\n${JSON.stringify(data)}`;\n\n const url = `mailto:?subject=${encodeURIComponent(`Character backup: ${names.join(', ')} (${date.toLocaleString()})`)}&body=${encodeURIComponent(body)}`;\n\n // Sadly this simple solution doesn't work in iOS\n // document.location.href = url;\n this.emitter.trigger('backup:email', url);\n } else {\n if (typeof window.Blob !== 'function') {\n // fallback to displaying the data for copy/pasting\n this.emitter.trigger('backup:textpaste', JSON.stringify(data));\n return;\n }\n // for env that support it, create a file for download\n const a = document.createElement('a');\n const file = new Blob([JSON.stringify(data)], { type: 'application/json' });\n const url = URL.createObjectURL(file);\n a.href = url;\n a.download = `${this.appname}_${date.getFullYear()}_${date.getMonth() + 1}_${date.getDate()}`;\n document.body.appendChild(a);\n a.click();\n setTimeout(function () {\n document.body.removeChild(a);\n window.URL.revokeObjectURL(url);\n }, 0);\n }\n },\n /**\n * Restore Backup form handler\n * @param {HTMLElement} form\n */\n restoreFormSubmit: function (form) {\n const input_file = form.querySelector('input[type=file]');\n const input = form.querySelector('textarea');\n if (input_file.files && input_file.files.length > 0) {\n Array.from(input_file.files).forEach((f) => {\n const reader = new FileReader();\n // Closure to capture the file information.\n reader.onload = (() => {\n return (e) => {\n this.restoreCharacters(e.target.result);\n };\n })(f);\n reader.readAsText(f);\n });\n } else if (input.value !== '') {\n this.restoreCharacters(input.value);\n }\n },\n /**\n * Take json backup data and load the character(s)\n * @param {String} data JSON string we hope\n */\n restoreCharacters: function (data) {\n try {\n // look for the start of the JSON string Array of Objects\n let start = data.indexOf('[{');\n let end = data.lastIndexOf('}]');\n // make sure it's not :[{, an array of objects inside one of the objects\n const check = data.indexOf(':[{');\n if (check !== -1 && check < start) {\n // if so start over\n start = -1;\n }\n if (start === -1) {\n start = data.indexOf('{');\n end = data.lastIndexOf('}');\n data = data.substring(start);\n data = data.substring(0, end + 1);\n } else {\n data = data.substring(start);\n data = data.substring(0, end + 2);\n }\n data = data.trim(); // just in case\n\n // convert linebreaks to html br else JSON.parse breaks\n // first make sure it's not a break between objects...\n data = data.replace(/\\},[\\r\\n]+\\{/g, '},{');\n data = data.replace(/(?:\\r\\n|\\r|\\n)/g, '
    ');\n let backups = JSON.parse(data);\n // make it an array\n if (!Array.isArray(backups)) {\n backups = [backups];\n }\n const imported_chars = [];\n let reloadCurrentChar = false;\n const currentCharKey = getCurrentCharacterKey();\n backups.forEach((char_obj) => {\n const newCharacter = importCharacter(char_obj);\n // if its the current character we should reload them\n if (newCharacter.key === currentCharKey) {\n reloadCurrentChar = true;\n }\n const li = document.createElement('li');\n li.textContent = `${newCharacter.charname} has been added. `;\n const a = document.createElement('a');\n a.setAttribute('href', `#${newCharacter.key}`);\n a.textContent = 'View character now.';\n a.addEventListener('click', () => {\n this.alert.closeClear();\n });\n li.appendChild(a);\n imported_chars.push(li);\n });\n\n const ul = document.createElement('ul');\n imported_chars.forEach((li) => {\n ul.appendChild(li);\n });\n this.alert.header = 'Restored Characters';\n this.alert.setContent([ul]);\n this.alert.open();\n\n if (reloadCurrentChar) {\n this.loadCharacter(currentCharKey).catch((error) => {\n console.log(error);\n });\n }\n } catch (e) {\n alert(`Error processing backup data: ${e.message}`);\n }\n },\n /**\n * Set a timeout to remove the character in a few seconds.\n * @param {String} key character key\n */\n deleteCharacterTemp: function (key) {\n if (key === '' || key === 'settings') {\n return;\n }\n // if its the current character we should trigger \"new character\" action\n if (getCurrentCharacterKey() === key) {\n this.triggerNewCharacter();\n }\n this.dialog_undo.querySelector('button').dataset.key = key;\n this.dialog_undo.hidden = false;\n // This will trigger a transition bar.\n const timeoutIndicator = this.dialog_undo.querySelector('.delete-timeout');\n // The transition animation doesn't happen if you don't have this timeout,\n // since we are also just now revealing the element.\n setTimeout(() => {\n timeoutIndicator.classList.add('transition', 'timeout');\n }, 10);\n // Note: if we change the timeout of the delete undo, we also need to change the transition timing in the css.\n this[`deleteTimeout${key}`] = setTimeout(this.deleteCharacter.bind(this), 8000, key);\n },\n /**\n * Delete a character from local storage\n * @param {String} key character key\n */\n deleteCharacter: function (key) {\n if (key === '' || key === 'settings') {\n return;\n }\n removeCharacterLocal(key);\n this.dialog_undo.querySelector('button').dataset.key = '';\n this.dialog_undo.hidden = true;\n // This will reset the transition bar.\n const timeoutIndicator = this.dialog_undo.querySelector('.delete-timeout');\n timeoutIndicator.classList.remove('transition', 'timeout');\n },\n /**\n * Remove the timeout and stop the delete from happening.\n * @param {Event} ev Undo button click.\n */\n undoDelete: function (ev) {\n const key = ev.target.dataset.key || null;\n if (!key) {\n return;\n }\n this.dialog_undo.querySelector('button').dataset.key = '';\n this.dialog_undo.hidden = true;\n // Reset transition bar.\n const timeoutIndicator = this.dialog_undo.querySelector('.delete-timeout');\n timeoutIndicator.classList.remove('transition', 'timeout');\n if (this[`deleteTimeout${key}`]) {\n clearTimeout(this[`deleteTimeout${key}`]);\n }\n },\n /**\n * If no characters are saved we show an app intro dialog\n */\n showIntroDialog: function () {\n const template = document.getElementById('introAlert');\n this.alert.setContent([...document.importNode(template.content, true).children]);\n this.alert.open();\n },\n /**\n * Show the unsaved data dialog.\n */\n showUnsavedDialog: function () {\n this.dialog_unsaved.hidden = false;\n },\n /**\n * Hide the unsaved data dialog.\n */\n hideUnsavedDialog: function () {\n this.dialog_unsaved.hidden = true;\n },\n /**\n * Show an error message.\n * @param {String} error\n */\n showErrorMessage: function (error) {\n // Blah, for now just keep it simple and obvious.\n alert(error);\n },\n /**\n * Start up the app with some events and such\n * @param {Object} settings things we need to set external to this script\n * @param {EventEmitter} settings.emitter\n * @param {String} settings.prefix prefix for localStorage keys\n * @param {String} settings.appname used to identify the app property in a character model\n */\n initialize: function ({\n emitter = null,\n prefix = '',\n appname = ''\n }) {\n if (!emitter || !prefix || !appname) {\n document.body.innerHTML = '

    App is missing required settings.

    ';\n return;\n }\n this.emitter = emitter;\n // Set this up first.\n this.emitter.on('error:display', this.showErrorMessage, this);\n\n this.appname = appname;\n // set up storage\n setLocalStoragePrefix(prefix);\n // set up default alert\n this.alert = document.getElementById('alert-main');\n\n monitorAuth(this.emitter);\n\n const shortCuts = new ShortCutKeys(this.emitter);\n shortCuts.addShortCut('Ctrl+Shift+ArrowDown', 'character:save');\n shortCuts.addShortCut('Ctrl+Shift+ArrowRight', 'tab:switch');\n shortCuts.addShortCut('Ctrl+Shift+ArrowLeft', 'tab:switch');\n shortCuts.addShortCut('Ctrl+Shift+ArrowUp', 'loaddialog:toggle');\n\n document.querySelector('.btn-help').addEventListener('click', (ev) => {\n ev.preventDefault();\n const template = document.getElementById('helpDialog');\n const div = document.importNode(template.content, true);\n this.alert.setContent([...div.children]);\n this.alert.open();\n });\n\n // Event: Listen for hashchange and change the current character\n window.addEventListener('hashchange', () => { this.changeCharacter(); }, false);\n\n this.dialog_unsaved.querySelector('.btn-save').addEventListener('click', () => {\n this.emitter.trigger('character:save');\n });\n this.dialog_undo.querySelector('.btn-delete-undo').addEventListener('click', (ev) => {\n this.undoDelete(ev);\n });\n\n // Listen for events, mostly from the menus.\n this.emitter.on('character:new', this.triggerNewCharacter, this);\n this.emitter.on('character:save', this.saveCharacter, this);\n this.emitter.on('character:delete', this.deleteCharacterTemp, this);\n this.emitter.on('backup:download', this.downloadBackup, this);\n this.emitter.on('backup:restore', this.restoreFormSubmit, this);\n this.emitter.on('dialog:save:show', this.showUnsavedDialog, this);\n this.emitter.on('dialog:save:hide', this.hideUnsavedDialog, this);\n\n // Check the hash to see if we need to load a specific character\n const urlhash = window.location.hash.substring(1);\n if (urlhash !== '') {\n this.loadCharacter(urlhash).catch((error) => {\n console.log(error);\n });\n } else {\n // Show intro if they have no characters, since they might be new to this...\n if (getAllCharactersLocal().length === 0) {\n this.showIntroDialog();\n }\n this.triggerNewCharacter();\n }\n }\n};\n\nexport default Manager;\n", "// Confirmation button (i.e. \"Are you sure\" after first click.)\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\nSubmit\nAre you sure?\n`;\n\nclass ConfirmButton extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this._wait = 3000;\n // Default to not triggered\n this._triggered = false;\n // Default to asking for confirmation.\n this._confirm = true;\n // No default callback after confirmation.\n this._confirmCallback = null;\n this.dataset.triggered = 'false';\n // Accessible role\n this.setAttribute('role', 'button');\n }\n connectedCallback () {\n // Add focus-ability if it has not already been set in the html.\n if (this.getAttribute('tabindex') === null) {\n this.setAttribute('tabindex', 0);\n }\n // click handler\n this.addEventListener('click', this._handleClick);\n // space/enter handler to simulate normal button\n this.addEventListener('keydown', this._handleKeyDown);\n this._wait = parseInt(this.dataset.wait || 3000, 10);\n // Allow for setting the confirm click feature to be disabled.\n // Only set this here if the data attribute is explicitly set\n // else it will overwrite the property set on the class directly.\n if (this.dataset.confirm !== undefined) {\n this._confirm = !(this.dataset.confirm === 'false');\n }\n // Unhide slotted content now that the button is loaded.\n // CSS will handle this now based on data-triggered.\n Array.from(this.children).forEach((slotted) => {\n slotted.hidden = false;\n });\n if (this._confirmCallback) {\n this.addEventListener('click', this._confirmCallback);\n }\n }\n disconnectedCallback () {\n this.removeEventListener('click', this._handleClick);\n this.removeEventListener('keydown', this._handleKeyDown);\n if (this._confirmCallback) {\n this.removeEventListener('click', this._confirmCallback);\n }\n }\n /**\n * Update display when triggered value changes.\n * @param {Boolean|String} value\n */\n set triggered (value) {\n const newValue = !!value;\n if (this._triggered === newValue) {\n return;\n }\n this._triggered = newValue;\n // Update data-triggered so the css changes what text is displayed.\n if (this._triggered) {\n this.dataset.triggered = 'true';\n } else {\n this.dataset.triggered = 'false';\n }\n }\n get triggered () {\n return this._triggered;\n }\n get confirm () {\n return this._confirm;\n }\n /**\n * Set if the confirm button/click should be used.\n */\n set confirm (value) {\n this._confirm = !!value;\n }\n\n get confirmCallback () {\n return this._confirmCallback;\n }\n /**\n * Set confirm callback here if you need to set it _before_ putting the button in the DOM.\n * This assures it is triggered after the default event handler.\n */\n set confirmCallback (func) {\n if (typeof func === 'function') {\n this._confirmCallback = func;\n }\n }\n /**\n * Clicking.\n * @param {Event} ev Click event on element.\n */\n _handleClick (ev) {\n if (!this.triggered && this._confirm) {\n // stop any other events from happening\n ev.preventDefault();\n ev.stopImmediatePropagation();\n this.triggered = true;\n // wait a bit then reset.\n setTimeout(() => {\n this.triggered = false;\n }, this._wait);\n }\n // let any other events happen if triggered was true\n // whatever other listeners have been added to the click.\n }\n /**\n * Handle button or space to trigger.\n * @param {KeyboardEvent} ev\n */\n _handleKeyDown (ev) {\n if ((ev.key !== 'Enter' && ev.key !== ' ') || ev.shiftKey) {\n return;\n }\n // Prevent things like space bar trigger scrolling while focused on the button.\n ev.preventDefault();\n this.click();\n }\n /**\n * Use to reset the button from external code.\n */\n reset () {\n this.triggered = false;\n }\n}\n\nif (!window.customElements.get('confirm-button')) {\n window.customElements.define('confirm-button', ConfirmButton);\n}\n\nexport default ConfirmButton;\n", "import { getAllCharactersLocal, getAllCharactersRemote, getCharacter, getCharacterRemote, saveCharacter, saveCharacterRemote, removeCharacterRemote, removeCharacterLocal } from './CharacterService.js';\n\nconst compareLocalToRemote = function (local, remote) {\n // updated stamp on both is in UTC string which can be parse from new Date(utc string)\n const lUpdated = new Date(local);\n const rUpdated = new Date(remote);\n if (lUpdated > rUpdated) {\n return 'local';\n }\n if (rUpdated > lUpdated) {\n return 'remote';\n }\n return 'equal';\n};\n/**\n * Get all characters local and remote\n * With comparisons by key for which is most recent.\n * @returns {Object[]}\n */\nconst getCharacterMatchings = async function () {\n const localCharacters = getAllCharactersLocal();\n const remoteCharacters = await getAllCharactersRemote();\n const matches = [];\n localCharacters.forEach((local) => {\n const match = {\n key: local.key,\n local\n };\n const remote = remoteCharacters.get(local.key);\n if (remote) {\n match.remote = remote;\n remoteCharacters.delete(local.key);\n // Set something to say which is newer.\n match.latest = compareLocalToRemote(local.updated, remote.updated);\n }\n matches.push(match);\n });\n // Any that are on remote but not on local.\n remoteCharacters.forEach((remote) => {\n const match = {\n key: remote.key,\n remote\n };\n matches.push(match);\n });\n return matches;\n};\n/**\n * Upload a character to the remote.\n * @param {String} key\n * @returns {Boolean}\n */\nconst uploadCharacter = async function (key) {\n const char = getCharacter(key);\n if (!char) {\n throw new Error('Character not found');\n }\n const remote = await getCharacterRemote(key);\n if (remote) {\n throw new Error('Character already on the remote');\n }\n return await saveCharacterRemote(char);\n};\n/**\n * Download a character to the local.\n * @param {String} key\n * @returns {Boolean}\n */\nconst downloadCharacter = async function (key) {\n const char = getCharacter(key);\n if (char) {\n return 'Character already on local';\n }\n const remote = await getCharacterRemote(key);\n if (!remote) {\n return 'Character not found on the remote';\n }\n return await saveCharacter(remote);\n};\n/**\n * Delete remote character data.\n * @param {String} key\n * @returns {Boolean}\n */\nconst deleteRemote = async function (key) {\n return removeCharacterRemote(key);\n};\n/**\n * Delete local character data.\n * @param {String} key\n * @returns {Boolean}\n */\nconst deleteLocal = async function (key) {\n return removeCharacterLocal(key);\n};\n/**\n * Update remote character from local data.\n * @param {String} key\n * @returns {Boolean}\n */\nconst syncToRemote = async function (key) {\n const local = getCharacter(key);\n if (!local) {\n throw new Error('Character not found on local');\n }\n return await saveCharacterRemote(local);\n};\n/**\n * Update local character from remote data.\n * @param {String} key\n * @returns {Boolean}\n */\nconst syncToLocal = async function (key) {\n const remote = await getCharacterRemote(key);\n if (!remote) {\n throw new Error('Character not found on the remote');\n }\n const result = await saveCharacter(remote);\n return result;\n};\n\nexport {\n getCharacterMatchings,\n uploadCharacter,\n downloadCharacter,\n deleteRemote,\n deleteLocal,\n syncToRemote,\n syncToLocal\n};\n", "/**\n * Character local/remote sync info/actions.\n */\nimport { downloadCharacter, uploadCharacter, deleteRemote, deleteLocal, syncToLocal, syncToRemote } from '../services/syncService.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n
    ()
    \n
    \n No local copy.\n \n \n
    \n
    \n No remote copy.\n \n \n
    \n
    \n
    \n`;\n\nclass SyncInfo extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.setAttribute('role', 'list-item');\n this.setAttribute('aria-labelledby', 'char-name');\n this._key = '';\n this.localDiv = this.shadowRoot.querySelector('.local');\n this.remoteDiv = this.shadowRoot.querySelector('.remote');\n this.syncDiv = this.shadowRoot.querySelector('.syncaction');\n this.isCurrentCharacter = false;\n }\n\n connectedCallback () {\n this.shadowRoot.addEventListener('click', this.handleButtonClick.bind(this));\n }\n\n disconnectedCallback () {\n this.shadowRoot.removeEventListener('click', this.handleButtonClick.bind(this));\n }\n\n get key () {\n return this._key;\n }\n\n _showError (message) {\n this.shadowRoot.querySelector('.error').innerHTML = message;\n }\n /**\n * Handler clicks in the element.\n * @param {Event} ev Click event\n */\n handleButtonClick (ev) {\n console.log(ev);\n const button = ev.target.closest('button');\n if (!button) {\n return;\n }\n const action = button.dataset.action;\n if (!action) {\n return;\n }\n console.log(`Action: ${action}`);\n\n switch (action) {\n case 'upload':\n uploadCharacter(this._key)\n .then(() => {\n this.remoteDiv.querySelector('.summary').innerHTML = this.localDiv.querySelector('.summary').innerHTML;\n this.remoteDiv.querySelector('.updated').innerHTML = this.localDiv.querySelector('.updated').innerHTML;\n this.remoteDiv.querySelector('.action').innerHTML = '';\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('removeremote', 'Delete from Remote')\n );\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'removeremote':\n deleteRemote(this._key)\n .then(() => {\n this.remoteDiv.querySelector('.summary').innerHTML = 'No remote copy.';\n this.remoteDiv.querySelector('.updated').innerHTML = '';\n this.remoteDiv.querySelector('.action').innerHTML = '';\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('upload', 'Upload')\n );\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'download':\n downloadCharacter(this._key)\n .then(() => {\n this.localDiv.querySelector('.summary').innerHTML = this.remoteDiv.querySelector('.summary').innerHTML;\n this.localDiv.querySelector('.updated').innerHTML = this.remoteDiv.querySelector('.updated').innerHTML;\n this.localDiv.querySelector('.action').innerHTML = '';\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('removelocal', 'Delete from Local')\n );\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'removelocal':\n if (this.isCurrentCharacter) {\n this._showError('You cannot remove the currently displayed character.');\n return;\n }\n deleteLocal(this._key)\n .then(() => {\n this.localDiv.querySelector('.summary').innerHTML = 'No local copy.';\n this.localDiv.querySelector('.updated').innerHTML = '';\n this.localDiv.querySelector('.action').innerHTML = '';\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('download', 'Download')\n );\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'syncup':\n syncToRemote(this._key)\n .then(() => {\n this.remoteDiv.querySelector('.summary').innerHTML = this.localDiv.querySelector('.summary').innerHTML;\n this.remoteDiv.querySelector('.updated').innerHTML = this.localDiv.querySelector('.updated').innerHTML;\n this.remoteDiv.querySelector('.action').innerHTML = '';\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('removeremote', 'Delete from Remote')\n );\n this.syncDiv.innerHTML = '';\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'syncdown':\n if (this.isCurrentCharacter) {\n this._showError('You cannot sync to local the currently displayed character.');\n return;\n }\n syncToLocal(this._key)\n .then(() => {\n this.localDiv.querySelector('.summary').innerHTML = this.remoteDiv.querySelector('.summary').innerHTML;\n this.localDiv.querySelector('.updated').innerHTML = this.remoteDiv.querySelector('.updated').innerHTML;\n this.localDiv.querySelector('.action').innerHTML = '';\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('removelocal', 'Delete from Local')\n );\n this.syncDiv.innerHTML = '';\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n }\n }\n\n _getButton (action, label) {\n const button = document.createElement('BUTTON');\n button.classList.add('btn-sm');\n button.dataset.action = action;\n button.innerText = label;\n return button;\n }\n /**\n * Set the character data.\n * @param {Object} data\n * @param {String} key Character key.\n * @param {Character} local Local copy\n * @param {Character} remote Remote copy\n * @param {String} latest Which is more recent.\n * @returns\n */\n setData ({\n key = '',\n local = {},\n remote = {},\n latest = ''\n }) {\n if (!key) {\n return;\n }\n this._key = key;\n const charName = local.key\n ? local.charname\n : (remote.key ? remote.charname : '[Unknown]');\n this.shadowRoot.querySelector('.charname').innerHTML = charName;\n this.shadowRoot.querySelector('.key').innerHTML = key;\n if (local.key) {\n this.localDiv.querySelector('.summary').innerHTML = local.summaryHeader;\n this.localDiv.querySelector('.updated').innerHTML = local.updatedTime;\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('removelocal', 'Delete from Local')\n );\n } else {\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('download', 'Download')\n );\n }\n\n if (remote.key) {\n this.remoteDiv.querySelector('.summary').innerHTML = remote.summaryHeader;\n this.remoteDiv.querySelector('.updated').innerHTML = remote.updatedTime;\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('removeremote', 'Delete from Remote')\n );\n } else {\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('upload', 'Upload')\n );\n }\n\n if (latest === 'local') {\n this.syncDiv.appendChild(\n this._getButton('syncup', 'Update on Remote')\n );\n } else if (latest === 'remote') {\n this.syncDiv.appendChild(\n this._getButton('syncdown', 'Update on Local')\n );\n }\n }\n}\n\nif (!window.customElements.get('sync-info')) {\n window.customElements.define('sync-info', SyncInfo);\n}\n\nexport default SyncInfo;\n", "/**\n * Action Toolbar\n * Also requires the Modal component.\n */\nimport { getAllCharactersLocal, getCurrentCharacterKey, getGameOptions } from '../services/CharacterService.js';\nimport ConfirmButton from '../components/ConfirmButton.js';\nimport SyncInfo from '../components/SyncInfo.js';\nimport { isAuthed, signIn, signOut } from '../services/AuthService.js';\nimport { getCharacterMatchings } from '../services/syncService.js';\n\n/**\n * Buttons in the toolbar.\n * Mostly in re focus management and keyboard events.\n */\nclass ActionButton {\n /**\n * @param {HTMLElement} el Button element.\n * @param {ActionMenu} menu\n */\n constructor (el, menu) {\n this.el = el;\n this.menu = menu;\n this.action = el.dataset.action || '';\n this.el.addEventListener('keydown', this.handleKeyBoardEvent.bind(this));\n this.el.addEventListener('click', this.menu.setTabFocusToButton.bind(this.menu, this));\n }\n /**\n * Handler: Keyboard actions.\n * @param {KeyboardEvent} ev Keydown event.\n */\n handleKeyBoardEvent (ev) {\n // Stop if any other modifer keys are pressed.\n if (ev.shiftKey || ev.ctrlKey || ev.metaKey || ev.altKey) {\n return;\n }\n if (ev.key === 'ArrowRight') {\n this.removeTabFocus();\n this.menu.setFocusToNext(this);\n return;\n }\n if (ev.key === 'ArrowLeft') {\n this.removeTabFocus();\n this.menu.setFocusToPrevious(this);\n return;\n }\n if (ev.key === 'Home') {\n this.removeTabFocus();\n this.menu.setFocusToFirst();\n return;\n }\n if (ev.key === 'End') {\n this.removeTabFocus();\n this.menu.setFocusToLast();\n }\n }\n\n isFocusable () {\n return this.el.getAttribute('tabindex') > -1;\n }\n\n isVisible () {\n return !!(this.el.offsetWidth || this.el.offsetHeight || this.el.getClientRects().length);\n }\n /**\n * Set button to not be tabbable.\n */\n removeTabFocus () {\n this.el.setAttribute('tabindex', '-1');\n }\n /**\n * Set button to be tabbable.\n */\n setTabFocus () {\n this.el.setAttribute('tabindex', '0');\n }\n /**\n * Focus on this button.\n */\n focus () {\n this.el.focus();\n }\n /**\n * Switch to this button. Set its tabindex and focus.\n * @param {Boolean} forward\n */\n switchTo (forward = true) {\n if (!this.isVisible()) {\n if (forward) {\n this.menu.setFocusToNext(this);\n } else {\n this.menu.setFocusToPrevious(this);\n }\n }\n this.setTabFocus();\n this.focus();\n }\n}\n\n/**\n * Toolbar and associated action events or dialogs.\n */\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n \n \n
    \n \n
    \n \n \n \n \n
    \n
    \n\n`;\n\n/**\n* @prop {Array} Matching action button classes to methods to calls.\n*/\nconst buttonActions = {\n save: '_saveCharacter',\n load: '_openLoadModal',\n new: '_newCharacterModal',\n backup: '_openDownloadForm',\n restore: '_openRestoreForm',\n delete: '_openDeleteModal',\n auth: '_openAuthDialog',\n more: '_showMore'\n};\nclass ActionMenu extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.setAttribute('role', 'toolbar');\n this.setAttribute('aria-label', 'Character Actions');\n this.setAttribute('tabindex', 0);\n /**\n * @prop {ActionButton[]}\n */\n this.buttons = [];\n /**\n * @prop {HTMLELement} Menu toogle button when menu is collapsed on narrow screens.\n */\n this.opener = null;\n /**\n * @prop {Modal} Modal for new menu.\n */\n this.newDialog = null;\n /**\n * @prop {Modal} Modal for load menu.\n */\n this.loadDialog = null;\n /**\n * @prop {Modal} Modal for Backup save.\n */\n this.downloadDialog = null;\n /**\n * @prop {Modal} Modal for Backup restore.\n */\n this.restoreDialog = null;\n /**\n * @prop {Modal} authDialog\n */\n this.authDialog = null;\n /**\n * @prop {Modal} syncDialog\n */\n this.syncDialog = null;\n }\n\n connectedCallback () {\n this.addEventListener('focus', this.focus.bind(this));\n\n const buttons = this.shadowRoot.querySelectorAll('button');\n Array.prototype.forEach.call(buttons, (btn) => {\n this.buttons.push(new ActionButton(btn, this));\n });\n // event handlers for all the menu buttons\n this.shadowRoot.addEventListener('click', this._handleClicks.bind(this));\n }\n\n disconnectedCallback () {\n this.shadowRoot.removeEventListener('click', this._handleClicks.bind(this));\n if (this.emitter) {\n this.emitter.off('newdialog:close', this._closeNewModal, this);\n this.emitter.off('loaddialog:close', this._closeLoadModal, this);\n this.emitter.off('loaddialog:toggle', this._openLoadModal, this);\n this.emitter.off('backup:email', this._emailDownload, this);\n this.emitter.off('backup:textpaste', this._altDownload, this);\n this.emitter.off('auth:enabled', this._showAuth, this);\n this.emitter.off('auth:signin', this._signedIn, this);\n this.emitter.off('auth:signout', this._signedOut, this);\n }\n }\n\n setEmitter (emitter) {\n this.emitter = emitter;\n this.emitter.on('newdialog:close', this._closeNewModal, this);\n this.emitter.on('loaddialog:close', this._closeLoadModal, this);\n this.emitter.on('loaddialog:toggle', this._openLoadModal, this);\n this.emitter.on('backup:email', this._emailDownload, this);\n this.emitter.on('backup:textpaste', this._altDownload, this);\n this.emitter.on('auth:enabled', this._showAuth, this);\n this.emitter.on('auth:signin', this._signedIn, this);\n this.emitter.on('auth:signout', this._signedOut, this);\n }\n\n _handleClicks (ev) {\n const target = ev.target.closest('button');\n const button = this.buttons.find((btn) => { return btn.el === target; });\n if (!button) {\n return;\n }\n const action = buttonActions[button.action] || null;\n if (!action) {\n return;\n }\n this[action](button);\n }\n\n _openAuthDialog () {\n this.authDialog = this.authDialog || document.getElementById('dialog-auth');\n this.authDialog.clear();\n if (this.authDialog.isOpen) {\n this.authDialog.close();\n return;\n }\n let template = null;\n\n if (isAuthed()) {\n template = document.getElementById('authSignOutModal');\n } else {\n template = document.getElementById('authSignInModal');\n }\n this.authDialog.setContent([...document.importNode(template.content, true).children]);\n if (isAuthed()) {\n this.authDialog.querySelector('#signOut').addEventListener('click', () => {\n signOut();\n });\n this.authDialog.querySelector('#syncData').addEventListener('click', () => {\n this._openSyncModal();\n this.authDialog.close();\n });\n } else {\n this.authDialog.querySelector('#googleSignIn').addEventListener('click', () => {\n signIn();\n });\n }\n this.authDialog.open();\n }\n /**\n * Open the character sync modal.\n */\n _openSyncModal () {\n this.syncDialog = this.syncDialog || document.getElementById('dialog-sync');\n this.syncDialog.clear();\n if (this.syncDialog.isOpen) {\n this.syncDialog.close();\n return;\n }\n const template = document.getElementById('syncModal');\n this.syncDialog.setContent([...document.importNode(template.content, true).children]);\n\n const currentCharKey = getCurrentCharacterKey();\n\n getCharacterMatchings().then((matches) => {\n const frag = document.createDocumentFragment();\n matches.forEach((match) => {\n const info = new SyncInfo();\n info.setData(match);\n // Not all actions are allowed for the current character.\n if (info.key === currentCharKey) {\n info.isCurrentCharacter = true;\n }\n frag.appendChild(info);\n });\n this.syncDialog.querySelector('#characterSyncList').appendChild(frag);\n this.syncDialog.open();\n })\n .catch((error) => {\n console.log(error);\n });\n }\n /**\n * Show the dialog for backing up characters.\n * Else close it if its open.\n */\n _openDownloadForm () {\n this.downloadDialog = this.downloadDialog || document.getElementById('dialog-backup');\n this.downloadDialog.clear();\n if (this.downloadDialog.isOpen) {\n this.downloadDialog.close();\n return;\n }\n const template = document.getElementById('backupModal');\n const form = document.importNode(template.content, true);\n\n const checkboxes = [];\n getAllCharactersLocal().forEach((char) => {\n const li = `
  • `;\n checkboxes.push(li);\n });\n form.querySelector('.character_downloads').innerHTML = checkboxes.join('');\n this.downloadDialog.setContent([...form.children], false);\n this.downloadDialog.querySelector('form').addEventListener('submit', (ev) => {\n ev.preventDefault();\n this.emitter.trigger('backup:download', ev.target);\n });\n this.downloadDialog.open();\n }\n /**\n * Show the back up restore form.\n * Else close it if its open.\n */\n _openRestoreForm () {\n this.restoreDialog = this.restoreDialog || document.getElementById('dialog-restore');\n this.restoreDialog.clear();\n if (this.restoreDialog.isOpen) {\n this.restoreDialog.close();\n return;\n }\n const template = document.getElementById('restoreModal');\n const form = document.importNode(template.content, true);\n this.restoreDialog.setContent([...form.children], false);\n this.restoreDialog.querySelector('form').addEventListener('submit', (ev) => {\n ev.preventDefault();\n this.emitter.trigger('backup:restore', ev.target);\n this.restoreDialog.closeClear();\n });\n this.restoreDialog.open();\n }\n /**\n * If file download is unavailable show the data to copy/paste\n * @param {String} data the backup data\n */\n _altDownload (data) {\n const p = document.createElement('p');\n p.innerHTML = `Your current browser/os does not support direct file downloads, so here is the data for you to copy/paste.`;\n const text = document.createElement('textarea');\n text.classList.add('large');\n text.value = data;\n this.downloadDialog.clear();\n this.downloadDialog.header = 'Alernate Download Option';\n this.downloadDialog.setContent([p, text, this.downloadDialog.getCloseButton()], false);\n this.downloadDialog.open();\n }\n /**\n * Show email download link.\n * @param {String} url The email url\n */\n _emailDownload (url) {\n const a = document.createElement('a');\n a.href = url;\n a.setAttribute('target', '_blank');\n a.innerHTML = 'Open new message in default email client';\n a.addEventListener('click', () => {\n this.downloadDialog.closeClear();\n });\n const p = document.createElement('p');\n p.appendChild(a);\n this.downloadDialog.clear();\n this.downloadDialog.setContent([p, this.downloadDialog.getCloseButton()], false);\n this.downloadDialog.open();\n }\n /**\n * Trigger a save character event.\n */\n _saveCharacter () {\n this.emitter.trigger('character:save');\n }\n /**\n * Open the new character modal.\n */\n _newCharacterModal () {\n this.newDialog = this.newDialog || document.getElementById('dialog-new');\n this.newDialog.clear();\n if (this.newDialog.isOpen) {\n this.newDialog.close();\n return;\n }\n\n // Are there unsaved changes\n // This could be done better in the future if we had some kind of central state management.\n let currentlyUnsaved = false;\n // is the unsaved dialog showing...\n const unsavedDialog = document.querySelector('.alert-unsaved');\n if (unsavedDialog && !unsavedDialog.hidden) {\n currentlyUnsaved = true;\n }\n\n const template = document.getElementById('createModal');\n const content = document.importNode(template.content, true);\n\n if (currentlyUnsaved) {\n const alert = document.createElement('p');\n alert.classList.add('alert');\n alert.innerHTML = 'Warning: You have unsaved changes.';\n content.querySelector('form').prepend(alert);\n }\n\n const select = content.querySelector('select');\n getGameOptions().forEach((char_type) => {\n const option = document.createElement('option');\n option.value = char_type;\n option.innerText = char_type;\n select.appendChild(option);\n });\n this.newDialog.setContent([...content.children]);\n this.newDialog.querySelector('form').addEventListener('submit', (ev) => {\n ev.preventDefault();\n const formData = new FormData(ev.target);\n this.emitter.trigger('character:new', formData.get('char_type'));\n });\n this.newDialog.open();\n }\n /**\n * Close the mew modal.\n */\n _closeNewModal () {\n if (this.newDialog !== null) {\n this.newDialog.closeClear();\n }\n }\n /**\n * Load up a character by triggering a hash change.\n * @param {Event} ev Click event\n * @returns\n */\n _loadCharClick (ev) {\n const button = ev.currentTarget;\n const charKey = button.dataset.key || '';\n if (charKey === '') {\n return;\n }\n window.location.hash = `#${charKey}`;\n }\n /**\n * Open the dialog to load a character.\n */\n _openLoadModal () {\n this.loadDialog = this.loadDialog || document.getElementById('dialog-load');\n this.loadDialog.clear();\n if (this.loadDialog.isOpen) {\n this.loadDialog.close();\n return;\n }\n\n // Are there unsaved changes\n // This could be done better in the future if we had some kind of central state management.\n let currentlyUnsaved = false;\n // is the unsaved dialog showing...\n const unsavedDialog = document.querySelector('.alert-unsaved');\n if (unsavedDialog && !unsavedDialog.hidden) {\n currentlyUnsaved = true;\n }\n\n const template = document.getElementById('loadModal');\n const content = document.importNode(template.content, true);\n const list = content.querySelector('ul');\n getAllCharactersLocal().forEach((char) => {\n const li = document.createElement('li');\n const cButton = new ConfirmButton();\n cButton.dataset.key = char.key;\n cButton.classList.add('btn', 'btn-plain');\n cButton.innerHTML = `${char.summaryHeader}\n `;\n if (!currentlyUnsaved) {\n cButton.confirm = false;\n }\n // set this so it's added _after_ the internal confirm event.\n cButton.confirmCallback = this._loadCharClick.bind(this);\n li.appendChild(cButton);\n list.appendChild(li);\n });\n this.loadDialog.setContent([...content.children]);\n this.loadDialog.open();\n }\n /**\n * Close the load modal.\n */\n _closeLoadModal () {\n if (this.loadDialog !== null) {\n this.loadDialog.closeClear();\n }\n }\n /**\n * Modal for deleting characters.\n */\n _openDeleteModal () {\n const modal = document.getElementById('dialog-delete');\n if (modal.isOpen) {\n modal.close();\n return;\n }\n const template = document.getElementById('deleteModal');\n const content = document.importNode(template.content, true);\n\n const items = [];\n getAllCharactersLocal().forEach((char) => {\n const li = `
  • \n ${char.summaryHeader}\n \n
  • `;\n items.push(li);\n });\n content.querySelector('ul').innerHTML = items.join('');\n\n modal.setContent([...content.children]);\n modal.querySelector('ul').addEventListener('click', (ev) => {\n const button = ev.target.tagName === 'CONFIRM-BUTTON' ? ev.target : ev.target.closest('confirm-button');\n if (button && button.classList.contains('btn-delete-char')) {\n ev.preventDefault();\n this.emitter.trigger('character:delete', button.getAttribute('data-key'));\n modal.closeClear();\n }\n });\n modal.open();\n }\n\n _showMore () {\n this.shadowRoot.querySelector('.more-actions').classList.toggle('closed');\n }\n /**\n * Show auth button if auth is setup.\n */\n _showAuth () {\n const authbutton = this.buttons.find((btn) => { return btn.el.classList.contains('btn-auth'); });\n if (authbutton) {\n authbutton.el.classList.remove('hidden');\n }\n }\n /**\n * When user switches to being logged in.\n */\n _signedIn () {\n const button = this.buttons.find((b) => {\n return b.action === 'auth';\n });\n if (button) {\n button.el.innerHTML = 'Sync/Logout';\n }\n // Trigger the dialog so user can sync data.\n this._openAuthDialog();\n }\n /**\n * When user switches to being logged ou.\n */\n _signedOut () {\n const button = this.buttons.find((b) => {\n return b.action === 'auth';\n });\n if (button) {\n button.el.innerHTML = 'Login';\n }\n if (this.authDialog && this.authDialog.isOpen) {\n this.authDialog.close();\n }\n }\n /**\n * Set focus to next button (or wrap around).\n * @param {ActionButton} currentBtn\n */\n setFocusToNext (currentBtn) {\n const index = this.buttons.indexOf(currentBtn);\n const newIndex = index + 1;\n if (newIndex > this.buttons.length - 1) {\n this.setFocusToFirst();\n return;\n }\n this.buttons[newIndex].switchTo();\n }\n /**\n * Set focus to previous button (or wrap around).\n * @param {ActionButton} currentBtn\n */\n setFocusToPrevious (currentBtn) {\n const index = this.buttons.indexOf(currentBtn);\n const newIndex = index - 1;\n if (newIndex < 0) {\n this.setFocusToLast();\n return;\n }\n this.buttons[newIndex].switchTo(false);\n }\n /**\n * Set focus to first button.\n */\n setFocusToFirst () {\n this.buttons[0].switchTo();\n }\n /**\n * Set focus to last button.\n */\n setFocusToLast () {\n this.buttons[this.buttons.length - 1].switchTo(false);\n }\n /**\n * Set focus to specific button.\n * @param {ActionButton} button\n */\n setTabFocusToButton (button) {\n this.buttons.forEach((btn) => {\n if (btn === button) {\n btn.switchTo();\n } else {\n btn.removeTabFocus();\n }\n });\n }\n /**\n * Set focus to whatever button was last focused or else the first one.\n */\n focus () {\n let button = this.buttons.find((btn) => {\n return btn.isFocusable();\n });\n if (!button) {\n button = this.buttons[0];\n }\n this.setTabFocusToButton(button);\n }\n}\n\nif (!window.customElements.get('action-menu')) {\n window.customElements.define('action-menu', ActionMenu);\n}\n\nexport default ActionMenu;\n", "/**\n * Container for Definition list pairs used as note header/text.\n */\nimport CharacterNote from '../models/CharacterNote.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n
    \n
    \n`;\n\nclass NoteListItem extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list-item');\n }\n }\n\n /**\n * Get the content (header and text) of the pair.\n * @returns {CharacterNote}\n */\n get content () {\n return new CharacterNote({\n header: this.shadowRoot.querySelector('dt').innerHTML,\n text: this.shadowRoot.querySelector('dd').innerHTML\n });\n }\n /**\n * Set the header and text of the pair.\n * @param {CharacterNote}\n */\n set content (note) {\n // set the content.\n this.shadowRoot.querySelector('dt').innerHTML = note.header;\n this.shadowRoot.querySelector('dd').innerHTML = note.text;\n }\n /**\n * Clear the text.\n */\n clear () {\n this.content = [];\n }\n /**\n * Get the in focus element.\n * @returns {Element}\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n * @param {Boolean} onContent If true focus on the dd instead.\n */\n focus (onContent = false) {\n if (onContent) {\n this.shadowRoot.querySelector('dd').focus();\n return;\n }\n this.shadowRoot.querySelector('dt').focus();\n }\n /**\n * Determine whether NoteListItem is empty, ignoring lead and trailing whitespace\n * @returns true if empty, false otherwise\n */\n isEmpty () {\n if (this.shadowRoot.querySelector('dt').innerText.trim() === '' &&\n this.shadowRoot.querySelector('dd').innerText.trim() === '') {\n return true;\n }\n return false;\n }\n}\n\nwindow.customElements.define('note-list-item', NoteListItem);\n\nexport default NoteListItem;\n", "/**\n * Set the cursor to the end of the content.\n * Call after setting focus on el\n * @param {HTMLElement} el Element that is contenteditable=true\n */\nconst setCursorAtContentEnd = function (el) {\n const theNodes = el.childNodes;\n if (theNodes.length === 0) {\n return;\n }\n const contentRange = document.createRange();\n const windowSelection = window.getSelection();\n // Remove any previously created ranges\n windowSelection.removeAllRanges();\n contentRange.setStartBefore(theNodes[0]);\n contentRange.setEndAfter(theNodes[theNodes.length - 1]);\n contentRange.collapse(false);\n // add the range to a window selection object.\n windowSelection.addRange(contentRange);\n windowSelection.collapseToEnd();\n};\n\nexport default setCursorAtContentEnd;\n", "import NoteListItem from './NoteListItem.js';\nimport CharacterNote from '../models/CharacterNote.js';\nimport setCursorAtContentEnd from '../utils/setCursorAtContentEnd.js';\n\n/**\n * Parent container for Definition list pairs used as note header/text.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n`;\n\nclass NoteList extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes?\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list');\n }\n // add event listeners\n this.addEventListener('keydown', this._keyDown);\n this.addEventListener('blur', this._blur);\n this._upgradeProperty('fieldName');\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.removeEventListener('keydown', this._keyDown);\n this.removeEventListener('blur', this._blur);\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Setter: field name for data.\n */\n set fieldName (value) {\n this.dataset.name = value;\n }\n /**\n * Getter: field name for data.\n */\n get fieldName () {\n return this.dataset.name || '';\n }\n /**\n * Getter: Content of list items.\n * @returns {CharacterNote[]}\n */\n get contentArray () {\n const items = Array.from(this.shadowRoot.querySelectorAll('note-list-item'));\n const array = [];\n items.forEach((item) => {\n const content = item.content;\n // Check if it's empty.\n if (!content.header && !content.text) {\n return;\n }\n array.push(content);\n });\n return array;\n }\n /**\n * Add a new note-list-item.\n * Set its header/text if appropriate.\n * @param {CharacterNote|null} note\n */\n addItem (note = null) {\n const item = new NoteListItem();\n if (note) {\n item.content = note;\n }\n this.shadowRoot.appendChild(item);\n }\n /**\n * Clear out the items.\n */\n clear () {\n Array.from(this.shadowRoot.querySelectorAll('note-list-item')).forEach((item) => {\n this.shadowRoot.removeChild(item);\n });\n }\n /**\n * Get focused element.\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Handler: Enter to move through the items or add new ones.\n * @param {KeyboardEvent} ev Keypress event\n */\n _keyDown (ev) {\n if ((ev.key !== 'Enter' && ev.key !== 'Backspace') || ev.shiftKey) {\n return;\n }\n const el = this.deepActiveElement();\n // Move to next field on enter.\n if (ev.key === 'Enter') {\n ev.preventDefault();\n ev.stopPropagation();\n if (el.tagName === 'DT' || el.closest('dt')) {\n console.log(el);\n // If this is a child of dt we need to handle this differently.\n el.nextElementSibling.focus();\n } else if (el.tagName === 'DD' || el.closest('dd')) {\n console.log(el);\n if (el.parentNode.host === this.shadowRoot.lastElementChild) {\n // Last NoteListItem, so add a new item and focus.\n const newList = new NoteListItem();\n this.shadowRoot.appendChild(newList);\n newList.focus();\n } else {\n const nextList = el.parentNode.host.nextElementSibling;\n if (nextList) {\n nextList.focus();\n }\n }\n }\n return;\n }\n\n if (ev.key === 'Backspace') {\n // trim this in case of line breaks, spaces, etc.\n if (el.innerText.trim() !== '') {\n return;\n }\n ev.preventDefault();\n ev.stopPropagation();\n if (el.tagName === 'DT' || el.closest('dt')) {\n // If it's not the first NoteListItem, move to the previous one's text field.\n if (el.parentNode.host !== this.shadowRoot.querySelector('note-list-item')) {\n const prevItem = el.parentNode.host.previousElementSibling;\n\n if (prevItem) {\n prevItem.focus(true);\n setCursorAtContentEnd(this.deepActiveElement());\n\n // If both NoteListItem fields are empty, delete it\n if (el.parentNode.host.isEmpty()) {\n el.parentNode.host.remove();\n }\n }\n }\n } else if (el.tagName === 'DD' || el.closest('dd')) {\n // NoteListItem focus always goes to the DT.\n el.parentNode.host.focus();\n setCursorAtContentEnd(this.deepActiveElement());\n }\n }\n }\n /**\n * On blur dispatch an event so the character model can be updated.\n * @param {Event} ev\n */\n _blur (ev) {\n const detail = {\n field: this.fieldName,\n value: this.contentArray\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('note-list-item').focus();\n }\n}\n\nwindow.customElements.define('note-list', NoteList);\n\nexport default NoteList;\n", "import setCursorAtContentEnd from '../utils/setCursorAtContentEnd.js';\n\n/**\n * Parent container for a simple list.\n * Add data-number=\"true\" to make it a numbered list.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n`;\n\nclass SimpleList extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes?\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list');\n }\n // add event listeners\n this.addEventListener('keydown', this._keyDown);\n this.addEventListener('blur', this._blur);\n this._upgradeProperty('fieldName');\n this._upgradeProperty('subFieldName');\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.removeEventListener('keydown', this._keyDown);\n this.removeEventListener('blur', this._blur);\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Setter: field name for data.\n */\n set fieldName (value) {\n this.dataset.name = value;\n }\n /**\n * Getter: field name for data.\n */\n get fieldName () {\n return this.dataset.name || '';\n }\n /**\n * Setter: subfield name for data.\n */\n set subFieldName (value) {\n this.dataset.subfield = value;\n }\n /**\n * Getter: subfield name for data.\n */\n get subFieldName () {\n return this.dataset.subfield || '';\n }\n /**\n * Getter: Content of list items.\n */\n get contentArray () {\n const items = Array.from(this.shadowRoot.querySelectorAll('li'));\n const array = [];\n items.forEach((item) => {\n const content = item.innerHTML;\n if (content === '') {\n return;\n }\n array.push(content);\n });\n return array;\n }\n /**\n * Add a new li.\n * Set its text if appropriate.\n * @param {String} content\n * @returns {HTMLLIElement}\n */\n addItem (content = '') {\n const item = document.createElement('li');\n item.setAttribute('contenteditable', true);\n item.innerHTML = content;\n this.shadowRoot.appendChild(item);\n return item;\n }\n /**\n * Clear out the items.\n */\n clear () {\n Array.from(this.shadowRoot.querySelectorAll('li')).forEach((item) => {\n this.shadowRoot.removeChild(item);\n });\n }\n /**\n * Get focused element.\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Handler: Enter to move through the items or add new ones.\n * @param {KeyboardEvent} ev Keypress event\n */\n _keyDown (ev) {\n if ((ev.key !== 'Enter' && ev.key !== 'Backspace') || ev.shiftKey) {\n return;\n }\n const el = this.deepActiveElement();\n if (el.tagName !== 'LI' && !el.closest('li')) {\n return;\n }\n if (ev.key === 'Enter') {\n ev.preventDefault();\n // compare the focused elements parent component node (note-list-item) to the last item in the list.\n if (el === this.shadowRoot.lastElementChild) {\n // Last one so add a new item and focus.\n const newItem = this.addItem();\n newItem.focus();\n } else {\n // Move to the next item.\n const nextItem = el.nextElementSibling;\n if (nextItem) {\n nextItem.focus();\n }\n }\n return;\n }\n if (ev.key === 'Backspace') {\n if (el !== this.shadowRoot.querySelector('li')) {\n if (el.innerText.trim() === '') {\n ev.preventDefault();\n const prevItem = el.previousElementSibling;\n prevItem.focus();\n setCursorAtContentEnd(prevItem);\n el.remove();\n }\n }\n }\n }\n /**\n * On blur dispatch an event so the character model can be updated.\n * @param {Event} ev\n */\n _blur () {\n const detail = {\n field: this.fieldName,\n subfield: this.subFieldName,\n value: this.contentArray\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('li').focus();\n }\n}\n\nif (!window.customElements.get('simple-list')) {\n window.customElements.define('simple-list', SimpleList);\n}\n\nexport default SimpleList;\n", "import setCursorAtContentEnd from '../utils/setCursorAtContentEnd.js';\n\n/**\n * Editable table.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n \n\n\n\n\n`;\n\nclass TableEditable extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.columns = 0;\n }\n\n connectedCallback () {\n // set any default attributes?\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'table');\n }\n // add event listeners\n this.addEventListener('keydown', this._keyDown);\n this.addEventListener('blur', this._blur);\n this._upgradeProperty('fieldName');\n // for now the column names are also the keys of the data.\n this.columnNames = this.getAttribute('columns').split('||');\n this.columns = this.columnNames.length;\n\n const headRow = this.shadowRoot.querySelector('thead tr');\n this.columnNames.forEach((name) => {\n const th = document.createElement('th');\n th.innerHTML = name;\n headRow.appendChild(th);\n });\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.removeEventListener('keydown', this._keyDown);\n this.removeEventListener('blur', this._blur);\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Setter: field name for data.\n */\n set fieldName (value) {\n this.dataset.name = value;\n }\n /**\n * Getter: field name for data.\n */\n get fieldName () {\n return this.dataset.name || '';\n }\n /**\n * Getter: Content of list items.\n */\n get contentArray () {\n const entries = [];\n const rows = Array.from(this.shadowRoot.querySelectorAll('tbody > tr'));\n\n rows.forEach((row) => {\n const cells = Array.from(row.querySelectorAll('td'));\n if (cells.length === 0) {\n return;\n }\n const rowData = {};\n let isEmpty = true;\n cells.forEach((cell, i) => {\n const key = this.columnNames[i].toLowerCase();\n const text = cell.innerHTML.trim();\n if (text !== '') {\n isEmpty = false;\n }\n rowData[key] = text;\n });\n if (isEmpty) {\n return;\n }\n entries.push(rowData);\n });\n return entries;\n }\n /**\n * Add a new row to the table.\n * Set its header/text if appropriate.\n * @param {String[]} array\n * @returns {HTMLTableRowElement}\n */\n addRow (content = []) {\n const row = document.createElement('tr');\n const cell = document.createElement('td');\n cell.setAttribute('contenteditable', true);\n\n for (let i = 0; i < this.columns; i++) {\n const key = this.columnNames[i].toLowerCase();\n const newCell = cell.cloneNode(false);\n newCell.innerHTML = content[key] || '';\n row.appendChild(newCell);\n }\n this.shadowRoot.querySelector('tbody').appendChild(row);\n return row;\n }\n /**\n * Clear out the body rows.\n */\n clear () {\n Array.from(this.shadowRoot.querySelectorAll('tbody > tr')).forEach((row) => {\n row.parentNode.removeChild(row);\n });\n }\n /**\n * Get focused element.\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Handler: Enter to move through the items or add new ones.\n * @param {KeyboardEvent} ev Keydown event\n */\n _keyDown (ev) {\n if ((ev.key !== 'Enter' && ev.key !== 'Backspace') || ev.shiftKey) {\n return;\n }\n const el = this.deepActiveElement();\n if (el.tagName !== 'TD' && !el.closest(`td`)) {\n return;\n }\n const td = el.tagName === 'TD' ? el : el.closest(`td`);\n const row = td.parentElement;\n if (ev.key === 'Enter') {\n ev.preventDefault();\n\n if (td !== row.lastElementChild) {\n const nextCell = td.nextElementSibling;\n if (nextCell) {\n nextCell.focus();\n }\n return;\n }\n const nextRow = row.nextElementSibling;\n if (nextRow) {\n nextRow.querySelector('td').focus();\n return;\n }\n const newRow = this.addRow();\n newRow.querySelector('td').focus();\n return;\n }\n if (ev.key === 'Backspace') {\n if (td.innerText.trim() !== '') {\n return;\n }\n ev.preventDefault();\n // if it's not the first cell, move to the previous cell.\n if (td !== row.firstElementChild) {\n const prevCell = td.previousElementSibling;\n if (prevCell) {\n prevCell.focus();\n setCursorAtContentEnd(prevCell);\n }\n return;\n }\n // it is the first cell.\n // if there is a prev row, move to its last cell, delete current row if it's empty.\n const prevRow = row.previousElementSibling;\n if (prevRow) {\n prevRow.lastElementChild.focus();\n setCursorAtContentEnd(prevRow.lastElementChild);\n let delRow = true;\n row.querySelectorAll('td').forEach((c) => {\n if (c.innerText.trim() !== '') {\n delRow = false;\n }\n });\n if (delRow) {\n row.remove();\n }\n }\n }\n }\n /**\n * On blur dispatch an event so the character model can be updated.\n * @param {Event} ev\n */\n _blur (ev) {\n const detail = {\n field: this.fieldName,\n value: this.contentArray\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('[contenteditable=true]').focus();\n }\n}\n\nwindow.customElements.define('table-editable', TableEditable);\n\nexport default TableEditable;\n", "/**\n * Container for skill check boxes and data.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n0\n\n`;\n\nclass SkillListing extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list-item');\n }\n\n this.profCheck = this.shadowRoot.querySelector('input[data-name=\"skills\"]');\n this.expertCheck = this.shadowRoot.querySelector('input[data-name=\"expert\"]');\n // add event listeners\n this.profCheck.addEventListener('change', this._checkSkills.bind(this));\n this.expertCheck.addEventListener('change', this._checkExpert.bind(this));\n this.shadowRoot.querySelector('button').addEventListener('click', this._skillCheck.bind(this));\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.profCheck.removeEventListener('change', this._checkSkills.bind(this));\n this.expertCheck.removeEventListener('change', this._checkExpert.bind(this));\n this.shadowRoot.querySelector('button').removeEventListener('click', this._skillCheck.bind(this));\n }\n /**\n * Name of the skill based on the data-subfield attribute.\n * @returns {String}\n */\n get skillName () {\n return this.dataset.subfield || '';\n }\n /**\n * Set skill name.\n * @param {String} val\n */\n set skillName (val) {\n this.dataset.subfield = val;\n }\n get skillLabel () {\n return this.shadowRoot.querySelector('.pc-skill-name').innerHTML;\n }\n /**\n * Set human readable label\n * @param {String} val\n */\n set skillLabel (val) {\n this.shadowRoot.querySelector('.pc-skill-name').innerHTML = val;\n }\n\n get skillValue () {\n if (!this.profCheck.checked) {\n return 0;\n }\n return this.expertCheck.checked ? 2 : 1;\n }\n /**\n * Set skill proficiency/expert status.\n * @param {Number} val\n */\n set skillValue (val) {\n this.profCheck.checked = false;\n this.expertCheck.checked = false;\n if (val > 0) {\n this.profCheck.checked = true;\n this.expertCheck.disabled = false;\n }\n if (val > 1) {\n this.expertCheck.checked = true;\n }\n }\n get skillMod () {\n return this.shadowRoot.querySelector('.pc-skill-mod').innerHTML;\n }\n /**\n * Set the skill modifiter.\n * @param {String} mod\n */\n set skillMod (mod) {\n this.shadowRoot.querySelector('.pc-skill-mod').innerHTML = mod;\n }\n /**\n * Handler when proficiency is (un)checked.\n * @param {Event} ev\n */\n _checkSkills (ev) {\n // change event for checkboxes\n // check data-name of check.\n const expert = this.expertCheck;\n if (!ev.target.checked) {\n expert.checked = false;\n expert.disabled = true;\n } else {\n expert.disabled = false;\n }\n\n const detail = {\n field: 'skills',\n subfield: this.skillName,\n value: ev.target.checked ? 1 : 0\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Handler when expert is (un)checked.\n * @param {Event} ev\n */\n _checkExpert (ev) {\n // change event for checkboxes\n // check data-name of check.\n const detail = {\n field: 'skills',\n subfield: this.skillName,\n value: ev.target.checked ? 2 : 1\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Roll a skill check.\n * @param {ClickEvent} ev\n */\n _skillCheck (ev) {\n const roller = document.querySelector('sheet-view-5e').shadowRoot.querySelector('dice-roller');\n if (!roller) {\n return;\n }\n const mod = this.skillMod;\n const die = `1d20${mod !== '0' ? mod : ''}`;\n roller.roll(die);\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('input').focus();\n }\n}\n\nwindow.customElements.define('skill-listing', SkillListing);\n\nexport default SkillListing;\n", "/**\n * Attribute score/bonus/saves.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n0\n\n0\n\n`;\n\nclass AttributeListing extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list-item');\n }\n\n this.scoreInput = this.shadowRoot.querySelector('input.pc-attribute');\n this.saveCheck = this.shadowRoot.querySelector('input[name=\"pc-save\"]');\n\n // add event listeners\n this.saveCheck.addEventListener('change', this._checkSave.bind(this));\n this.scoreInput.addEventListener('change', this._scoreUpdate.bind(this));\n this.shadowRoot.querySelector('button').addEventListener('click', this._savingThrow.bind(this));\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.saveCheck.removeEventListener('change', this._checkSave.bind(this));\n this.scoreInput.removeEventListener('change', this._scoreUpdate.bind(this));\n this.shadowRoot.querySelector('button').removeEventListener('click', this._savingThrow.bind(this));\n }\n /**\n * Name of the skill based on the data-name attribute.\n * @returns {String}\n */\n get attributeName () {\n return this.dataset.name || '';\n }\n /**\n * Set attribute name.\n * @param {String} val\n */\n set attributeName (val) {\n this.dataset.name = val;\n }\n /**\n * Get current attribute score.\n * @returns {Number}\n */\n get attributeScore () {\n return parseInt(this.scoreInput.value, 10);\n }\n /**\n * Set the attribute score.\n * @param {Number} val\n */\n set attributeScore (val) {\n this.scoreInput.value = val;\n }\n /**\n * Get if the save is proficient.\n * @returns {Number}\n */\n get saveProficiency () {\n return this.saveCheck.checked ? 1 : 0;\n }\n /**\n * Check (or not) the save proficiency.\n * @param {Number} val\n */\n set saveProficiency (val) {\n this.saveCheck.checked = (val);\n }\n /**\n * Set the attribute modifier.\n * @param {String} val\n */\n set attributeMod (val) {\n this.shadowRoot.querySelector('.pc-attribute-mod').innerHTML = val;\n }\n\n get saveMod () {\n return this.shadowRoot.querySelector('.pc-save-mod').innerHTML;\n }\n /**\n * Set the save modifier.\n * @param {String} mod\n */\n set saveMod (mod) {\n this.shadowRoot.querySelector('.pc-save-mod').innerHTML = mod;\n }\n /**\n * Handler: Change event on saves.\n * @param {Event} ev\n */\n _checkSave (ev) {\n const detail = {\n field: this.attributeName,\n value: ev.target.checked ? 1 : 0\n };\n this.dispatchEvent(new CustomEvent('saveChange', { bubbles: true, detail }));\n }\n /**\n * Handler: Change event on number input.\n * @param {Event} ev\n */\n _scoreUpdate (ev) {\n const detail = {\n field: this.attributeName,\n value: ev.target.value\n };\n this.dispatchEvent(new CustomEvent('attributeChange', { bubbles: true, detail }));\n }\n /**\n * Roll a saving throw.\n * @param {ClickEvent} ev\n */\n _savingThrow (ev) {\n const roller = document.querySelector('sheet-view-5e').shadowRoot.querySelector('dice-roller');\n if (!roller) {\n return;\n }\n const mod = this.saveMod;\n const die = `1d20${mod !== '0' ? mod : ''}`;\n roller.roll(die);\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('input').focus();\n }\n}\n\nwindow.customElements.define('attr-listing', AttributeListing);\n\nexport default AttributeListing;\n", "/**\n * Sum an array\n * @param {Array} arr an array of numbers\n * @returns {Number} Total value of numbers in array\n */\nconst arraySum = function (arr) {\n let total = 0;\n for (let i = 0; i < arr.length; i++) {\n const v = parseFloat(arr[i]);\n if (!isNaN(v)) {\n total += v;\n }\n }\n return total;\n};\n\n/**\n * Random integer between two numbers (stolen from underscorejs)\n * @param {Number} [min=0] mininum value\n * @param {Number} [max=null] maximum value\n * @returns {Number} random value\n */\nconst randomInteger = function (min = 0, max = null) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n};\n\n/**\n * Random value selection\n * @param {Array} values an array of objects from which to choose\n * @param {Array} weights a matching array of integers to weight the values (i.e. values and weights are in the same order)\n * @returns {String} the randomly selected Array element from values param\n */\nconst getWeightedRandom = function (values, weights) {\n let n = 0;\n const num = randomInteger(1, arraySum.call(this, weights));\n let i = 0;\n for (i; i < values.length; i++) {\n n = n + weights[i];\n if (n >= num) {\n break;\n }\n }\n return values[i];\n};\n/**\n * Random value selection, wrapper for getWeightedRandom that processes the data into values/weights arrays\n * @param {String[]} data values\n * @returns {String|null} the randomly selected string\n */\nconst randomString = function (data) {\n const values = [];\n const weights = [];\n\n if (!Array.isArray(data) || data.length === 0) {\n return null;\n }\n data.forEach((entry) => {\n weights.push(1);\n values.push(entry);\n });\n\n return getWeightedRandom(values, weights);\n};\n\nexport {\n randomInteger,\n getWeightedRandom,\n randomString\n};\n", "/* eslint-disable no-useless-escape */\nimport { randomInteger } from './randomizer.js';\n\n/**\n * @prop {String} die Die notation.\n * @prop {Number} value Random roll for the die notation.\n */\nclass DiceResult {\n constructor ({\n die = '',\n value = 0\n }) {\n this.die = die;\n this.value = value;\n }\n toString () {\n return this.value;\n }\n toJSON () {\n return {\n className: 'DiceResult',\n die: this.die,\n value: this.value\n };\n }\n}\n\nclass DiceRoller {\n /**\n *\n * @param {Number} die Die type\n * @returns {Number}\n */\n getSingleDieResult (die) {\n return randomInteger(1, die);\n }\n /**\n * Apply a modifier to the number of dice retained.\n * @param {Number[]} rolls\n * @param {String} diemod Modifier to dice (drop/keep high/low count).\n * @returns\n */\n applyDieMod (rolls, diemod) {\n const m = diemod.match(/^([dklh]{2})([0-9]*)$/);\n if (m === null) {\n return rolls;\n }\n const count = !m[2] ? 1 : parseInt(m[2]);\n switch (m[1]) {\n case 'dl':\n // Sort ascending\n rolls.sort((a, b) => a - b);\n rolls.splice(0, count);\n return rolls;\n case 'dh':\n // Sort descending\n rolls.sort((a, b) => b - a);\n rolls.splice(0, count);\n return rolls;\n case 'kl':\n // Sort ascending\n rolls.sort((a, b) => a - b);\n return rolls.slice(0, count);\n case 'kh':\n // Sort descending\n rolls.sort((a, b) => b - a);\n return rolls.slice(0, count);\n default:\n return rolls;\n }\n }\n /**\n * Dice rolling simulator\n * @param {Number} [die=6] Die type\n * @param {Number} [number=1] Number of times to roll the die\n * @param {Number} [modifier=0] Numeric modifier to dice total\n * @param {String} [mod_op=+] Operator for the modifier (+,-,/,*)\n * @param {String} [diemod=''] Modifier to the dice (like keep/drop high/low die)\n * @returns {Number} Number rolled (die*number [mod_op][modifier])\n */\n _parseDiceNotation (die = 6, number = 1, modifier = 0, mod_op = '+', diemod = '') {\n modifier = parseInt(modifier, 10);\n die = parseInt(die, 10);\n\n if (number <= 0) {\n number = 1;\n } else {\n number = parseInt(number, 10);\n }\n\n let rolls = [];\n for (let i = 1; i <= number; i++) {\n rolls.push(this.getSingleDieResult(die));\n }\n\n if (diemod !== '') {\n rolls = this.applyDieMod(rolls, diemod);\n }\n let sum = 0;\n if (rolls.length > 0) {\n sum = rolls.reduce((total, cur) => {\n return total + cur;\n });\n }\n if (modifier === 0) {\n return sum;\n }\n\n switch (mod_op) {\n case '*':\n sum = sum * modifier;\n break;\n case '-':\n sum = sum - modifier;\n break;\n case '/':\n sum = sum / modifier;\n break;\n case '+':\n default:\n sum = sum + modifier;\n break;\n }\n return Math.round(sum);\n }\n /**\n * takes a string like '3d6+2', 'd6', '2d6', parses it, and puts it through roll\n * @params {String} string a die roll notation\n * @returns {Number} the result of the roll\n */\n rollDie (string = '') {\n string = string.trim();\n const m = string.match(/^([0-9]*)d([0-9]+)([dklh]{2}[0-9]*)*(?:([\\+\\-\\*\\/])([0-9]+))*$/);\n if (!m) {\n return '';\n }\n return this._parseDiceNotation(m[2], m[1], m[5], m[4], m[3]);\n }\n /**\n * Return a dice result.\n * @param {String} die Die roll notation.\n * @returns {DiceResult}\n */\n getDiceResult (die = '') {\n return new DiceResult({\n die,\n value: this.rollDie(die)\n });\n }\n}\n\n/**\n * takes a string like '3d6+2', 'd6', '2d6', parses it, and puts it through roll\n * @params {String} string a die roll notation\n * @returns {Number} the result of the roll\n */\nconst rollDie = function (string = '') {\n const roller = new DiceRoller();\n return roller.rollDie(string);\n};\n\n/**\n * Return a dice result.\n * @param {String} die Die roll notation.\n * @returns {DiceResult}\n */\nconst getDiceResult = function (die = '') {\n const roller = new DiceRoller();\n return new DiceResult({\n die,\n value: roller.rollDie(die)\n });\n};\n\nexport {\n rollDie,\n DiceResult,\n getDiceResult,\n DiceRoller\n};\nexport default DiceRoller;\n", "/**\n * Class for handling dragging an HTMLElement around the screen.\n *\n * @prop {Number} _startX X coordinate in pixels of drag event when it starts.\n * @prop {Number} _startY Y coordinate in pixels of drag event when it starts.\n * @prop {Number} _startPosX Offset in pixels for the Element when drag starts.\n * @prop {Number} _startPosY Offset in pixels for the Element when drag starts.\n * @prop {Number} _startWidth Starting width of element for resize.\n * @prop {Number} _startHeight Starting height of element for resize.\n * @prop {Boolean} enabled Are dragging events currently enabled.\n * @prop {Function} doDragCallback Bound callback for the drag event.\n * @prop {Function} stopDragCallback Bound callback for the stop drag event.\n * @prop {Function} doResizeCallback Bound callback for the resize event.\n * @prop {Function} stopResizeCallback Bound callback for the stop resize event.\n * @prop {Function} callbackStartDrag Custom callback for when a drag starts. Passed the: dragElement, handleSelector.\n */\nexport default class Dragger {\n /**\n * @prop {HTMLElement} dragElement Element to drag around.\n * @prop {String} handleSelector Selector for the child element inside dragElement which activates dragging. Don't make this a button.\n */\n constructor ({\n dragElement = null,\n handleSelector = null\n }) {\n this.dragElement = dragElement;\n if (!(this.dragElement instanceof HTMLElement)) {\n throw new Error('Dragger.dragElements must be HTMLElement');\n }\n this.handleSelector = handleSelector;\n\n // By binding all these we make sure they can be removed properly.\n this.initDragBound = this.initDrag.bind(this);\n this.doDragCallback = this.doDrag.bind(this);\n this.stopDragCallback = this.stopDrag.bind(this);\n\n this._startX = null;\n this._startY = null;\n this._startPosX = null;\n this._startPosY = null;\n this._startWidth = null;\n this._startHeight = null;\n this.enabled = false;\n this.callbackStartDrag = null;\n }\n /**\n * Get the x position of the mouse/touch.\n * @param {Event} ev Drag or touch Event\n * @return {Number}\n */\n getEventX (ev) {\n return (ev.type.toLowerCase().indexOf('touch') === 0) ? ev.touches[0].clientX : ev.clientX;\n }\n /**\n * Get the y position of the mouse/touch.\n * @param {Event} ev Drag or touch Event\n * @return {Number}\n */\n getEventY (ev) {\n return (ev.type.toLowerCase().indexOf('touch') === 0) ? ev.touches[0].clientY : ev.clientY;\n }\n /**\n * Move the box as we drag\n * @param {Event} ev Drag or touch Event\n */\n doDrag (ev) {\n ev.preventDefault();\n // Adjust the node coords based on how much the event moved.\n this.dragElement.coords = [\n this._startPosX + (this.getEventX(ev) - this._startX),\n this._startPosY + (this.getEventY(ev) - this._startY)\n ];\n }\n /**\n * Stop the drag, make sure the box is visible, clean up.\n */\n stopDrag () {\n // make sure it isn't off the map.\n if (typeof this.dragElement.adjustForParentBounds === 'function') {\n this.dragElement.adjustForParentBounds();\n }\n // save it's location now that the drag is over.\n if (typeof this.dragElement.saveCoords === 'function') {\n this.dragElement.saveCoords();\n }\n document.documentElement.removeEventListener('mousemove', this.doDragCallback, false);\n document.documentElement.removeEventListener('touchmove', this.doDragCallback, false);\n document.documentElement.removeEventListener('mouseup', this.stopDragCallback, false);\n document.documentElement.removeEventListener('touchend', this.stopDragCallback, false);\n }\n /**\n * Start a drag action\n * @param {Event} ev Event for mouse down or touchstart\n */\n initDrag (ev) {\n // Stop on center/right clicks.\n if (ev.button > 1) {\n return;\n }\n ev.preventDefault();\n ev.stopPropagation();\n this._startX = this.getEventX(ev);\n this._startY = this.getEventY(ev);\n [this._startPosX, this._startPosY] = this.dragElement.coords;\n if (this.callbackStartDrag !== null) {\n this.callbackStartDrag(this.dragElement, this.handleSelector);\n }\n document.documentElement.addEventListener('mousemove', this.doDragCallback, false);\n document.documentElement.addEventListener('touchmove', this.doDragCallback, false);\n document.documentElement.addEventListener('mouseup', this.stopDragCallback, false);\n document.documentElement.addEventListener('touchend', this.stopDragCallback, false);\n }\n /**\n * Remove events stop dragging from working.\n */\n disableDrag () {\n if (!this.enabled) {\n return;\n }\n this.dragElement.removeEventListener('mousedown', this.initDragBound, false);\n this.dragElement.removeEventListener('touchstart', this.initDragBound, false);\n const dragHandle = this.handleSelector === ''\n ? this.dragElement\n : this.dragElement.querySelector(this.handleSelector);\n if (dragHandle !== null) {\n dragHandle.style.cursor = 'auto';\n }\n this.enabled = false;\n }\n /**\n * Re-add events starts dragging working again.\n */\n enableDrag () {\n if (this.enabled) {\n return;\n }\n this.dragElement.addEventListener('mousedown', this.initDragBound, false);\n this.dragElement.addEventListener('touchstart', this.initDragBound, false);\n const dragHandle = this.handleSelector === ''\n ? this.dragElement\n : this.dragElement.querySelector(this.handleSelector);\n if (dragHandle !== null) {\n dragHandle.style.cursor = 'move';\n }\n this.enabled = true;\n }\n};\n", "import Dragger from '../utils/dragger.js';\nimport { randomInteger } from 'rpg-table-randomizer/src/randomizer.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n
    \n\n\n`;\n\nclass Die extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.resultDiv = this.shadowRoot.querySelector('div');\n // Default to d6\n this._die = '1d6';\n // Default to empty\n this._result = '';\n this._coords = [0, 0];\n }\n connectedCallback () {\n this.removeButton = this.shadowRoot.querySelector('button.btn-remove');\n this.dragger = new Dragger({\n dragElement: this\n });\n\n this._upgradeProperty('die');\n this._upgradeProperty('result');\n this._upgradeProperty('coords');\n this._updateLabels();\n this.removeButton.addEventListener('click', this.remove.bind(this));\n const [x1, y1] = this.coords;\n if (x1 === 0 && y1 === 0) {\n // Offset from the parent roller.\n // @todo code to avoid collisions, particular with the \"roller\"\n // offset from the dice-roller parent.\n let { x, y } = this.getRootNode().host.getBoundingClientRect();\n x = x + randomInteger(-200, 200);\n y = y + randomInteger(-200, 200);\n this.coords = [x, y];\n }\n this.dragger.enableDrag();\n }\n disconnectedCallback () {\n this.removeButton.removeEventListener('click', this.remove.bind(this));\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Update accessible label on component\n */\n _updateLabels () {\n this.setAttribute('aria-label', `${this.die} roll result: ${this.result}`);\n this.shadowRoot.querySelector('small').innerText = `${this.die}`;\n }\n\n get die () {\n return this._die;\n }\n set die (value) {\n // Should this validate?\n this._die = value;\n this._updateLabels();\n }\n\n get result () {\n return this._result;\n }\n set result (value) {\n this._result = value;\n this.resultDiv.innerText = this._result;\n this._updateLabels();\n }\n\n get coords () {\n return this._coords;\n }\n\n set coords ([x, y]) {\n // @todo this could be cleaned up a lot.\n if (x < 0) {\n x = 0;\n }\n if (x > window.innerWidth) {\n x = window.innerWidth - this.offsetWidth;\n }\n if (y < 0) {\n y = 0;\n }\n if (y > window.innerHeight) {\n y = window.innerHeight - this.offsetHeight;\n }\n this._coords = [x, y];\n this.style.left = `${x}px`;\n this.style.top = `${y}px`;\n this.style.bottom = 'auto';\n this.style.right = 'auto';\n }\n /**\n * Remove the die.\n */\n remove () {\n this.dispatchEvent(\n new CustomEvent(\n 'dice:remove',\n {\n bubbles: true,\n detail: {\n die: this\n }\n }\n )\n );\n }\n}\n\nif (!window.customElements.get('dice-single')) {\n window.customElements.define('dice-single', Die);\n}\n\nexport default Die;\n", "import { getDiceResult, DiceResult } from 'rpg-table-randomizer/src/dice_roller.js';\nimport Die from './Die.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n
    \n\n`;\n\nclass DiceRoller extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this._dice = [];\n }\n connectedCallback () {\n this.resultDiv = this.shadowRoot.getElementById('dice-result');\n this.resetButton = this.shadowRoot.querySelector('button.btn-reset');\n\n this._upgradeProperty('dice');\n\n // Remove event from child Die elements.\n this.shadowRoot.addEventListener('dice:remove', this._removeDie.bind(this));\n // Click handler for slotted buttons\n Array.from(this.children).forEach((buttons) => {\n buttons.addEventListener('click', this._handleRoll.bind(this));\n });\n // Clear all dice\n this.resetButton.addEventListener('click', this.reset.bind(this));\n }\n disconnectedCallback () {\n this.shadowRoot.removeEventListener('dice:remove', this._removeDie.bind(this));\n Array.from(this.children).forEach((buttons) => {\n buttons.removeEventListener('click', this._handleRoll.bind(this));\n });\n this.resetButton.removeEventListener('click', this.reset.bind(this));\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Roll a result from an internal event\n * @param {Event} ev Click event on element.\n */\n _handleRoll (ev) {\n const button = ev.target;\n const die = button.dataset.die || '';\n const roll = getDiceResult(`${die}`);\n this._addDie(roll);\n }\n /**\n * Handle roll from external to the component.\n * @param {String} die\n */\n roll (die = '1d6') {\n const roll = getDiceResult(die);\n this._addDie(roll);\n }\n /**\n * @returns {Die[]}\n */\n get dice () {\n return this._dice;\n }\n /**\n * Resets dice to passed ones.\n * @param {Die[]} value\n */\n set dice (value) {\n if (!Array.isArray(value)) {\n throw Error('Dice must be array');\n }\n this._dice = value;\n this.resultDiv.innerHTML = '';\n this._dice.forEach((die) => {\n if (!(die instanceof Die)) {\n return;\n }\n this.resultDiv.appendChild(die);\n });\n }\n /**\n * @param {DiceResult} diceResult\n */\n _addDie (diceResult) {\n const die = new Die();\n die.die = diceResult.die;\n die.result = diceResult.value;\n this._dice.push(die);\n this.resultDiv.appendChild(die);\n }\n /**\n * @param {CustomEvent} ev\n */\n _removeDie (ev) {\n ev.stopImmediatePropagation();\n const die = ev.detail.die || null;\n if (!die) {\n return;\n }\n const index = this._dice.findIndex((d) => d === die);\n if (index < 0) {\n return;\n }\n const dieEl = this._dice[index];\n this.resultDiv.removeChild(dieEl);\n this._dice.splice(index, 1);\n // this.dice = this.dice.filter((d) => d !== die);\n }\n /**\n * Reset the rolls\n */\n reset () {\n this.dice = [];\n }\n}\n\nif (!window.customElements.get('dice-roller')) {\n window.customElements.define('dice-roller', DiceRoller);\n}\n\nexport default DiceRoller;\n", "/**\n * Simple Editable field.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n`;\n\nclass EditableField extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n if (this.hasAttribute('placeholder')) {\n this.placeholderText = this.getAttribute('placeholder');\n }\n\n // add event listeners\n this.addEventListener('blur', this._blur);\n this._upgradeProperty('fieldName');\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.removeEventListener('blur', this._blur);\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Setter: field name for data.\n */\n set fieldName (value) {\n this.dataset.name = value;\n }\n /**\n * Getter: field name for data.\n */\n get fieldName () {\n return this.dataset.name || '';\n }\n get placeholderText () {\n this.shadowRoot.querySelector('span').getAttribute('placeholder');\n }\n /**\n * Set placeholder text in the field.\n */\n set placeholderText (val) {\n this.shadowRoot.querySelector('span').setAttribute('placeholder', val);\n }\n /**\n * Getter: Content of field.\n * @returns {String}\n */\n get content () {\n return this.shadowRoot.querySelector('span').innerHTML;\n }\n /**\n * Setter: Content of field.\n * @param {String} value\n */\n set content (value) {\n this.shadowRoot.querySelector('span').innerHTML = value;\n }\n /**\n * On blur dispatch an event so the character model can be updated.\n * @param {Event} ev\n */\n _blur (ev) {\n let currentVal = this.content;\n // Trim empty end spaces/line breaks\n currentVal = currentVal.trim().replace(/(\\s| |)+$/, '');\n this.content = currentVal;\n const detail = {\n field: this.fieldName,\n value: currentVal\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Focus\n */\n focus () {\n this.shadowRoot.querySelector('[contenteditable=true]').focus();\n }\n}\n\nwindow.customElements.define('field-editable', EditableField);\n\nexport default EditableField;\n", "/**\n * Navigation links for page/tabs.\n * Dynamically updates depending on SheetView type.\n */\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n
      \n
    1. Top
    2. \n
    \n`;\n\nclass FooterNav extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.setAttribute('role', 'navigation');\n this.setAttribute('aria-label', 'Character sheet tab/section navigation');\n this.list = this.shadowRoot.querySelector('ol');\n this.topLink = this.shadowRoot.querySelector('li:first-child');\n\n this.shadowRoot.addEventListener('click', this._handleClicks.bind(this));\n }\n\n _handleClicks (ev) {\n if (ev.target.tagName === 'A') {\n ev.preventDefault();\n const link = ev.target;\n const targetPane = link.dataset.tab;\n\n const sheetView = document.querySelector('[data-sheetview]');\n if (targetPane) {\n sheetView.switchToPane(targetPane);\n }\n const target_id = link.getAttribute('href');\n sheetView.navigateTo(target_id);\n }\n }\n /**\n * Set links in header.\n * @param {Object[]} links\n */\n setLinks (links) {\n links.forEach((link) => {\n const li = document.createElement('li');\n const a = document.createElement('a');\n a.href = link.href || '';\n a.innerText = link.label || '';\n a.dataset.tab = link.tab || '';\n li.appendChild(a);\n this.list.appendChild(li);\n });\n }\n /**\n * Remove all but the top link.\n */\n removeLinks () {\n this.shadowRoot.querySelectorAll('li').forEach((el) => {\n if (el === this.topLink) {\n return;\n }\n el.parentNode.removeChild(el);\n });\n }\n}\n\nif (!window.customElements.get('footer-nav')) {\n window.customElements.define('footer-nav', FooterNav);\n}\n\nexport default FooterNav;\n", "/**\n * Modal.\n */\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n

    \n\n `;\n\nclass Modal extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.setAttribute('role', 'dialog');\n this.setAttribute('aria-labelledby', 'modal-label');\n\n this.boundOutsideClickClose = function () {};\n this.boundKeyboardEvents = function () {};\n this.opener = null;\n this.addEventListener('click', this.handleCloseClick);\n }\n\n connectedCallback () {\n }\n\n disconnectedCallback () {\n }\n\n get header () {\n return this.shadowRoot.querySelector('slot[name=\"header\"]').innerHTML;\n }\n set header (html) {\n this.shadowRoot.querySelector('slot[name=\"header\"]').innerHTML = html;\n }\n /**\n * Is the modal open or not\n */\n get isOpen () {\n return !this.hidden;\n }\n /**\n * Return a close button to use\n * @returns {HTMLElement} button.close\n */\n getCloseButton () {\n const button = document.createElement('button');\n button.setAttribute('type', 'button');\n button.classList.add('close');\n button.textContent = 'Close';\n button.setAttribute('slot', 'content');\n return button;\n }\n /**\n * Adapted from https://github.com/salesforce/kagekiri\n * Get children of a node, including getting slotted content.\n * @param {HTMLElement} node\n * @returns HTMLCollection|HTMLElement[]\n */\n getChildren (node) {\n // is it a slot.\n if (typeof node.assignedElements === 'function') {\n const assigned = node.assignedElements();\n // slotted content or the default\n return assigned.length ? assigned : node.children;\n } else {\n return node.children;\n }\n }\n /**\n * Is an element focusable.\n * This probably doesn't cover ALL possibilities, but its a decent start.\n * @param {HTMLElement} element\n * @param {Boolean} keyboardOnly Are we only looking for tabbable focus.\n */\n isFocusable (element, keyboardOnly = false) {\n const tagName = element.tagName;\n // Just in case.\n if (tagName === undefined) {\n return false;\n }\n // Will be false-y if not set/available.\n const disabled = element.disabled;\n // Convert to integer or NaN if tabindex is not set.\n const tabIndex = parseInt(element.getAttribute('tabindex'), 10);\n const contentEditable = element.getAttribute('contenteditable');\n\n switch (tagName) {\n case 'INPUT':\n case 'TEXTAREA':\n case 'SELECT':\n case 'BUTTON':\n case 'A':\n if (tabIndex === -1) {\n return false;\n }\n if (disabled) {\n return false;\n }\n if (tagName === 'A' && !element.href) {\n return false;\n }\n return true;\n default:\n if (keyboardOnly && tabIndex >= 0) {\n return true;\n } else if (!keyboardOnly && tabIndex >= -1) {\n return true;\n }\n if (contentEditable === 'true') {\n return true;\n }\n }\n return false;\n }\n /**\n * Get focusable elements recursively.\n * @param {HTMLElement} element\n * @param {Boolean} keyboardOnly Only tabbable elements?\n * @param {Boolean} single Only get the first one.\n * @returns\n */\n getFocusableChildren (element, keyboardOnly = false, single = false) {\n let focusables = [];\n const children = Array.from(this.getChildren(element));\n if (children.length === 0) {\n return focusables;\n }\n for (const child of children) {\n // check if element is focusable.\n if (this.isFocusable(child, keyboardOnly)) {\n focusables.push(child);\n if (single) {\n return focusables;\n }\n }\n const childFocusables = this.getFocusableChildren(child, keyboardOnly, single);\n if (single && childFocusables.length === 1) {\n return childFocusables;\n }\n focusables = focusables.concat(childFocusables);\n }\n return focusables;\n }\n /**\n * Get focusable elements in the component\n * Shadow DOM and slotted elements\n * Theoretically in the correct order.\n * @param {Boolean} keyboardOnly Only tabbable elements?\n * @param {Boolean} single Only get the first one.\n * @returns {HTMLElement[]}\n */\n findFocusables (keyboardOnly = false, single = false) {\n return this.getFocusableChildren(this.shadowRoot, keyboardOnly, single);\n }\n /**\n * Get the first focusable element in the modal.\n * @returns {HTMLElement|null}\n */\n findFirstFocusable () {\n return this.findFocusables(false, true).shift();\n }\n /**\n * Get the first tabbing focusable element in the modal.\n * @returns {HTMLElement|null}\n */\n findFirstTabFocusable () {\n return this.findFocusables(true, true).shift();\n }\n /**\n * Return last focusable element in the modal.\n * @returns {HTMLElement|null}\n */\n findLastTabFocusable () {\n const focusables = this.findFocusables(true);\n return focusables[focusables.length - 1];\n }\n /**\n * Find first focusable element in modal and focus on it.\n */\n focusFirst () {\n const focusable = this.findFirstFocusable();\n if (focusable) {\n focusable.focus();\n }\n }\n /**\n * Handler: Clicks outside modal close the modal.\n * Bound to this then listens on document.\n * @param {MouseEvent} ev Click event.\n */\n outsideClickClose (ev) {\n const close = ev.target.closest('modal-mib');\n if (close === null) {\n if (ev.target.classList.contains('btn-dialog')) {\n return;\n }\n // Hide the help.\n this.close();\n this.clear();\n }\n }\n /**\n * Get focused element.\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Handler: Keyboard events to:\n * - Close on Esc\n * - Trap tab focus into modal.\n * @param {KeyboardEvent} ev Keydown event\n */\n keyboardEvents (ev) {\n if (ev.key === 'Escape') {\n this.close();\n return;\n }\n if (ev.key !== 'Tab') {\n return;\n }\n // Get current active/focused element.\n const currentEl = this.deepActiveElement();\n if (ev.shiftKey) {\n // Shift tab, only concerned with first element.\n if (currentEl === this.findFirstFocusable() || currentEl === this.findFirstTabFocusable()) {\n // Go to the last element in the modal.\n const focusable = this.findLastTabFocusable();\n if (focusable) {\n ev.preventDefault();\n focusable.focus();\n }\n }\n return;\n }\n // Tab (no shift), only concerned with last element.\n if (currentEl === this.findLastTabFocusable()) {\n // Go to the first element in the modal.\n const focusable = this.findFirstTabFocusable();\n if (focusable) {\n ev.preventDefault();\n focusable.focus();\n }\n }\n }\n /**\n * Open/show Modal\n */\n open () {\n if (this.isOpen) {\n return;\n }\n /**\n * Get the opener trigger (usually a button/link).\n */\n this.opener = this.deepActiveElement();\n this.hidden = false;\n this.focusFirst();\n // We need to do this to be able to remove the listener later.\n this.boundOutsideClickClose = this.outsideClickClose.bind(this);\n document.addEventListener('click', this.boundOutsideClickClose, true);\n this.boundKeyboardEvents = this.keyboardEvents.bind(this);\n document.addEventListener('keydown', this.boundKeyboardEvents, true);\n }\n /**\n * Close the modal.\n * Return focus to whatever opened it.\n */\n close () {\n this.hidden = true;\n // Remove click handler to close modal.\n document.removeEventListener('click', this.boundOutsideClickClose, true);\n document.removeEventListener('keydown', this.boundKeyboardEvents, true);\n if (this.opener) {\n this.opener.focus();\n }\n }\n /**\n * Clear the modal, by removing the slotted elements in the light DOM\n * Leaves the shadow DOM alone so we can reslot.\n */\n clear () {\n while (this.firstChild) {\n this.removeChild(this.firstChild);\n }\n }\n /**\n * Close and clear contents.\n */\n closeClear () {\n this.close();\n this.clear();\n }\n /**\n * Handler clicks in the modal.\n * If it's the close button then close the modal.\n * @param {Event} ev Click event\n */\n handleCloseClick (ev) {\n if (ev.target.classList.contains('close')) {\n // Close button click\n ev.preventDefault();\n this.close();\n this.clear();\n }\n }\n /**\n * Add content to modal.\n * This adds the content slotted item to the light DOM.\n * @param {HTMLElement[]|HTMLElement} content single element or Array of elements\n * @param {Boolean} includeCloseButton Include a close button at the bottom.\n */\n setContent (content, includeCloseButton = true) {\n if (!Array.isArray(content)) {\n content = [content];\n }\n this.clear(); // make sure we start empty\n const f = document.createDocumentFragment();\n content.forEach((el) => {\n // Default to content slot.\n if (!el.getAttribute('slot')) {\n el.setAttribute('slot', 'content');\n }\n f.appendChild(el);\n });\n if (includeCloseButton) {\n f.appendChild(this.getCloseButton());\n }\n this.appendChild(f);\n }\n}\n\nif (!window.customElements.get('modal-mib')) {\n window.customElements.define('modal-mib', Modal);\n}\n\nexport default Modal;\n", "[\n {\n \"index\": \"acid-arrow\",\n \"name\": \"Acid Arrow\",\n \"desc\": [\n \"A shimmering green arrow streaks toward a target within range and bursts in a spray of acid. Make a ranged spell attack against the target. On a hit, the target takes 4d4 acid damage immediately and 2d4 acid damage at the end of its next turn. On a miss, the arrow splashes the target with acid for half as much of the initial damage and no damage at the end of its next turn.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage (both initial and later) increases by 1d4 for each slot level above 2nd.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Powdered rhubarb leaf and an adder's stomach.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"acid\",\n \"name\": \"Acid\",\n \"url\": \"/api/damage-types/acid\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"4d4\",\n \"3\": \"5d4\",\n \"4\": \"6d4\",\n \"5\": \"7d4\",\n \"6\": \"8d4\",\n \"7\": \"9d4\",\n \"8\": \"10d4\",\n \"9\": \"11d4\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/acid-arrow\"\n },\n {\n \"index\": \"acid-splash\",\n \"name\": \"Acid Splash\",\n \"desc\": [\n \"You hurl a bubble of acid. Choose one creature within range, or choose two creatures within range that are within 5 feet of each other. A target must succeed on a dexterity saving throw or take 1d6 acid damage.\",\n \"This spell's damage increases by 1d6 when you reach 5th level (2d6), 11th level (3d6), and 17th level (4d6).\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"acid\",\n \"name\": \"Acid\",\n \"url\": \"/api/damage-types/acid\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d6\",\n \"5\": \"2d6\",\n \"11\": \"3d6\",\n \"17\": \"4d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/acid-splash\"\n },\n {\n \"index\": \"aid\",\n \"name\": \"Aid\",\n \"desc\": [\n \"Your spell bolsters your allies with toughness and resolve. Choose up to three creatures within range. Each target's hit point maximum and current hit points increase by 5 for the duration.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, a target's hit points increase by an additional 5 for each slot level above 2nd.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny strip of white cloth.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"heal_at_slot_level\": {\n \"2\": \"5\",\n \"3\": \"10\",\n \"4\": \"15\",\n \"5\": \"20\",\n \"6\": \"25\",\n \"7\": \"30\",\n \"8\": \"35\",\n \"9\": \"40\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/aid\"\n },\n {\n \"index\": \"alarm\",\n \"name\": \"Alarm\",\n \"desc\": [\n \"You set an alarm against unwanted intrusion. Choose a door, a window, or an area within range that is no larger than a 20-foot cube. Until the spell ends, an alarm alerts you whenever a Tiny or larger creature touches or enters the warded area. When you cast the spell, you can designate creatures that won't set off the alarm. You also choose whether the alarm is mental or audible.\",\n \"A mental alarm alerts you with a ping in your mind if you are within 1 mile of the warded area. This ping awakens you if you are sleeping.\",\n \"An audible alarm produces the sound of a hand bell for 10 seconds within 60 feet.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny bell and a piece of fine silver wire.\",\n \"ritual\": true,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/alarm\"\n },\n {\n \"index\": \"alter-self\",\n \"name\": \"Alter Self\",\n \"desc\": [\n \"You assume a different form. When you cast the spell, choose one of the following options, the effects of which last for the duration of the spell. While the spell lasts, you can end one option as an action to gain the benefits of a different one.\",\n \"***Aquatic Adaptation.*** You adapt your body to an aquatic environment, sprouting gills and growing webbing between your fingers. You can breathe underwater and gain a swimming speed equal to your walking speed.\",\n \"***Change Appearance.*** You transform your appearance. You decide what you look like, including your height, weight, facial features, sound of your voice, hair length, coloration, and distinguishing characteristics, if any. You can make yourself appear as a member of another race, though none of your statistics change. You also can't appear as a creature of a different size than you, and your basic shape stays the same; if you're bipedal, you can't use this spell to become quadrupedal, for instance. At any time for the duration of the spell, you can use your action to change your appearance in this way again.\",\n \"***Natural Weapons.*** You grow claws, fangs, spines, horns, or a different natural weapon of your choice. Your unarmed strikes deal 1d6 bludgeoning, piercing, or slashing damage, as appropriate to the natural weapon you chose, and you are proficient with your unarmed strikes. Finally, the natural weapon is magic and you have a +1 bonus to the attack and damage rolls you make using it.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/alter-self\"\n },\n {\n \"index\": \"animal-friendship\",\n \"name\": \"Animal Friendship\",\n \"desc\": [\n \"This spell lets you convince a beast that you mean it no harm. Choose a beast that you can see within range. It must see and hear you. If the beast's Intelligence is 4 or higher, the spell fails. Otherwise, the beast must succeed on a wisdom saving throw or be charmed by you for the spell's duration. If you or one of your companions harms the target, the spells ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A morsel of food.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/animal-friendship\"\n },\n {\n \"index\": \"animal-messenger\",\n \"name\": \"Animal Messenger\",\n \"desc\": [\n \"By means of this spell, you use an animal to deliver a message. Choose a Tiny beast you can see within range, such as a squirrel, a blue jay, or a bat. You specify a location, which you must have visited, and a recipient who matches a general description, such as \\\"a man or woman dressed in the uniform of the town guard\\\" or \\\"a red-haired dwarf wearing a pointed hat.\\\" You also speak a message of up to twenty-five words. The target beast travels for the duration of the spell toward the specified location, covering about 50 miles per 24 hours for a flying messenger, or 25 miles for other animals.\",\n \"When the messenger arrives, it delivers your message to the creature that you described, replicating the sound of your voice. The messenger speaks only to a creature matching the description you gave. If the messenger doesn't reach its destination before the spell ends, the message is lost, and the beast makes its way back to where you cast this spell.\"\n ],\n \"higher_level\": [\n \"If you cast this spell using a spell slot of 3nd level or higher, the duration of the spell increases by 48 hours for each slot level above 2nd.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A morsel of food.\",\n \"ritual\": true,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/animal-messenger\"\n },\n {\n \"index\": \"animal-shapes\",\n \"name\": \"Animal Shapes\",\n \"desc\": [\n \"Your magic turns others into beasts. Choose any number of willing creatures that you can see within range. You transform each target into the form of a Large or smaller beast with a challenge rating of 4 or lower. On subsequent turns, you can use your action to transform affected creatures into new forms.\",\n \"The transformation lasts for the duration for each target, or until the target drops to 0 hit points or dies. You can choose a different form for each target. A target's game statistics are replaced by the statistics of the chosen beast, though the target retains its alignment and Intelligence, Wisdom, and Charisma scores. The target assumes the hit points of its new form, and when it reverts to its normal form, it returns to the number of hit points it had before it transformed. If it reverts as a result of dropping to 0 hit points, any excess damage carries over to its normal form. As long as the excess damage doesn't reduce the creature's normal form to 0 hit points, it isn't knocked unconscious. The creature is limited in the actions it can perform by the nature of its new form, and it can't speak or cast spells.\",\n \"The target's gear melds into the new form. The target can't activate, wield, or otherwise benefit from any of its equipment.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 24 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/animal-shapes\"\n },\n {\n \"index\": \"animate-dead\",\n \"name\": \"Animate Dead\",\n \"desc\": [\n \"This spell creates an undead servant. Choose a pile of bones or a corpse of a Medium or Small humanoid within range. Your spell imbues the target with a foul mimicry of life, raising it as an undead creature. The target becomes a skeleton if you chose bones or a zombie if you chose a corpse (the GM has the creature's game statistics).\",\n \"On each of your turns, you can use a bonus action to mentally command any creature you made with this spell if the creature is within 60 feet of you (if you control multiple creatures, you can command any or all of them at the same time, issuing the same command to each one). You decide what action the creature will take and where it will move during its next turn, or you can issue a general command, such as to guard a particular chamber or corridor. If you issue no commands, the creature only defends itself against hostile creatures. Once given an order, the creature continues to follow it until its task is complete.\",\n \"The creature is under your control for 24 hours, after which it stops obeying any command you've given it. To maintain control of the creature for another 24 hours, you must cast this spell on the creature again before the current 24-hour period ends. This use of the spell reasserts your control over up to four creatures you have animated with this spell, rather than animating a new one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, you animate or reassert control over two additional undead creatures for each slot level above 3rd. Each of the creatures must come from a different corpse or pile of bones.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of blood, a piece of flesh, and a pinch of bone dust.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 3,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/animate-dead\"\n },\n {\n \"index\": \"animate-objects\",\n \"name\": \"Animate Objects\",\n \"desc\": [\n \"Objects come to life at your command. Choose up to ten nonmagical objects within range that are not being worn or carried. Medium targets count as two objects, Large targets count as four objects, Huge targets count as eight objects. You can't animate any object larger than Huge. Each target animates and becomes a creature under your control until the spell ends or until reduced to 0 hit points.\",\n \"As a bonus action, you can mentally command any creature you made with this spell if the creature is within 500 feet of you (if you control multiple creatures, you can command any or all of them at the same time, issuing the same command to each one). You decide what action the creature will take and where it will move during its next turn, or you can issue a general command, such as to guard a particular chamber or corridor. If you issue no commands, the creature only defends itself against hostile creatures. Once given an order, the creature continues to follow it until its task is complete.\",\n \"##### Animated Object Statistics\",\n \"| Size | HP | AC | Attack | Str | Dex |\",\n \"|---|---|---|---|---|---|\",\n \"| Tiny | 20 | 18 | +8 to hit, 1d4 + 4 damage | 4 | 18 |\",\n \"| Small | 25 | 16 | +6 to hit, 1d8 + 2 damage | 6 | 14 |\",\n \"| Medium | 40 | 13 | +5 to hit, 2d6 + 1 damage | 10 | 12 |\",\n \"| Large | 50 | 10 | +6 to hit, 2d10 + 2 damage | 14 | 10 |\",\n \"| Huge | 80 | 10 | +8 to hit, 2d12 + 4 damage | 18 | 6 |\",\n \"An animated object is a construct with AC, hit points, attacks, Strength, and Dexterity determined by its size. Its Constitution is 10 and its Intelligence and Wisdom are 3, and its Charisma is 1. Its speed is 30 feet; if the object lacks legs or other appendages it can use for locomotion, it instead has a flying speed of 30 feet and can hover. If the object is securely attached to a surface or a larger object, such as a chain bolted to a wall, its speed is 0. It has blindsight with a radius of 30 feet and is blind beyond that distance. When the animated object drops to 0 hit points, it reverts to its original object form, and any remaining damage carries over to its original object form.\",\n \"If you command an object to attack, it can make a single melee attack against a creature within 5 feet of it. It makes a slam attack with an attack bonus and bludgeoning damage determined by its size. The GM might rule that a specific object inflicts slashing or piercing damage based on its form.\"\n ],\n \"higher_level\": [\n \"If you cast this spell using a spell slot of 6th level or higher, you can animate two additional objects for each slot level above 5th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/animate-objects\"\n },\n {\n \"index\": \"antilife-shell\",\n \"name\": \"Antilife Shell\",\n \"desc\": [\n \"A shimmering barrier extends out from you in a 10-foot radius and moves with you, remaining centered on you and hedging out creatures other than undead and constructs. The barrier lasts for the duration.\",\n \"The barrier prevents an affected creature from passing or reaching through. An affected creature can cast spells or make attacks with ranged or reach weapons through the barrier.\",\n \"If you move so that an affected creature is forced to pass through the barrier, the spell ends.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/antilife-shell\"\n },\n {\n \"index\": \"antimagic-field\",\n \"name\": \"Antimagic Field\",\n \"desc\": [\n \"A 10-foot-radius invisible sphere of antimagic surrounds you. This area is divorced from the magical energy that suffuses the multiverse. Within the sphere, spells can't be cast, summoned creatures disappear, and even magic items become mundane. Until the spell ends, the sphere moves with you, centered on you.\",\n \"Spells and other magical effects, except those created by an artifact or a deity, are suppressed in the sphere and can't protrude into it. A slot expended to cast a suppressed spell is consumed. While an effect is suppressed, it doesn't function, but the time it spends suppressed counts against its duration.\",\n \"***Targeted Effects.*** Spells and other magical effects, such as magic missile and charm person, that target a creature or an object in the sphere have no effect on that target.\",\n \"***Areas of Magic.*** The area of another spell or magical effect, such as fireball, can't extend into the sphere. If the sphere overlaps an area of magic, the part of the area that is covered by the sphere is suppressed. For example, the flames created by a wall of fire are suppressed within the sphere, creating a gap in the wall if the overlap is large enough.\",\n \"***Spells.*** Any active spell or other magical effect on a creature or an object in the sphere is suppressed while the creature or object is in it.\",\n \"***Magic Items.*** The properties and powers of magic items are suppressed in the sphere. For example, a +1 longsword in the sphere functions as a nonmagical longsword.\",\n \"A magic weapon's properties and powers are suppressed if it is used against a target in the sphere or wielded by an attacker in the sphere. If a magic weapon or a piece of magic ammunition fully leaves the sphere (for example, if you fire a magic arrow or throw a magic spear at a target outside the sphere), the magic of the item ceases to be suppressed as soon as it exits.\",\n \"***Magical Travel.*** Teleportation and planar travel fail to work in the sphere, whether the sphere is the destination or the departure point for such magical travel. A portal to another location, world, or plane of existence, as well as an opening to an extradimensional space such as that created by the rope trick spell, temporarily closes while in the sphere.\",\n \"***Creatures and Objects.*** A creature or object summoned or created by magic temporarily winks out of existence in the sphere. Such a creature instantly reappears once the space the creature occupied is no longer within the sphere.\",\n \"***Dispel Magic.*** Spells and magical effects such as dispel magic have no effect on the sphere. Likewise, the spheres created by different antimagic field spells don't nullify each other.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of powdered iron or iron filings.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/antimagic-field\"\n },\n {\n \"index\": \"antipathy-sympathy\",\n \"name\": \"Antipathy/Sympathy\",\n \"desc\": [\n \"This spell attracts or repels creatures of your choice. You target something within range, either a Huge or smaller object or creature or an area that is no larger than a 200-foot cube. Then specify a kind of intelligent creature, such as red dragons, goblins, or vampires. You invest the target with an aura that either attracts or repels the specified creatures for the duration. Choose antipathy or sympathy as the aura's effect.\",\n \"***Antipathy.*** The enchantment causes creatures of the kind you designated to feel an intense urge to leave the area and avoid the target. When such a creature can see the target or comes within 60 feet of it, the creature must succeed on a wisdom saving throw or become frightened. The creature remains frightened while it can see the target or is within 60 feet of it. While frightened by the target, the creature must use its movement to move to the nearest safe spot from which it can't see the target. If the creature moves more than 60 feet from the target and can't see it, the creature is no longer frightened, but the creature becomes frightened again if it regains sight of the target or moves within 60 feet of it.\",\n \"***Sympathy.*** The enchantment causes the specified creatures to feel an intense urge to approach the target while within 60 feet of it or able to see it. When such a creature can see the target or comes within 60 feet of it, the creature must succeed on a wisdom saving throw or use its movement on each of its turns to enter the area or move within reach of the target. When the creature has done so, it can't willingly move away from the target.\",\n \"If the target damages or otherwise harms an affected creature, the affected creature can make a wisdom saving throw to end the effect, as described below.\",\n \"***Ending the Effect.*** If an affected creature ends its turn while not within 60 feet of the target or able to see it, the creature makes a wisdom saving throw. On a successful save, the creature is no longer affected by the target and recognizes the feeling of repugnance or attraction as magical. In addition, a creature affected by the spell is allowed another wisdom saving throw every 24 hours while the spell persists.\",\n \"A creature that successfully saves against this effect is immune to it for 1 minute, after which time it can be affected again.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Either a lump of alum soaked in vinegar for the antipathy effect or a drop of honey for the sympathy effect.\",\n \"ritual\": false,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 8,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 200\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/antipathy-sympathy\"\n },\n {\n \"index\": \"arcane-eye\",\n \"name\": \"Arcane Eye\",\n \"desc\": [\n \"You create an invisible, magical eye within range that hovers in the air for the duration.\",\n \"You mentally receive visual information from the eye, which has normal vision and darkvision out to 30 feet. The eye can look in every direction.\",\n \"As an action, you can move the eye up to 30 feet in any direction. There is no limit to how far away from you the eye can move, but it can't enter another plane of existence. A solid barrier blocks the eye's movement, but the eye can pass through an opening as small as 1 inch in diameter.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of bat fur.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/arcane-eye\"\n },\n {\n \"index\": \"arcane-hand\",\n \"name\": \"Arcane Hand\",\n \"desc\": [\n \"You create a Large hand of shimmering, translucent force in an unoccupied space that you can see within range. The hand lasts for the spell's duration, and it moves at your command, mimicking the movements of your own hand.\",\n \"The hand is an object that has AC 20 and hit points equal to your hit point maximum. If it drops to 0 hit points, the spell ends. It has a Strength of 26 (+8) and a Dexterity of 10 (+0). The hand doesn't fill its space.\",\n \"When you cast the spell and as a bonus action on your subsequent turns, you can move the hand up to 60 feet and then cause one of the following effects with it.\",\n \"***Clenched Fist.*** The hand strikes one creature or object within 5 feet of it. Make a melee spell attack for the hand using your game statistics. On a hit, the target takes 4d8 force damage.\",\n \"***Forceful Hand.*** The hand attempts to push a creature within 5 feet of it in a direction you choose. Make a check with the hand's Strength contested by the Strength (Athletics) check of the target. If the target is Medium or smaller, you have advantage on the check. If you succeed, the hand pushes the target up to 5 feet plus a number of feet equal to five times your spellcasting ability modifier. The hand moves with the target to remain within 5 feet of it.\",\n \"***Grasping Hand.*** The hand attempts to grapple a Huge or smaller creature within 5 feet of it. You use the hand's Strength score to resolve the grapple. If the target is Medium or smaller, you have advantage on the check. While the hand is grappling the target, you can use a bonus action to have the hand crush it. When you do so, the target takes bludgeoning damage equal to 2d6 + your spellcasting ability modifier.\",\n \"***Interposing Hand.*** The hand interposes itself between you and a creature you choose until you give the hand a different command. The hand moves to stay between you and the target, providing you with half cover against the target. The target can't move through the hand's space if its Strength score is less than or equal to the hand's Strength score. If its Strength score is higher than the hand's Strength score, the target can move toward you through the hand's space, but that space is difficult terrain for the target.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the damage from the clenched fist option increases by 2d8 and the damage from the grasping hand increases by 2d6 for each slot level above 5th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An eggshell and a snakeskin glove.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/arcane-hand\"\n },\n {\n \"index\": \"arcane-lock\",\n \"name\": \"Arcane Lock\",\n \"desc\": [\n \"You touch a closed door, window, gate, chest, or other entryway, and it becomes locked for the duration. You and the creatures you designate when you cast this spell can open the object normally. You can also set a password that, when spoken within 5 feet of the object, suppresses this spell for 1 minute. Otherwise, it is impassable until it is broken or the spell is dispelled or suppressed. Casting knock on the object suppresses arcane lock for 10 minutes.\",\n \"While affected by this spell, the object is more difficult to break or force open; the DC to break it or pick any locks on it increases by 10.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Gold dust worth at least 25gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/arcane-lock\"\n },\n {\n \"index\": \"arcane-sword\",\n \"name\": \"Arcane Sword\",\n \"desc\": [\n \"You create a sword-shaped plane of force that hovers within range. It lasts for the duration.\",\n \"When the sword appears, you make a melee spell attack against a target of your choice within 5 feet of the sword. On a hit, the target takes 3d10 force damage. Until the spell ends, you can use a bonus action on each of your turns to move the sword up to 20 feet to a spot you can see and repeat this attack against the same target or a different one.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A miniature platinum sword with a grip and pommel of copper and zinc, worth 250 gp.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"7\": \"3d10\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/arcane-sword\"\n },\n {\n \"index\": \"arcanists-magic-aura\",\n \"name\": \"Arcanist's Magic Aura\",\n \"desc\": [\n \"You place an illusion on a creature or an object you touch so that divination spells reveal false information about it. The target can be a willing creature or an object that isn't being carried or worn by another creature.\",\n \"When you cast the spell, choose one or both of the following effects. The effect lasts for the duration. If you cast this spell on the same creature or object every day for 30 days, placing the same effect on it each time, the illusion lasts until it is dispelled.\",\n \"***False Aura.*** You change the way the target appears to spells and magical effects, such as detect magic, that detect magical auras. You can make a nonmagical object appear magical, a magical object appear nonmagical, or change the object's magical aura so that it appears to belong to a specific school of magic that you choose. When you use this effect on an object, you can make the false magic apparent to any creature that handles the item.\",\n \"***Mask.*** You change the way the target appears to spells and magical effects that detect creature types, such as a paladin's Divine Sense or the trigger of a symbol spell. You choose a creature type and other spells and magical effects treat the target as if it were a creature of that type or of that alignment.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small square of silk.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/arcanists-magic-aura\"\n },\n {\n \"index\": \"astral-projection\",\n \"name\": \"Astral Projection\",\n \"desc\": [\n \"You and up to eight willing creatures within range project your astral bodies into the Astral Plane (the spell fails and the casting is wasted if you are already on that plane). The material body you leave behind is unconscious and in a state of suspended animation; it doesn't need food or air and doesn't age.\",\n \"Your astral body resembles your mortal form in almost every way, replicating your game statistics and possessions. The principal difference is the addition of a silvery cord that extends from between your shoulder blades and trails behind you, fading to invisibility after 1 foot. This cord is your tether to your material body. As long as the tether remains intact, you can find your way home. If the cord is cut--something that can happen only when an effect specifically states that it does--your soul and body are separated, killing you instantly.\",\n \"Your astral form can freely travel through the Astral Plane and can pass through portals there leading to any other plane. If you enter a new plane or return to the plane you were on when casting this spell, your body and possessions are transported along the silver cord, allowing you to re-enter your body as you enter the new plane. Your astral form is a separate incarnation. Any damage or other effects that apply to it have no effect on your physical body, nor do they persist when you return to it.\",\n \"The spell ends for you and your companions when you use your action to dismiss it. When the spell ends, the affected creature returns to its physical body, and it awakens.\",\n \"The spell might also end early for you or one of your companions. A successful dispel magic spell used against an astral or physical body ends the spell for that creature. If a creature's original body or its astral form drops to 0 hit points, the spell ends for that creature. If the spell ends and the silver cord is intact, the cord pulls the creature's astral form back to its body, ending its state of suspended animation.\",\n \"If you are returned to your body prematurely, your companions remain in their astral forms and must find their own way back to their bodies, usually by dropping to 0 hit points.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"For each creature you affect with this spell, you must provide one jacinth worth at least 1,000gp and one ornately carved bar of silver worth at least 100gp, all of which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Special\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 9,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/astral-projection\"\n },\n {\n \"index\": \"augury\",\n \"name\": \"Augury\",\n \"desc\": [\n \"By casting gem-inlaid sticks, rolling dragon bones, laying out ornate cards, or employing some other divining tool, you receive an omen from an otherworldly entity about the results of a specific course of action that you plan to take within the next 30 minutes. The GM chooses from the following possible omens:\",\n \"- Weal, for good results\",\n \"- Woe, for bad results\",\n \"- Weal and woe, for both good and bad results\",\n \"- Nothing, for results that aren't especially good or bad\",\n \"The spell doesn't take into account any possible circumstances that might change the outcome, such as the casting of additional spells or the loss or gain of a companion.\",\n \"If you cast the spell two or more times before completing your next long rest, there is a cumulative 25 percent chance for each casting after the first that you get a random reading. The GM makes this roll in secret.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Specially marked sticks, bones, or similar tokens worth at least 25gp.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/augury\"\n },\n {\n \"index\": \"awaken\",\n \"name\": \"Awaken\",\n \"desc\": [\n \"After spending the casting time tracing magical pathways within a precious gemstone, you touch a Huge or smaller beast or plant. The target must have either no Intelligence score or an Intelligence of 3 or less. The target gains an Intelligence of 10. The target also gains the ability to speak one language you know. If the target is a plant, it gains the ability to move its limbs, roots, vines, creepers, and so forth, and it gains senses similar to a human's. Your GM chooses statistics appropriate for the awakened plant, such as the statistics for the awakened shrub or the awakened tree.\",\n \"The awakened beast or plant is charmed by you for 30 days or until you or your companions do anything harmful to it. When the charmed condition ends, the awakened creature chooses whether to remain friendly to you, based on how you treated it while it was charmed.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An agate worth at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"8 hours\",\n \"level\": 5,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/awaken\"\n },\n {\n \"index\": \"bane\",\n \"name\": \"Bane\",\n \"desc\": [\n \"Up to three creatures of your choice that you can see within range must make charisma saving throws. Whenever a target that fails this saving throw makes an attack roll or a saving throw before the spell ends, the target must roll a d4 and subtract the number rolled from the attack roll or saving throw.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can target one additional creature for each slot level above 1st.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of blood.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/bane\"\n },\n {\n \"index\": \"banishment\",\n \"name\": \"Banishment\",\n \"desc\": [\n \"You attempt to send one creature that you can see within range to another plane of existence. The target must succeed on a charisma saving throw or be banished.\",\n \"If the target is native to the plane of existence you're on, you banish the target to a harmless demiplane. While there, the target is incapacitated. The target remains there until the spell ends, at which point the target reappears in the space it left or in the nearest unoccupied space if that space is occupied.\",\n \"If the target is native to a different plane of existence than the one you're on, the target is banished with a faint popping noise, returning to its home plane. If the spell ends before 1 minute has passed, the target reappears in the space it left or in the nearest unoccupied space if that space is occupied. Otherwise, the target doesn't return.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, you can target one additional creature for each slot level above 4th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An item distasteful to the target.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/banishment\"\n },\n {\n \"index\": \"barkskin\",\n \"name\": \"Barkskin\",\n \"desc\": [\n \"You touch a willing creature. Until the spell ends, the target's skin has a rough, bark-like appearance, and the target's AC can't be less than 16, regardless of what kind of armor it is wearing.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A handful of oak bark.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/barkskin\"\n },\n {\n \"index\": \"beacon-of-hope\",\n \"name\": \"Beacon of Hope\",\n \"desc\": [\n \"This spell bestows hope and vitality. Choose any number of creatures within range. For the duration, each target has advantage on wisdom saving throws and death saving throws, and regains the maximum number of hit points possible from any healing.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/beacon-of-hope\"\n },\n {\n \"index\": \"bestow-curse\",\n \"name\": \"Bestow Curse\",\n \"desc\": [\n \"You touch a creature, and that creature must succeed on a wisdom saving throw or become cursed for the duration of the spell. When you cast this spell, choose the nature of the curse from the following options:\",\n \"- Choose one ability score. While cursed, the target has disadvantage on ability checks and saving throws made with that ability score.\",\n \"- While cursed, the target has disadvantage on attack rolls against you.\",\n \"- While cursed, the target must make a wisdom saving throw at the start of each of its turns. If it fails, it wastes its action that turn doing nothing.\",\n \"- While the target is cursed, your attacks and spells deal an extra 1d8 necrotic damage to the target.\",\n \"A remove curse spell ends this effect. At the GM's option, you may choose an alternative curse effect, but it should be no more powerful than those described above. The GM has final say on such a curse's effect.\"\n ],\n \"higher_level\": [\n \"If you cast this spell using a spell slot of 4th level or higher, the duration is concentration, up to 10 minutes. If you use a spell slot of 5th level or higher, the duration is 8 hours. If you use a spell slot of 7th level or higher, the duration is 24 hours. If you use a 9th level spell slot, the spell lasts until it is dispelled. Using a spell slot of 5th level or higher grants a duration that doesn't require concentration.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On fail, become cursed for the duration of the spell.\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/bestow-curse\"\n },\n {\n \"index\": \"black-tentacles\",\n \"name\": \"Black Tentacles\",\n \"desc\": [\n \"Squirming, ebony tentacles fill a 20-foot square on ground that you can see within range. For the duration, these tentacles turn the ground in the area into difficult terrain.\",\n \"When a creature enters the affected area for the first time on a turn or starts its turn there, the creature must succeed on a Dexterity saving throw or take 3d6 bludgeoning damage and be restrained by the tentacles until the spell ends. A creature that starts its turn in the area and is already restrained by the tentacles takes 3d6 bludgeoning damage.\",\n \"A creature restrained by the tentacles can use its action to make a Strength or Dexterity check (its choice) against your spell save DC. On a success, it frees itself.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of tentacle from a giant octopus or a giant squid\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"bludgeoning\",\n \"name\": \"Bludgeoning\",\n \"url\": \"/api/damage-types/bludgeoning\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"3d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"A creature restrained by the tentacles can use its action to make a Strength or Dexterity check (its choice) against your spell save DC. On a success, it frees itself.\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/black-tentacles\"\n },\n {\n \"index\": \"blade-barrier\",\n \"name\": \"Blade Barrier\",\n \"desc\": [\n \"You create a vertical wall of whirling, razor-sharp blades made of magical energy. The wall appears within range and lasts for the duration. You can make a straight wall up to 100 feet long, 20 feet high, and 5 feet thick, or a ringed wall up to 60 feet in diameter, 20 feet high, and 5 feet thick. The wall provides three-quarters cover to creatures behind it, and its space is difficult terrain.\",\n \"When a creature enters the wall's area for the first time on a turn or starts its turn there, the creature must make a dexterity saving throw. On a failed save, the creature takes 6d10 slashing damage. On a successful save, the creature takes half as much damage.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"slashing\",\n \"name\": \"Slashing\",\n \"url\": \"/api/damage-types/slashing\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"6d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/blade-barrier\"\n },\n {\n \"index\": \"bless\",\n \"name\": \"Bless\",\n \"desc\": [\n \"You bless up to three creatures of your choice within range. Whenever a target makes an attack roll or a saving throw before the spell ends, the target can roll a d4 and add the number rolled to the attack roll or saving throw.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can target one additional creature for each slot level above 1st.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sprinkling of holy water.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/bless\"\n },\n {\n \"index\": \"blight\",\n \"name\": \"Blight\",\n \"desc\": [\n \"Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a constitution saving throw. The target takes 8d8 necrotic damage on a failed save, or half as much damage on a successful one. The spell has no effect on undead or constructs.\",\n \"If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.\",\n \"If you target a nonmagical plant that isn't a creature, such as a tree or shrub, it doesn't make a saving throw; it simply withers and dies.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level of higher, the damage increases by 1d8 for each slot level above 4th.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"8d8\",\n \"5\": \"9d8\",\n \"6\": \"10d8\",\n \"7\": \"11d8\",\n \"8\": \"12d8\",\n \"9\": \"13d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/blight\"\n },\n {\n \"index\": \"blindness-deafness\",\n \"name\": \"Blindness/Deafness\",\n \"desc\": [\n \"You can blind or deafen a foe. Choose one creature that you can see within range to make a constitution saving throw. If it fails, the target is either blinded or deafened (your choice) for the duration. At the end of each of its turns, the target can make a constitution saving throw. On a success, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you can target one additional creature for each slot level above 2nd.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/blindness-deafness\"\n },\n {\n \"index\": \"blink\",\n \"name\": \"Blink\",\n \"desc\": [\n \"Roll a d20 at the end of each of your turns for the duration of the spell. On a roll of 11 or higher, you vanish from your current plane of existence and appear in the Ethereal Plane (the spell fails and the casting is wasted if you were already on that plane). At the start of your next turn, and when the spell ends if you are on the Ethereal Plane, you return to an unoccupied space of your choice that you can see within 10 feet of the space you vanished from. If no unoccupied space is available within that range, you appear in the nearest unoccupied space (chosen at random if more than one space is equally near). You can dismiss this spell as an action.\",\n \"While on the Ethereal Plane, you can see and hear the plane you originated from, which is cast in shades of gray, and you can't see anything there more than 60 feet away. You can only affect and be affected by other creatures on the Ethereal Plane. Creatures that aren't there can't perceive you or interact with you, unless they have the ability to do so.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/blink\"\n },\n {\n \"index\": \"blur\",\n \"name\": \"Blur\",\n \"desc\": [\n \"Your body becomes blurred, shifting and wavering to all who can see you. For the duration, any creature has disadvantage on attack rolls against you. An attacker is immune to this effect if it doesn't rely on sight, as with blindsight, or can see through illusions, as with truesight.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/blur\"\n },\n {\n \"index\": \"branding-smite\",\n \"name\": \"Branding Smite\",\n \"desc\": [\n \"The next time you hit a creature with a weapon attack before this spell ends, the weapon gleams with astral radiance as you strike. The attack deals an extra 2d6 radiant damage to the target, which becomes visible if it's invisible, and the target sheds dim light in a 5-foot radius and can't become invisible until the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the extra damage increases by 1d6 for each slot level above 2nd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d6\",\n \"3\": \"3d6\",\n \"4\": \"4d6\",\n \"5\": \"5d6\",\n \"6\": \"6d6\",\n \"7\": \"7d6\",\n \"8\": \"8d6\",\n \"9\": \"9d6\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/branding-smite\"\n },\n {\n \"index\": \"burning-hands\",\n \"name\": \"Burning Hands\",\n \"desc\": [\n \"As you hold your hands with thumbs touching and fingers spread, a thin sheet of flames shoots forth from your outstretched fingertips. Each creature in a 15-foot cone must make a dexterity saving throw. A creature takes 3d6 fire damage on a failed save, or half as much damage on a successful one.\",\n \"The fire ignites any flammable objects in the area that aren't being worn or carried.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d6 for each slot level above 1st.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"3d6\",\n \"2\": \"4d6\",\n \"3\": \"5d6\",\n \"4\": \"6d6\",\n \"5\": \"7d6\",\n \"6\": \"8d6\",\n \"7\": \"9d6\",\n \"8\": \"10d6\",\n \"9\": \"11d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/burning-hands\"\n },\n {\n \"index\": \"call-lightning\",\n \"name\": \"Call Lightning\",\n \"desc\": [\n \"A storm cloud appears in the shape of a cylinder that is 10 feet tall with a 60-foot radius, centered on a point you can see 100 feet directly above you. The spell fails if you can't see a point in the air where the storm cloud could appear (for example, if you are in a room that can't accommodate the cloud).\",\n \"When you cast the spell, choose a point you can see within range. A bolt of lightning flashes down from the cloud to that point. Each creature within 5 feet of that point must make a dexterity saving throw. A creature takes 3d10 lightning damage on a failed save, or half as much damage on a successful one. On each of your turns until the spell ends, you can use your action to call down lightning in this way again, targeting the same point or a different one.\",\n \"If you are outdoors in stormy conditions when you cast this spell, the spell gives you control over the existing storm instead of creating a new one. Under such conditions, the spell's damage increases by 1d10.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th or higher level, the damage increases by 1d10 for each slot level above 3rd.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"lightning\",\n \"name\": \"Lightning\",\n \"url\": \"/api/damage-types/lightning\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"3d10\",\n \"4\": \"4d10\",\n \"5\": \"5d10\",\n \"6\": \"6d10\",\n \"7\": \"7d10\",\n \"8\": \"8d10\",\n \"9\": \"9d10\"\n }\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/call-lightning\"\n },\n {\n \"index\": \"calm-emotions\",\n \"name\": \"Calm Emotions\",\n \"desc\": [\n \"You attempt to suppress strong emotions in a group of people. Each humanoid in a 20-foot-radius sphere centered on a point you choose within range must make a charisma saving throw; a creature can choose to fail this saving throw if it wishes. If a creature fails its saving throw, choose one of the following two effects. You can suppress any effect causing a target to be charmed or frightened. When this spell ends, any suppressed effect resumes, provided that its duration has not expired in the meantime.\",\n \"Alternatively, you can make a target indifferent about creatures of your choice that it is hostile toward. This indifference ends if the target is attacked or harmed by a spell or if it witnesses any of its friends being harmed. When the spell ends, the creature becomes hostile again, unless the GM rules otherwise.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/calm-emotions\"\n },\n {\n \"index\": \"chain-lightning\",\n \"name\": \"Chain Lightning\",\n \"desc\": [\n \"You create a bolt of lightning that arcs toward a target of your choice that you can see within range. Three bolts then leap from that target to as many as three other targets, each of which must be within 30 feet of the first target. A target can be a creature or an object and can be targeted by only one of the bolts.\",\n \"A target must make a dexterity saving throw. The target takes 10d8 lightning damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, one additional bolt leaps from the first target to another target for each slot level above 6th.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fur; a piece of amber, glass, or a crystal rod; and three silver pins.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"lightning\",\n \"name\": \"Lightning\",\n \"url\": \"/api/damage-types/lightning\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/chain-lightning\"\n },\n {\n \"index\": \"charm-person\",\n \"name\": \"Charm Person\",\n \"desc\": [\n \"You attempt to charm a humanoid you can see within range. It must make a wisdom saving throw, and does so with advantage if you or your companions are fighting it. If it fails the saving throw, it is charmed by you until the spell ends or until you or your companions do anything harmful to it. The charmed creature regards you as a friendly acquaintance. When the spell ends, the creature knows it was charmed by you.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can target one additional creature for each slot level above 1st. The creatures must be within 30 feet of each other when you target them.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/charm-person\"\n },\n {\n \"index\": \"chill-touch\",\n \"name\": \"Chill Touch\",\n \"desc\": [\n \"You create a ghostly, skeletal hand in the space of a creature within range. Make a ranged spell attack against the creature to assail it with the chill of the grave. On a hit, the target takes 1d8 necrotic damage, and it can't regain hit points until the start of your next turn. Until then, the hand clings to the target.\",\n \"If you hit an undead target, it also has disadvantage on attack rolls against you until the end of your next turn.\",\n \"This spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/chill-touch\"\n },\n {\n \"index\": \"circle-of-death\",\n \"name\": \"Circle of Death\",\n \"desc\": [\n \"A sphere of negative energy ripples out in a 60-foot radius sphere from a point within range. Each creature in that area must make a constitution saving throw. A target takes 8d6 necrotic damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the damage increases by 2d6 for each slot level above 6th.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"The powder of a crushed black pearl worth at least 500 gp.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"8d6\",\n \"7\": \"10d6\",\n \"8\": \"12d6\",\n \"9\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/circle-of-death\"\n },\n {\n \"index\": \"clairvoyance\",\n \"name\": \"Clairvoyance\",\n \"desc\": [\n \"You create an invisible sensor within range in a location familiar to you (a place you have visited or seen before) or in an obvious location that is unfamiliar to you (such as behind a door, around a corner, or in a grove of trees). The sensor remains in place for the duration, and it can't be attacked or otherwise interacted with.\",\n \"When you cast the spell, you choose seeing or hearing. You can use the chosen sense through the sensor as if you were in its space. As your action, you can switch between seeing and hearing.\",\n \"A creature that can see the sensor (such as a creature benefiting from see invisibility or truesight) sees a luminous, intangible orb about the size of your fist.\"\n ],\n \"range\": \"1 mile\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A focus worth at least 100gp, either a jeweled horn for hearing or a glass eye for seeing.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"10 minutes\",\n \"level\": 3,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/clairvoyance\"\n },\n {\n \"index\": \"clone\",\n \"name\": \"Clone\",\n \"desc\": [\n \"This spell grows an inert duplicate of a living creature as a safeguard against death. This clone forms inside a sealed vessel and grows to full size and maturity after 120 days; you can also choose to have the clone be a younger version of the same creature. It remains inert and endures indefinitely, as long as its vessel remains undisturbed.\",\n \"At any time after the clone matures, if the original creature dies, its soul transfers to the clone, provided that the soul is free and willing to return. The clone is physically identical to the original and has the same personality, memories, and abilities, but none of the original's equipment. The original creature's physical remains, if they still exist, become inert and can't thereafter be restored to life, since the creature's soul is elsewhere.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A diamond worth at least 1,000 gp and at least 1 cubic inch of flesh of the creature that is to be cloned, which the spell consumes, and a vessel worth at least 2,000 gp that has a sealable lid and is large enough to hold a Medium creature, such as a huge urn, coffin, mud-filled cyst in the ground, or crystal container filled with salt water.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 8,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/clone\"\n },\n {\n \"index\": \"cloudkill\",\n \"name\": \"Cloudkill\",\n \"desc\": [\n \"You create a 20-foot-radius sphere of poisonous, yellow-green fog centered on a point you choose within range. The fog spreads around corners. It lasts for the duration or until strong wind disperses the fog, ending the spell. Its area is heavily obscured.\",\n \"When a creature enters the spell's area for the first time on a turn or starts its turn there, that creature must make a constitution saving throw. The creature takes 5d8 poison damage on a failed save, or half as much damage on a successful one. Creatures are affected even if they hold their breath or don't need to breathe.\",\n \"The fog moves 10 feet away from you at the start of each of your turns, rolling along the surface of the ground. The vapors, being heavier than air, sink to the lowest level of the land, even pouring down openings.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the damage increases by 1d8 for each slot level above 5th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"poison\",\n \"name\": \"Poison\",\n \"url\": \"/api/damage-types/poison\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"5d8\",\n \"6\": \"6d8\",\n \"7\": \"7d8\",\n \"8\": \"8d8\",\n \"9\": \"9d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\",\n \"desc\": \"Creatures are affected even if they hold their breath or don't need to breathe.\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/cloudkill\"\n },\n {\n \"index\": \"color-spray\",\n \"name\": \"Color Spray\",\n \"desc\": [\n \"A dazzling array of flashing, colored light springs from your hand. Roll 6d10; the total is how many hit points of creatures this spell can effect. Creatures in a 15-foot cone originating from you are affected in ascending order of their current hit points (ignoring unconscious creatures and creatures that can't see).\",\n \"Starting with the creature that has the lowest current hit points, each creature affected by this spell is blinded until the spell ends. Subtract each creature's hit points from the total before moving on to the creature with the next lowest hit points. A creature's hit points must be equal to or less than the remaining total for that creature to be affected.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, roll an additional 2d10 for each slot level above 1st.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of powder or sand that is colored red, yellow, and blue.\",\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/color-spray\"\n },\n {\n \"index\": \"command\",\n \"name\": \"Command\",\n \"desc\": [\n \"You speak a one-word command to a creature you can see within range. The target must succeed on a wisdom saving throw or follow the command on its next turn. The spell has no effect if the target is undead, if it doesn't understand your language, or if your command is directly harmful to it.\",\n \"Some typical commands and their effects follow. You might issue a command other than one described here. If you do so, the GM determines how the target behaves. If the target can't follow your command, the spell ends.\",\n \"***Approach.*** The target moves toward you by the shortest and most direct route, ending its turn if it moves within 5 feet of you.\",\n \"***Drop.*** The target drops whatever it is holding and then ends its turn.\",\n \"***Flee.*** The target spends its turn moving away from you by the fastest available means.\",\n \"***Grovel.*** The target falls prone and then ends its turn.\",\n \"***Halt.*** The target doesn't move and takes no actions. A flying creature stays aloft, provided that it is able to do so. If it must move to stay aloft, it flies the minimum distance needed to remain in the air.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can affect one additional creature for each slot level above 1st. The creatures must be within 30 feet of each other when you target them.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/command\"\n },\n {\n \"index\": \"commune\",\n \"name\": \"Commune\",\n \"desc\": [\n \"You contact your deity or a divine proxy and ask up to three questions that can be answered with a yes or no. You must ask your questions before the spell ends. You receive a correct answer for each question.\",\n \"Divine beings aren't necessarily omniscient, so you might receive \\\"unclear\\\" as an answer if a question pertains to information that lies beyond the deity's knowledge. In a case where a one-word answer could be misleading or contrary to the deity's interests, the GM might offer a short phrase as an answer instead.\",\n \"If you cast the spell two or more times before finishing your next long rest, there is a cumulative 25 percent chance for each casting after the first that you get no answer. The GM makes this roll in secret.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Incense and a vial of holy or unholy water.\",\n \"ritual\": true,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/commune\"\n },\n {\n \"index\": \"commune-with-nature\",\n \"name\": \"Commune With Nature\",\n \"desc\": [\n \"You briefly become one with nature and gain knowledge of the surrounding territory. In the outdoors, the spell gives you knowledge of the land within 3 miles of you. In caves and other natural underground settings, the radius is limited to 300 feet. The spell doesn't function where nature has been replaced by construction, such as in dungeons and towns.\",\n \"You instantly gain knowledge of up to three facts of your choice about any of the following subjects as they relate to the area:\",\n \"- terrain and bodies of water\",\n \"- prevalent plants, minerals, animals, or peoples\",\n \"- powerful celestials, fey, fiends, elementals, or undead\",\n \"- influence from other planes of existence\",\n \"- buildings\",\n \"For example, you could determine the location of powerful undead in the area, the location of major sources of safe drinking water, and the location of any nearby towns.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/commune-with-nature\"\n },\n {\n \"index\": \"comprehend-languages\",\n \"name\": \"Comprehend Languages\",\n \"desc\": [\n \"For the duration, you understand the literal meaning of any spoken language that you hear. You also understand any written language that you see, but you must be touching the surface on which the words are written. It takes about 1 minute to read one page of text.\",\n \"This spell doesn't decode secret messages in a text or a glyph, such as an arcane sigil, that isn't part of a written language.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of soot and salt.\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/comprehend-languages\"\n },\n {\n \"index\": \"compulsion\",\n \"name\": \"Compulsion\",\n \"desc\": [\n \"Creatures of your choice that you can see within range and that can hear you must make a wisdom saving throw. A target automatically succeeds on this saving throw if it can't be charmed. On a failed save, a target is affected by this spell. Until the spell ends, you can use a bonus action on each of your turns to designate a direction that is horizontal to you. Each affected target must use as much of its movement as possible to move in that direction on its next turn. It can take any action before it moves. After moving in this way, it can make another Wisdom save to try to end the effect.\",\n \"A target isn't compelled to move into an obviously deadly hazard, such as a fire or a pit, but it will provoke opportunity attacks to move in the designated direction.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/compulsion\"\n },\n {\n \"index\": \"cone-of-cold\",\n \"name\": \"Cone of Cold\",\n \"desc\": [\n \"A blast of cold air erupts from your hands. Each creature in a 60-foot cone must make a constitution saving throw. A creature takes 8d8 cold damage on a failed save, or half as much damage on a successful one.\",\n \"A creature killed by this spell becomes a frozen statue until it thaws.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the damage increases by 1d8 for each slot level above 5th.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small crystal or glass cone.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"cold\",\n \"name\": \"Cold\",\n \"url\": \"/api/damage-types/cold\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"8d8\",\n \"6\": \"9d8\",\n \"7\": \"10d8\",\n \"8\": \"11d8\",\n \"9\": \"12d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\",\n \"desc\": \"A creature killed by this spell becomes a frozen statue until it thaws.\"\n },\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/cone-of-cold\"\n },\n {\n \"index\": \"confusion\",\n \"name\": \"Confusion\",\n \"desc\": [\n \"This spell assaults and twists creatures' minds, spawning delusions and provoking uncontrolled action. Each creature in a 10-foot-radius sphere centered on a point you choose within range must succeed on a Wisdom saving throw when you cast this spell or be affected by it.\",\n \"An affected target can't take reactions and must roll a d10 at the start of each of its turns to determine its behavior for that turn.\",\n \"| d10 | Behavior |\",\n \"|---|---|\",\n \"| 1 | The creature uses all its movement to move in a random direction. To determine the direction, roll a d8 and assign a direction to each die face. The creature doesn't take an action this turn. |\",\n \"| 2-6 | The creature doesn't move or take actions this turn. |\",\n \"| 7-8 | The creature uses its action to make a melee attack against a randomly determined creature within its reach. If there is no creature within its reach, the creature does nothing this turn. |\",\n \"| 9-10 | The creature can act and move normally. |\",\n \"At the end of each of its turns, an affected target can make a Wisdom saving throw. If it succeeds, this effect ends for that target.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, the radius of the sphere increases by 5 feet for each slot level above 4th.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Three walnut shells.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/confusion\"\n },\n {\n \"index\": \"conjure-animals\",\n \"name\": \"Conjure Animals\",\n \"desc\": [\n \"You summon fey spirits that take the form of beasts and appear in unoccupied spaces that you can see within range. Choose one of the following options for what appears:\",\n \"- One beast of challenge rating 2 or lower\",\n \"- Two beasts of challenge rating 1 or lower\",\n \"- Four beasts of challenge rating 1/2 or lower\",\n \"- Eight beasts of challenge rating 1/4 or lower\",\n \"- Each beast is also considered fey, and it disappears when it drops to 0 hit points or when the spell ends.\",\n \"The summoned creatures are friendly to you and your companions. Roll initiative for the summoned creatures as a group, which has its own turns. They obey any verbal commands that you issue to them (no action required by you). If you don't issue any commands to them, they defend themselves from hostile creatures, but otherwise take no actions.\",\n \"The GM has the creatures' statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using certain higher-level spell slots, you choose one of the summoning options above, and more creatures appear: twice as many with a 5th-level slot, three times as many with a 7th-level.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/conjure-animals\"\n },\n {\n \"index\": \"conjure-celestial\",\n \"name\": \"Conjure Celestial\",\n \"desc\": [\n \"You summon a celestial of challenge rating 4 or lower, which appears in an unoccupied space that you can see within range. The celestial disappears when it drops to 0 hit points or when the spell ends.\",\n \"The celestial is friendly to you and your companions for the duration. Roll initiative for the celestial, which has its own turns. It obeys any verbal commands that you issue to it (no action required by you), as long as they don't violate its alignment. If you don't issue any commands to the celestial, it defends itself from hostile creatures but otherwise takes no actions.\",\n \"The GM has the celestial's statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 9th-level spell slot, you summon a celestial of challenge rating 5 or lower.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 7,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/conjure-celestial\"\n },\n {\n \"index\": \"conjure-elemental\",\n \"name\": \"Conjure Elemental\",\n \"desc\": [\n \"You call forth an elemental servant. Choose an area of air, earth, fire, or water that fills a 10-foot cube within range. An elemental of challenge rating 5 or lower appropriate to the area you chose appears in an unoccupied space within 10 feet of it. For example, a fire elemental emerges from a bonfire, and an earth elemental rises up from the ground. The elemental disappears when it drops to 0 hit points or when the spell ends.\",\n \"The elemental is friendly to you and your companions for the duration. Roll initiative for the elemental, which has its own turns. It obeys any verbal commands that you issue to it (no action required by you). If you don't issue any commands to the elemental, it defends itself from hostile creatures but otherwise takes no actions.\",\n \"If your concentration is broken, the elemental doesn't disappear. Instead, you lose control of the elemental, it becomes hostile toward you and your companions, and it might attack. An uncontrolled elemental can't be dismissed by you, and it disappears 1 hour after you summoned it.\",\n \"The GM has the elemental's statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the challenge rating increases by 1 for each slot level above 5th.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Burning incense for air, soft clay for earth, sulfur and phosphorus for fire, or water and sand for water.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/conjure-elemental\"\n },\n {\n \"index\": \"conjure-fey\",\n \"name\": \"Conjure Fey\",\n \"desc\": [\n \"You summon a fey creature of challenge rating 6 or lower, or a fey spirit that takes the form of a beast of challenge rating 6 or lower. It appears in an unoccupied space that you can see within range. The fey creature disappears when it drops to 0 hit points or when the spell ends.\",\n \"The fey creature is friendly to you and your companions for the duration. Roll initiative for the creature, which has its own turns. It obeys any verbal commands that you issue to it (no action required by you), as long as they don't violate its alignment. If you don't issue any commands to the fey creature, it defends itself from hostile creatures but otherwise takes no actions.\",\n \"If your concentration is broken, the fey creature doesn't disappear. Instead, you lose control of the fey creature, it becomes hostile toward you and your companions, and it might attack. An uncontrolled fey creature can't be dismissed by you, and it disappears 1 hour after you summoned it.\",\n \"The GM has the fey creature's statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the challenge rating increases by 1 for each slot level above 6th.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/conjure-fey\"\n },\n {\n \"index\": \"conjure-minor-elementals\",\n \"name\": \"Conjure Minor Elementals\",\n \"desc\": [\n \"You summon elementals that appear in unoccupied spaces that you can see within range. You choose one the following options for what appears:\",\n \"- One elemental of challenge rating 2 or lower\",\n \"- Two elementals of challenge rating 1 or lower\",\n \"- Four elementals of challenge rating 1/2 or lower\",\n \"- Eight elementals of challenge rating 1/4 or lower.\",\n \"An elemental summoned by this spell disappears when it drops to 0 hit points or when the spell ends.\",\n \"The summoned creatures are friendly to you and your companions. Roll initiative for the summoned creatures as a group, which has its own turns. They obey any verbal commands that you issue to them (no action required by you). If you don't issue any commands to them, they defend themselves from hostile creatures, but otherwise take no actions.\",\n \"The GM has the creatures' statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using certain higher-level spell slots, you choose one of the summoning options above, and more creatures appear: twice as many with a 6th-level slot and three times as many with an 8th-level slot.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 4,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/conjure-minor-elementals\"\n },\n {\n \"index\": \"conjure-woodland-beings\",\n \"name\": \"Conjure Woodland Beings\",\n \"desc\": [\n \"You summon fey creatures that appear in unoccupied spaces that you can see within range. Choose one of the following options for what appears:\",\n \"- One fey creature of challenge rating 2 or lower\",\n \"- Two fey creatures of challenge rating 1 or lower\",\n \"- Four fey creatures of challenge rating 1/2 or lower\",\n \"- Eight fey creatures of challenge rating 1/4 or lower\",\n \"A summoned creature disappears when it drops to 0 hit points or when the spell ends.\",\n \"The summoned creatures are friendly to you and your companions. Roll initiative for the summoned creatures as a group, which have their own turns. They obey any verbal commands that you issue to them (no action required by you). If you don't issue any commands to them, they defend themselves from hostile creatures, but otherwise take no actions.\",\n \"The GM has the creatures' statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using certain higher-level spell slots, you choose one of the summoning options above, and more creatures appear: twice as many with a 6th-level slot and three times as many with an 8th-level slot.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"One holly berry per creature summoned.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/conjure-woodland-beings\"\n },\n {\n \"index\": \"contact-other-plane\",\n \"name\": \"Contact Other Plane\",\n \"desc\": [\n \"You mentally contact a demigod, the spirit of a long-dead sage, or some other mysterious entity from another plane. Contacting this extraplanar intelligence can strain or even break your mind. When you cast this spell, make a DC 15 intelligence saving throw. On a failure, you take 6d6 psychic damage and are insane until you finish a long rest. While insane, you can't take actions, can't understand what other creatures say, can't read, and speak only in gibberish. A greater restoration spell cast on you ends this effect.\",\n \"On a successful save, you can ask the entity up to five questions. You must ask your questions before the spell ends. The GM answers each question with one word, such as \\\"yes,\\\" \\\"no,\\\" \\\"maybe,\\\" \\\"never,\\\" \\\"irrelevant,\\\" or \\\"unclear\\\" (if the entity doesn't know the answer to the question). If a one-word answer would be misleading, the GM might instead offer a short phrase as an answer.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": true,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"int\",\n \"name\": \"INT\",\n \"url\": \"/api/ability-scores/int\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"On a failure, you take 6d6 psychic damage and are insane until you finish a long rest.\"\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/contact-other-plane\"\n },\n {\n \"index\": \"contagion\",\n \"name\": \"Contagion\",\n \"desc\": [\n \"Your touch inflicts disease. Make a melee spell attack against a creature within your reach. On a hit, you afflict the creature with a disease of your choice from any of the ones described below.\",\n \"At the end of each of the target's turns, it must make a constitution saving throw. After failing three of these saving throws, the disease's effects last for the duration, and the creature stops making these saves. After succeeding on three of these saving throws, the creature recovers from the disease, and the spell ends.\",\n \"Since this spell induces a natural disease in its target, any effect that removes a disease or otherwise ameliorates a disease's effects apply to it.\",\n \"***Blinding Sickness.*** Pain grips the creature's mind, and its eyes turn milky white. The creature has disadvantage on wisdom checks and wisdom saving throws and is blinded.\",\n \"***Filth Fever.*** A raging fever sweeps through the creature's body. The creature has disadvantage on strength checks, strength saving throws, and attack rolls that use Strength.\",\n \"***Flesh Rot.*** The creature's flesh decays. The creature has disadvantage on Charisma checks and vulnerability to all damage.\",\n \"***Mindfire.*** The creature's mind becomes feverish. The creature has disadvantage on intelligence checks and intelligence saving throws, and the creature behaves as if under the effects of the confusion spell during combat.\",\n \"***Seizure.*** The creature is overcome with shaking. The creature has disadvantage on dexterity checks, dexterity saving throws, and attack rolls that use Dexterity.\",\n \"***Slimy Doom.*** The creature begins to bleed uncontrollably. The creature has disadvantage on constitution checks and constitution saving throws. In addition, whenever the creature takes damage, it is stunned until the end of its next turn.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"7 days\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"attack_type\": \"melee\",\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"After succeeding on three of these saving throws, the creature recovers from the disease, and the spell ends.\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/contagion\"\n },\n {\n \"index\": \"contingency\",\n \"name\": \"Contingency\",\n \"desc\": [\n \"Choose a spell of 5th level or lower that you can cast, that has a casting time of 1 action, and that can target you. You cast that spell--called the contingent spell--as part of casting contingency, expending spell slots for both, but the contingent spell doesn't come into effect. Instead, it takes effect when a certain circumstance occurs. You describe that circumstance when you cast the two spells. For example, a contingency cast with water breathing might stipulate that water breathing comes into effect when you are engulfed in water or a similar liquid.\",\n \"The contingent spell takes effect immediately after the circumstance is met for the first time, whether or not you want it to. and then contingency ends.\",\n \"The contingent spell takes effect only on you, even if it can normally target others. You can use only one contingency spell at a time. If you cast this spell again, the effect of another contingency spell on you ends. Also, contingency ends on you if its material component is ever not on your person.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A statuette of yourself carved from ivory and decorated with gems worth at least 1,500 gp.\",\n \"ritual\": false,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/contingency\"\n },\n {\n \"index\": \"continual-flame\",\n \"name\": \"Continual Flame\",\n \"desc\": [\n \"A flame, equivalent in brightness to a torch, springs forth from an object that you touch. The effect looks like a regular flame, but it creates no heat and doesn't use oxygen. A continual flame can be covered or hidden but not smothered or quenched.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Ruby dust worth 50 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/continual-flame\"\n },\n {\n \"index\": \"control-water\",\n \"name\": \"Control Water\",\n \"desc\": [\n \"Until the spell ends, you control any freestanding water inside an area you choose that is a cube up to 100 feet on a side. You can choose from any of the following effects when you cast this spell. As an action on your turn, you can repeat the same effect or choose a different one.\",\n \"***Flood.*** You cause the water level of all standing water in the area to rise by as much as 20 feet. If the area includes a shore, the flooding water spills over onto dry land.\",\n \"If you choose an area in a large body of water, you instead create a 20-foot tall wave that travels from one side of the area to the other and then crashes down. Any Huge or smaller vehicles in the wave's path are carried with it to the other side. Any Huge or smaller vehicles struck by the wave have a 25 percent chance of capsizing.\",\n \"The water level remains elevated until the spell ends or you choose a different effect. If this effect produced a wave, the wave repeats on the start of your next turn while the flood effect lasts.\",\n \"***Part Water.*** You cause water in the area to move apart and create a trench. The trench extends across the spell's area, and the separated water forms a wall to either side. The trench remains until the spell ends or you choose a different effect. The water then slowly fills in the trench over the course of the next round until the normal water level is restored.\",\n \"***Redirect Flow.*** You cause flowing water in the area to move in a direction you choose, even if the water has to flow over obstacles, up walls, or in other unlikely directions. The water in the area moves as you direct it, but once it moves beyond the spell's area, it resumes its flow based on the terrain conditions. The water continues to move in the direction you chose until the spell ends or you choose a different effect.\",\n \"***Whirlpool.*** This effect requires a body of water at least 50 feet square and 25 feet deep. You cause a whirlpool to form in the center of the area. The whirlpool forms a vortex that is 5 feet wide at the base, up to 50 feet wide at the top, and 25 feet tall. Any creature or object in the water and within 25 feet of the vortex is pulled 10 feet toward it. A creature can swim away from the vortex by making a Strength (Athletics) check against your spell save DC.\",\n \"When a creature enters the vortex for the first time on a turn or starts its turn there, it must make a strength saving throw. On a failed save, the creature takes 2d8 bludgeoning damage and is caught in the vortex until the spell ends. On a successful save, the creature takes half damage, and isn't caught in the vortex. A creature caught in the vortex can use its action to try to swim away from the vortex as described above, but has disadvantage on the Strength (Athletics) check to do so.\",\n \"The first time each turn that an object enters the vortex, the object takes 2d8 bludgeoning damage; this damage occurs each round it remains in the vortex.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of water and a pinch of dust.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"bludgeoning\",\n \"name\": \"Bludgeoning\",\n \"url\": \"/api/damage-types/bludgeoning\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"2d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"str\",\n \"name\": \"STR\",\n \"url\": \"/api/ability-scores/str\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/control-water\"\n },\n {\n \"index\": \"control-weather\",\n \"name\": \"Control Weather\",\n \"desc\": [\n \"You take control of the weather within 5 miles of you for the duration. You must be outdoors to cast this spell. Moving to a place where you don't have a clear path to the sky ends the spell early.\",\n \"When you cast the spell, you change the current weather conditions, which are determined by the GM based on the climate and season. You can change precipitation, temperature, and wind. It takes 1d4 x 10 minutes for the new conditions to take effect. Once they do so, you can change the conditions again. When the spell ends, the weather gradually returns to normal.\",\n \"When you change the weather conditions, find a current condition on the following tables and change its stage by one, up or down. When changing the wind, you can change its direction.\",\n \"##### Precipitation\",\n \"| Stage | Condition |\",\n \"|---|---|\",\n \"| 1 | Clear |\",\n \"| 2 | Light clouds |\",\n \"| 3 | Overcast or ground fog |\",\n \"| 4 | Rain, hail, or snow |\",\n \"| 5 | Torrential rain, driving hail, or blizzard |\",\n \"##### Temperature\",\n \"| Stage | Condition |\",\n \"|---|---|\",\n \"| 1 | Unbearable heat |\",\n \"| 2 | Hot |\",\n \"| 3 | Warm |\",\n \"| 4 | Cool |\",\n \"| 5 | Cold |\",\n \"| 6 | Arctic cold |\",\n \"##### Wind\",\n \"| Stage | Condition |\",\n \"|---|---|\",\n \"| 1 | Calm |\",\n \"| 2 | Moderate wind |\",\n \"| 3 | Strong wind |\",\n \"| 4 | Gale |\",\n \"| 5 | Storm |\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Burning incense and bits of earth and wood mixed in water.\",\n \"ritual\": false,\n \"duration\": \"Up to 8 hours\",\n \"concentration\": true,\n \"casting_time\": \"10 minutes\",\n \"level\": 8,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/control-weather\"\n },\n {\n \"index\": \"counterspell\",\n \"name\": \"Counterspell\",\n \"desc\": [\n \"You attempt to interrupt a creature in the process of casting a spell. If the creature is casting a spell of 3rd level or lower, its spell fails and has no effect. If it is casting a spell of 4th level or higher, make an ability check using your spellcasting ability. The DC equals 10 + the spell's level. On a success, the creature's spell fails and has no effect.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the interrupted spell has no effect if its level is less than or equal to the level of the spell slot you used.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 reaction\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/counterspell\"\n },\n {\n \"index\": \"create-food-and-water\",\n \"name\": \"Create Food and Water\",\n \"desc\": [\n \"You create 45 pounds of food and 30 gallons of water on the ground or in containers within range, enough to sustain up to fifteen humanoids or five steeds for 24 hours. The food is bland but nourishing, and spoils if uneaten after 24 hours. The water is clean and doesn't go bad.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/create-food-and-water\"\n },\n {\n \"index\": \"create-undead\",\n \"name\": \"Create Undead\",\n \"desc\": [\n \"You can cast this spell only at night. Choose up to three corpses of Medium or Small humanoids within range. Each corpse becomes a ghoul under your control. (The GM has game statistics for these creatures.)\",\n \"As a bonus action on each of your turns, you can mentally command any creature you animated with this spell if the creature is within 120 feet of you (if you control multiple creatures, you can command any or all of them at the same time, issuing the same command to each one). You decide what action the creature will take and where it will move during its next turn, or you can issue a general command, such as to guard a particular chamber or corridor. If you issue no commands, the creature only defends itself against hostile creatures. Once given an order, the creature continues to follow it until its task is complete.\",\n \"The creature is under your control for 24 hours, after which it stops obeying any command you have given it. To maintain control of the creature for another 24 hours, you must cast this spell on the creature before the current 24-hour period ends. This use of the spell reasserts your control over up to three creatures you have animated with this spell, rather than animating new ones.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 7th-level spell slot, you can animate or reassert control over four ghouls. When you cast this spell using an 8th-level spell slot, you can animate or reassert control over five ghouls or two ghasts or wights. When you cast this spell using a 9th-level spell slot, you can animate or reassert control over six ghouls, three ghasts or wights, or two mummies.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"One clay pot filled with grave dirt, one clay pot filled with brackish water, and one 150 gp black onyx stone for each corpse.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/create-undead\"\n },\n {\n \"index\": \"create-or-destroy-water\",\n \"name\": \"Create or Destroy Water\",\n \"desc\": [\n \"You either create or destroy water.\",\n \"***Create Water.*** You create up to 10 gallons of clean water within range in an open container. Alternatively, the water falls as rain in a 30-foot cube within range.\",\n \"***Destroy Water.*** You destroy up to 10 gallons of water in an open container within range. Alternatively, you destroy fog in a 30-foot cube within range.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you create or destroy 10 additional gallons of water, or the size of the cube increases by 5 feet, for each slot level above 1st.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of water if creating water, or a few grains of sand if destroying it.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/create-or-destroy-water\"\n },\n {\n \"index\": \"creation\",\n \"name\": \"Creation\",\n \"desc\": [\n \"You pull wisps of shadow material from the Shadowfell to create a nonliving object of vegetable matter within range: soft goods, rope, wood, or something similar. You can also use this spell to create mineral objects such as stone, crystal, or metal. The object created must be no larger than a 5-foot cube, and the object must be of a form and material that you have seen before.\",\n \"The duration depends on the object's material. If the object is composed of multiple materials, use the shortest duration.\",\n \"| Material | Duration |\",\n \"|---|---|\",\n \"| Vegetable matter | 1 day |\",\n \"| Stone or crystal | 12 hours |\",\n \"| Precious metals | 1 hour |\",\n \"| Gems | 10 minutes |\",\n \"| Adamantine or mithral | 1 minute |\",\n \"Using any material created by this spell as another spell's material component causes that spell to fail.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the cube increases by 5 feet for each slot level above 5th.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny piece of matter of the same type of the item you plan to create.\",\n \"ritual\": false,\n \"duration\": \"Special\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/creation\"\n },\n {\n \"index\": \"cure-wounds\",\n \"name\": \"Cure Wounds\",\n \"desc\": [\n \"A creature you touch regains a number of hit points equal to 1d8 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the healing increases by 1d8 for each slot level above 1st.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"heal_at_slot_level\": {\n \"1\": \"1d8 + MOD\",\n \"2\": \"2d8 + MOD\",\n \"3\": \"3d8 + MOD\",\n \"4\": \"4d8 + MOD\",\n \"5\": \"5d8 + MOD\",\n \"6\": \"6d8 + MOD\",\n \"7\": \"7d8 + MOD\",\n \"8\": \"8d8 + MOD\",\n \"9\": \"9d8 + MOD\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/cure-wounds\"\n },\n {\n \"index\": \"dancing-lights\",\n \"name\": \"Dancing Lights\",\n \"desc\": [\n \"You create up to four torch-sized lights within range, making them appear as torches, lanterns, or glowing orbs that hover in the air for the duration. You can also combine the four lights into one glowing vaguely humanoid form of Medium size. Whichever form you choose, each light sheds dim light in a 10-foot radius.\",\n \"As a bonus action on your turn, you can move the lights up to 60 feet to a new spot within range. A light must be within 20 feet of another light created by this spell, and a light winks out if it exceeds the spell's range.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of phosphorus or wychwood, or a glowworm.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/dancing-lights\"\n },\n {\n \"index\": \"darkness\",\n \"name\": \"Darkness\",\n \"desc\": [\n \"Magical darkness spreads from a point you choose within range to fill a 15-foot-radius sphere for the duration. The darkness spreads around corners. A creature with darkvision can't see through this darkness, and nonmagical light can't illuminate it.\",\n \"If the point you choose is on an object you are holding or one that isn't being worn or carried, the darkness emanates from the object and moves with it. Completely covering the source of the darkness with an opaque object, such as a bowl or a helm, blocks the darkness.\",\n \"If any of this spell's area overlaps with an area of light created by a spell of 2nd level or lower, the spell that created the light is dispelled.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"Bat fur and a drop of pitch or piece of coal.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/darkness\"\n },\n {\n \"index\": \"darkvision\",\n \"name\": \"Darkvision\",\n \"desc\": [\n \"You touch a willing creature to grant it the ability to see in the dark. For the duration, that creature has darkvision out to a range of 60 feet.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Either a pinch of dried carrot or an agate.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/darkvision\"\n },\n {\n \"index\": \"daylight\",\n \"name\": \"Daylight\",\n \"desc\": [\n \"A 60-foot-radius sphere of light spreads out from a point you choose within range. The sphere is bright light and sheds dim light for an additional 60 feet.\",\n \"If you chose a point on an object you are holding or one that isn't being worn or carried, the light shines from the object and moves with it. Completely covering the affected object with an opaque object, such as a bowl or a helm, blocks the light.\",\n \"If any of this spell's area overlaps with an area of darkness created by a spell of 3rd level or lower, the spell that created the darkness is dispelled.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/daylight\"\n },\n {\n \"index\": \"death-ward\",\n \"name\": \"Death Ward\",\n \"desc\": [\n \"You touch a creature and grant it a measure of protection from death.\",\n \"The first time the target would drop to 0 hit points as a result of taking damage, the target instead drops to 1 hit point, and the spell ends.\",\n \"If the spell is still in effect when the target is subjected to an effect that would kill it instantaneously without dealing damage, that effect is instead negated against the target, and the spell ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/death-ward\"\n },\n {\n \"index\": \"delayed-blast-fireball\",\n \"name\": \"Delayed Blast Fireball\",\n \"desc\": [\n \"A beam of yellow light flashes from your pointing finger, then condenses to linger at a chosen point within range as a glowing bead for the duration. When the spell ends, either because your concentration is broken or because you decide to end it, the bead blossoms with a low roar into an explosion of flame that spreads around corners. Each creature in a 20-foot-radius sphere centered on that point must make a dexterity saving throw. A creature takes fire damage equal to the total accumulated damage on a failed save, or half as much damage on a successful one.\",\n \"The spell's base damage is 12d6. If at the end of your turn the bead has not yet detonated, the damage increases by 1d6.\",\n \"If the glowing bead is touched before the interval has expired, the creature touching it must make a dexterity saving throw. On a failed save, the spell ends immediately, causing the bead to erupt in flame. On a successful save, the creature can throw the bead up to 40 feet. When it strikes a creature or a solid object, the spell ends, and the bead explodes.\",\n \"The fire damages objects in the area and ignites flammable objects that aren't being worn or carried.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 8th level or higher, the base damage increases by 1d6 for each slot level above 7th.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny ball of bat guano and sulfur.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"7\": \"12d6\",\n \"8\": \"13d6\",\n \"9\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/delayed-blast-fireball\"\n },\n {\n \"index\": \"demiplane\",\n \"name\": \"Demiplane\",\n \"desc\": [\n \"You create a shadowy door on a flat solid surface that you can see within range. The door is large enough to allow Medium creatures to pass through unhindered. When opened, the door leads to a demiplane that appears to be an empty room 30 feet in each dimension, made of wood or stone. When the spell ends, the door disappears, and any creatures or objects inside the demiplane remain trapped there, as the door also disappears from the other side.\",\n \"Each time you cast this spell, you can create a new demiplane, or have the shadowy door connect to a demiplane you created with a previous casting of this spell. Additionally, if you know the nature and contents of a demiplane created by a casting of this spell by another creature, you can have the shadowy door connect to its demiplane instead.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/demiplane\"\n },\n {\n \"index\": \"detect-evil-and-good\",\n \"name\": \"Detect Evil and Good\",\n \"desc\": [\n \"For the duration, you know if there is an aberration, celestial, elemental, fey, fiend, or undead within 30 feet of you, as well as where the creature is located. Similarly, you know if there is a place or object within 30 feet of you that has been magically consecrated or desecrated.\",\n \"The spell can penetrate most barriers, but it is blocked by 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/detect-evil-and-good\"\n },\n {\n \"index\": \"detect-magic\",\n \"name\": \"Detect Magic\",\n \"desc\": [\n \"For the duration, you sense the presence of magic within 30 feet of you. If you sense magic in this way, you can use your action to see a faint aura around any visible creature or object in the area that bears magic, and you learn its school of magic, if any.\",\n \"The spell can penetrate most barriers, but it is blocked by 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/detect-magic\"\n },\n {\n \"index\": \"detect-poison-and-disease\",\n \"name\": \"Detect Poison and Disease\",\n \"desc\": [\n \"For the duration, you can sense the presence and location of poisons, poisonous creatures, and diseases within 30 feet of you. You also identify the kind of poison, poisonous creature, or disease in each case.\",\n \"The spell can penetrate most barriers, but it is blocked by 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A yew leaf.\",\n \"ritual\": true,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/detect-poison-and-disease\"\n },\n {\n \"index\": \"detect-thoughts\",\n \"name\": \"Detect Thoughts\",\n \"desc\": [\n \"For the duration, you can read the thoughts of certain creatures. When you cast the spell and as your action on each turn until the spell ends, you can focus your mind on any one creature that you can see within 30 feet of you. If the creature you choose has an Intelligence of 3 or lower or doesn't speak any language, the creature is unaffected.\",\n \"You initially learn the surface thoughts of the creature - what is most on its mind in that moment. As an action, you can either shift your attention to another creature's thoughts or attempt to probe deeper into the same creature's mind. If you probe deeper, the target must make a Wisdom saving throw. If it fails, you gain insight into its reasoning (if any), its emotional state, and something that looms large in its mind (such as something it worries over, loves, or hates). If it succeeds, the spell ends. Either way, the target knows that you are probing into its mind, and unless you shift your attention to another creature's thoughts, the creature can use its action on its turn to make an Intelligence check contested by your Intelligence check; if it succeeds, the spell ends.\",\n \"Questions verbally directed at the target creature naturally shape the course of its thoughts, so this spell is particularly effective as part of an interrogation.\",\n \"You can also use this spell to detect the presence of thinking creatures you can't see. When you cast the spell or as your action during the duration, you can search for thoughts within 30 feet of you. The spell can penetrate barriers, but 2 feet of rock, 2 inches of any metal other than lead, or a thin sheet of lead blocks you. You can't detect a creature with an Intelligence of 3 or lower or one that doesn't speak any language.\",\n \"Once you detect the presence of a creature in this way, you can read its thoughts for the rest of the duration as described above, even if you can't see it, but it must still be within range.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A copper coin.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/detect-thoughts\"\n },\n {\n \"index\": \"dimension-door\",\n \"name\": \"Dimension Door\",\n \"desc\": [\n \"You teleport yourself from your current location to any other spot within range. You arrive at exactly the spot desired. It can be a place you can see, one you can visualize, or one you can describe by stating distance and direction, such as \\\"200 feet straight downward\\\" or \\\"upward to the northwest at a 45-degree angle, 300 feet.\\\"\",\n \"You can bring along objects as long as their weight doesn't exceed what you can carry. You can also bring one willing creature of your size or smaller who is carrying gear up to its carrying capacity. The creature must be within 5 feet of you when you cast this spell.\",\n \"If you would arrive in a place already occupied by an object or a creature, you and any creature traveling with you each take 4d6 force damage, and the spell fails to teleport you.\"\n ],\n \"range\": \"500 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"4d6\"\n }\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dimension-door\"\n },\n {\n \"index\": \"disguise-self\",\n \"name\": \"Disguise Self\",\n \"desc\": [\n \"You make yourself--including your clothing, armor, weapons, and other belongings on your person--look different until the spell ends or until you use your action to dismiss it. You can seem 1 foot shorter or taller and can appear thin, fat, or in between. You can't change your body type, so you must adopt a form that has the same basic arrangement of limbs. Otherwise, the extent of the illusion is up to you.\",\n \"The changes wrought by this spell fail to hold up to physical inspection. For example, if you use this spell to add a hat to your outfit, objects pass through the hat, and anyone who touches it would feel nothing or would feel your head and hair. If you use this spell to appear thinner than you are, the hand of someone who reaches out to touch you would bump into you while it was seemingly still in midair.\",\n \"To discern that you are disguised, a creature can use its action to inspect your appearance and must succeed on an Intelligence (Investigation) check against your spell save DC.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/disguise-self\"\n },\n {\n \"index\": \"disintegrate\",\n \"name\": \"Disintegrate\",\n \"desc\": [\n \"A thin green ray springs from your pointing finger to a target that you can see within range. The target can be a creature, an object, or a creation of magical force, such as the wall created by wall of force.\",\n \"A creature targeted by this spell must make a dexterity saving throw. On a failed save, the target takes 10d6 + 40 force damage. If this damage reduces the target to 0 hit points, it is disintegrated.\",\n \"A disintegrated creature and everything it is wearing and carrying, except magic items, are reduced to a pile of fine gray dust. The creature can be restored to life only by means of a true resurrection or a wish spell.\",\n \"This spell automatically disintegrates a Large or smaller nonmagical object or a creation of magical force. If the target is a Huge or larger object or creation of force, this spell disintegrates a 10-foot-cube portion of it. A magic item is unaffected by this spell.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the damage increases by 3d6 for each slot level above 6th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A lodestone and a pinch of dust.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"10d6 + 40\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/disintegrate\"\n },\n {\n \"index\": \"dispel-evil-and-good\",\n \"name\": \"Dispel Evil and Good\",\n \"desc\": [\n \"Shimmering energy surrounds and protects you from fey, undead, and creatures originating from beyond the Material Plane. For the duration, celestials, elementals, fey, fiends, and undead have disadvantage on attack rolls against you.\",\n \"You can end the spell early by using either of the following special functions.\",\n \"***Break Enchantment.*** As your action, you touch a creature you can reach that is charmed, frightened, or possessed by a celestial, an elemental, a fey, a fiend, or an undead. The creature you touch is no longer charmed, frightened, or possessed by such creatures.\",\n \"***Dismissal.*** As your action, make a melee spell attack against a celestial, an elemental, a fey, a fiend, or an undead you can reach. On a hit, you attempt to drive the creature back to its home plane. The creature must succeed on a charisma saving throw or be sent back to its home plane (if it isn't there already). If they aren't on their home plane, undead are sent to the Shadowfell, and fey are sent to the Feywild.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Holy water or powdered silver and iron.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"The creature must succeed on a charisma saving throw or be sent back to its home plane (if it isn't there already)\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dispel-evil-and-good\"\n },\n {\n \"index\": \"dispel-magic\",\n \"name\": \"Dispel Magic\",\n \"desc\": [\n \"Choose one creature, object, or magical effect within range. Any spell of 3rd level or lower on the target ends. For each spell of 4th level or higher on the target, make an ability check using your spellcasting ability. The DC equals 10 + the spell's level. On a successful check, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, you automatically end the effects of a spell on the target if the spell's level is equal to or less than the level of the spell slot you used.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/dispel-magic\"\n },\n {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"desc\": [\n \"Your magic and an offering put you in contact with a god or a god's servants. You ask a single question concerning a specific goal, event, or activity to occur within 7 days. The GM offers a truthful reply. The reply might be a short phrase, a cryptic rhyme, or an omen.\",\n \"The spell doesn't take into account any possible circumstances that might change the outcome, such as the casting of additional spells or the loss or gain of a companion.\",\n \"If you cast the spell two or more times before finishing your next long rest, there is a cumulative 25 percent chance for each casting after the first that you get a random reading. The GM makes this roll in secret.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Incense and a sacrificial offering appropriate to your religion, together worth at least 25gp, which the spell consumes.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/divination\"\n },\n {\n \"index\": \"divine-favor\",\n \"name\": \"Divine Favor\",\n \"desc\": [\n \"Your prayer empowers you with divine radiance. Until the spell ends, your weapon attacks deal an extra 1d4 radiant damage on a hit.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"1d4\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/divine-favor\"\n },\n {\n \"index\": \"divine-word\",\n \"name\": \"Divine Word\",\n \"desc\": [\n \"You utter a divine word, imbued with the power that shaped the world at the dawn of creation. Choose any number of creatures you can see within range. Each creature that can hear you must make a Charisma saving throw. On a failed save, a creature suffers an effect based on its current hit points:\",\n \"- 50 hit points or fewer: deafened for 1 minute\",\n \"- 40 hit points or fewer: deafened and blinded for 10 minutes\",\n \"- 30 hit points or fewer: blinded, deafened, and stunned for 1 hour\",\n \"- 20 hit points or fewer: killed instantly\",\n \"Regardless of its current hit points, a celestial, an elemental, a fey, or a fiend that fails its save is forced back to its plane of origin (if it isn't there already) and can't return to your current plane for 24 hours by any means short of a wish spell.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 7,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, a creature suffers an effect based on its current hit points.\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/divine-word\"\n },\n {\n \"index\": \"dominate-beast\",\n \"name\": \"Dominate Beast\",\n \"desc\": [\n \"You attempt to beguile a creature that you can see within range. It must succeed on a wisdom saving throw or be charmed by you for the duration. If you or creatures that are friendly to you are fighting it, it has advantage on the saving throw.\",\n \"While the creature is charmed, you have a telepathic link with it as long as the two of you are on the same plane of existence. You can use this telepathic link to issue commands to the creature while you are conscious (no action required), which it does its best to obey. You can specify a simple and general course of action, such as \\\"Attack that creature,\\\" \\\"Run over there,\\\" or \\\"Fetch that object.\\\" If the creature completes the order and doesn't receive further direction from you, it defends and preserves itself to the best of its ability.\",\n \"You can use your action to take total and precise control of the target. Until the end of your next turn, the creature takes only the actions you choose, and doesn't do anything that you don't allow it to do. During this time, you can also cause the creature to use a reaction, but this requires you to use your own reaction as well. Each time the target takes damage, it makes a new wisdom saving throw against the spell. If the saving throw succeeds, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell with a 9th level spell slot, the duration is concentration, up to 8 hours.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dominate-beast\"\n },\n {\n \"index\": \"dominate-monster\",\n \"name\": \"Dominate Monster\",\n \"desc\": [\n \"You attempt to beguile a creature that you can see within range. It must succeed on a wisdom saving throw or be charmed by you for the duration. If you or creatures that are friendly to you are fighting it, it has advantage on the saving throw.\",\n \"While the creature is charmed, you have a telepathic link with it as long as the two of you are on the same plane of existence. You can use this telepathic link to issue commands to the creature while you are conscious (no action required), which it does its best to obey. You can specify a simple and general course of action, such as \\\"Attack that creature,\\\" \\\"Run over there,\\\" or \\\"Fetch that object.\\\" If the creature completes the order and doesn't receive further direction from you, it defends and preserves itself to the best of its ability.\",\n \"You can use your action to take total and precise control of the target. Until the end of your next turn, the creature takes only the actions you choose, and doesn't do anything that you don't allow it to do. During this time, you can also cause the creature to use a reaction, but this requires you to use your own reaction as well.\",\n \"Each time the target takes damage, it makes a new wisdom saving throw against the spell. If the saving throw succeeds, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell with a 9th-level spell slot, the duration is concentration, up to 8 hours.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On failure, the creature is charmed by you for the duration.\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dominate-monster\"\n },\n {\n \"index\": \"dominate-person\",\n \"name\": \"Dominate Person\",\n \"desc\": [\n \"You attempt to beguile a humanoid that you can see within range. It must succeed on a wisdom saving throw or be charmed by you for the duration. If you or creatures that are friendly to you are fighting it, it has advantage on the saving throw.\",\n \"While the target is charmed, you have a telepathic link with it as long as the two of you are on the same plane of existence. You can use this telepathic link to issue commands to the creature while you are conscious (no action required), which it does its best to obey. You can specify a simple and general course of action, such as \\\"Attack that creature,\\\" \\\"Run over there,\\\" or \\\"Fetch that object.\\\" If the creature completes the order and doesn't receive further direction from you, it defends and preserves itself to the best of its ability.\",\n \"You can use your action to take total and precise control of the target. Until the end of your next turn, the creature takes only the actions you choose, and doesn't do anything that you don't allow it to do. During this time you can also cause the creature to use a reaction, but this requires you to use your own reaction as well.\",\n \"Each time the target takes damage, it makes a new wisdom saving throw against the spell. If the saving throw succeeds, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 6th-level spell slot, the duration is concentration, up to 10 minutes. When you use a 7th-level spell slot, the duration is concentration, up to 1 hour. When you use a spell slot of 8th level or higher, the duration is concentration, up to 8 hours.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"Each time the target takes damage, it makes a new wisdom saving throw against the spell. If the saving throw succeeds, the spell ends.\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dominate-person\"\n },\n {\n \"index\": \"dream\",\n \"name\": \"Dream\",\n \"desc\": [\n \"This spell shapes a creature's dreams. Choose a creature known to you as the target of this spell. The target must be on the same plane of existence as you. Creatures that don't sleep, such as elves, can't be contacted by this spell. You, or a willing creature you touch, enters a trance state, acting as a messenger.\",\n \"While in the trance, the messenger is aware of his or her surroundings, but can't take actions or move.\",\n \"If the target is asleep, the messenger appears in the target's dreams and can converse with the target as long as it remains asleep, through the duration of the spell. The messenger can also shape the environment of the dream, creating landscapes, objects, and other images. The messenger can emerge from the trance at any time, ending the effect of the spell early. The target recalls the dream perfectly upon waking. If the target is awake when you cast the spell, the messenger knows it, and can either end the trance (and the spell) or wait for the target to fall asleep, at which point the messenger appears in the target's dreams.\",\n \"You can make the messenger appear monstrous and terrifying to the target. If you do, the messenger can deliver a message of no more than ten words and then the target must make a wisdom saving throw. On a failed save, echoes of the phantasmal monstrosity spawn a nightmare that lasts the duration of the target's sleep and prevents the target from gaining any benefit from that rest. In addition, when the target wakes up, it takes 3d6 psychic damage.\",\n \"If you have a body part, lock of hair, clipping from a nail, or similar portion of the target's body, the target makes its saving throw with disadvantage.\"\n ],\n \"range\": \"Special\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A handful of sand, a dab of ink, and a writing quill plucked from a sleeping bird.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"psychic\",\n \"name\": \"Psychic\",\n \"url\": \"/api/damage-types/psychic\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"3d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, echoes of the phantasmal monstrosity spawn a nightmare that lasts the duration of the target's sleep and prevents the target from gaining any benefit from that rest.\"\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/dream\"\n },\n {\n \"index\": \"druidcraft\",\n \"name\": \"Druidcraft\",\n \"desc\": [\n \"Whispering to the spirits of nature, you create one of the following effects within 'range':\",\n \"- You create a tiny, harmless sensory effect that predicts what the weather will be at your location for the next 24 hours. The effect might manifest as a golden orb for clear skies, a cloud for rain, falling snowflakes for snow, and so on. This effect persists for 1 round.\",\n \"- You instantly make a flower bloom, a seed pod open, or a leaf bud bloom.\",\n \"- You create an instantaneous, harmless sensory effect, such as falling leaves, a puff of wind, the sound of a small animal, or the faint order of skunk. The effect must fit in a 5-foot cube.\",\n \"- You instantly light or snuff out a candle, a torch, or a small campfire.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/druidcraft\"\n },\n {\n \"index\": \"earthquake\",\n \"name\": \"Earthquake\",\n \"desc\": [\n \"You create a seismic disturbance at a point on the ground that you can see within range. For the duration, an intense tremor rips through the ground in a 100-foot-radius circle centered on that point and shakes creatures and structures in contact with the ground in that area.\",\n \"The ground in the area becomes difficult terrain. Each creature on the ground that is concentrating must make a constitution saving throw. On a failed save, the creature's concentration is broken.\",\n \"When you cast this spell and at the end of each turn you spend concentrating on it, each creature on the ground in the area must make a dexterity saving throw. On a failed save, the creature is knocked prone.\",\n \"This spell can have additional effects depending on the terrain in the area, as determined by the GM.\",\n \"Fissures. Fissures open throughout the spell's area at the start of your next turn after you cast the spell. A total of 1d6 such fissures open in locations chosen by the GM. Each is 1d10 x 10 feet deep, 10 feet wide, and extends from one edge of the spell's area to the opposite side. A creature standing on a spot where a fissure opens must succeed on a dexterity saving throw or fall in. A creature that successfully saves moves with the fissure's edge as it opens.\",\n \"A fissure that opens beneath a structure causes it to automatically collapse (see below).\",\n \"Structures. The tremor deals 50 bludgeoning damage to any structure in contact with the ground in the area when you cast the spell and at the start of each of your turns until the spell ends. If a structure drops to 0 hit points, it collapses and potentially damages nearby creatures. A creature within half the distance of a structure's height must make a dexterity saving throw. On a failed save, the creature takes 5d6 bludgeoning damage, is knocked prone, and is buried in the rubble, requiring a DC 20 Strength (Athletics) check as an action to escape. The GM can adjust the DC higher or lower, depending on the nature of the rubble. On a successful save, the creature takes half as much damage and doesn't fall prone or become buried.\"\n ],\n \"range\": \"500 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of dirt, a piece of rock, and a lump of clay.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/earthquake\"\n },\n {\n \"index\": \"eldritch-blast\",\n \"name\": \"Eldritch Blast\",\n \"desc\": [\n \"A beam of crackling energy streaks toward a creature within range. Make a ranged spell attack against the target. On a hit, the target takes 1d10 force damage. The spell creates more than one beam when you reach higher levels: two beams at 5th level, three beams at 11th level, and four beams at 17th level. You can direct the beams at the same target or at different ones. Make a separate attack roll for each beam.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d10\",\n \"5\": \"1d10\",\n \"11\": \"1d10\",\n \"17\": \"1d10\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/eldritch-blast\"\n },\n {\n \"index\": \"enhance-ability\",\n \"name\": \"Enhance Ability\",\n \"desc\": [\n \"You touch a creature and bestow upon it a magical enhancement. Choose one of the following effects; the target gains that effect until the spell ends.\",\n \"***Bear's Endurance.*** The target has advantage on constitution checks. It also gains 2d6 temporary hit points, which are lost when the spell ends.\",\n \"***Bull's Strength.*** The target has advantage on strength checks, and his or her carrying capacity doubles.\",\n \"***Cat's Grace.*** The target has advantage on dexterity checks. It also doesn't take damage from falling 20 feet or less if it isn't incapacitated.\",\n \"***Eagle's Splendor.*** The target has advantage on Charisma checks.\",\n \"***Fox's Cunning.*** The target has advantage on intelligence checks.\",\n \"***Owl's Wisdom.*** The target has advantage on wisdom checks.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you can target one additional creature for each slot level above 2nd.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Fur or a feather from a beast.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/enhance-ability\"\n },\n {\n \"index\": \"enlarge-reduce\",\n \"name\": \"Enlarge/Reduce\",\n \"desc\": [\n \"You cause a creature or an object you can see within range to grow larger or smaller for the duration. Choose either a creature or an object that is neither worn nor carried. If the target is unwilling, it can make a Constitution saving throw. On a success, the spell has no effect.\",\n \"If the target is a creature, everything it is wearing and carrying changes size with it. Any item dropped by an affected creature returns to normal size at once.\",\n \"***Enlarge.*** The target's size doubles in all dimensions, and its weight is multiplied by eight. This growth increases its size by one category-from Medium to Large, for example. If there isn't enough room for the target to double its size, the creature or object attains the maximum possible size in the space available. Until the spell ends, the target also has advantage on Strength checks and Strength saving throws. The target's weapons also grow to match its new size. While these weapons are enlarged, the target's attacks with them deal 1d4 extra damage.\",\n \"***Reduce.*** The target's size is halved in all dimensions, and its weight is reduced to one-eighth of normal. This reduction decreases its size by one category-from Medium to Small, for example. Until the spell ends, the target also has disadvantage on Strength checks and Strength saving throws. The target's weapons also shrink to match its new size. While these weapons are reduced, the target's attacks with them deal 1d4 less damage (this can't reduce the damage below 1).\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch iron powder.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/enlarge-reduce\"\n },\n {\n \"index\": \"entangle\",\n \"name\": \"Entangle\",\n \"desc\": [\n \"Grasping weeds and vines sprout from the ground in a 20-foot square starting form a point within range. For the duration, these plants turn the ground in the area into difficult terrain.\",\n \"A creature in the area when you cast the spell must succeed on a strength saving throw or be restrained by the entangling plants until the spell ends. A creature restrained by the plants can use its action to make a Strength check against your spell save DC. On a success, it frees itself.\",\n \"When the spell ends, the conjured plants wilt away.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"str\",\n \"name\": \"STR\",\n \"url\": \"/api/ability-scores/str\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/entangle\"\n },\n {\n \"index\": \"enthrall\",\n \"name\": \"Enthrall\",\n \"desc\": [\n \"You weave a distracting string of words, causing creatures of your choice that you can see within range and that can hear you to make a wisdom saving throw. Any creature that can't be charmed succeeds on this saving throw automatically, and if you or your companions are fighting a creature, it has advantage on the save. On a failed save, the target has disadvantage on Wisdom (Perception) checks made to perceive any creature other than you until the spell ends or until the target can no longer hear you. The spell ends if you are incapacitated or can no longer speak.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/enthrall\"\n },\n {\n \"index\": \"etherealness\",\n \"name\": \"Etherealness\",\n \"desc\": [\n \"You step into the border regions of the Ethereal Plane, in the area where it overlaps with your current plane. You remain in the Border Ethereal for the duration or until you use your action to dismiss the spell. During this time, you can move in any direction. If you move up or down, every foot of movement costs an extra foot. You can see and hear the plane you originated from, but everything there looks gray, and you can't see anything more than 60 feet away.\",\n \"While on the Ethereal Plane, you can only affect and be affected by other creatures on that plane. Creatures that aren't on the Ethereal Plane can't perceive you and can't interact with you, unless a special ability or magic has given them the ability to do so.\",\n \"You ignore all objects and effects that aren't on the Ethereal Plane, allowing you to move through objects you perceive on the plane you originated from.\",\n \"When the spell ends, you immediately return to the plane you originated from in the spot you currently occupy. If you occupy the same spot as a solid object or creature when this happens, you are immediately shunted to the nearest unoccupied space that you can occupy and take force damage equal to twice the number of feet you are moved.\",\n \"This spell has no effect if you cast it while you are on the Ethereal Plane or a plane that doesn't border it, such as one of the Outer Planes.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 8th level or higher, you can target up to three willing creatures (including you) for each slot level above 7th. The creatures must be within 10 feet of you when you cast the spell.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/etherealness\"\n },\n {\n \"index\": \"expeditious-retreat\",\n \"name\": \"Expeditious Retreat\",\n \"desc\": [\n \"This spell allows you to move at an incredible pace. When you cast this spell, and then as a bonus action on each of your turns until the spell ends, you can take the Dash action.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/expeditious-retreat\"\n },\n {\n \"index\": \"eyebite\",\n \"name\": \"Eyebite\",\n \"desc\": [\n \"For the spell's duration, your eyes become an inky void imbued with dread power. One creature of your choice within 60 feet of you that you can see must succeed on a wisdom saving throw or be affected by one of the following effects of your choice for the duration. On each of your turns until the spell ends, you can use your action to target another creature but can't target a creature again if it has succeeded on a saving throw against this casting of eyebite.\",\n \"***Asleep.*** The target falls unconscious. It wakes up if it takes any damage or if another creature uses its action to shake the sleeper awake.\",\n \"***Panicked.*** The target is frightened of you. On each of its turns, the frightened creature must take the Dash action and move away from you by the safest and shortest available route, unless there is nowhere to move. If the target moves to a place at least 60 feet away from you where it can no longer see you, this effect ends.\",\n \"***Sickened.*** The target has disadvantage on attack rolls and ability checks. At the end of each of its turns, it can make another wisdom saving throw. If it succeeds, the effect ends.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On failure, the target can be affected by one of the following effects of your choice for the duration. [Asleep. The target falls unconscious. It wakes up if it takes any damage or if another creature uses its action to shake the sleeper awake.] [Panicked. The target is frightened of you. On each of its turns, the frightened creature must take the Dash action and move away from you by the safest and shortest available route, unless there is nowhere to move. If the target moves to a place at least 60 feet away from you where it can no longer see you, this effect ends.] [Sickened. The target has disadvantage on attack rolls and ability checks. At the end of each of its turns, it can make another wisdom saving throw. If it succeeds, the effect ends.]\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/eyebite\"\n },\n {\n \"index\": \"fabricate\",\n \"name\": \"Fabricate\",\n \"desc\": [\n \"You convert raw materials into products of the same material. For example, you can fabricate a wooden bridge from a clump of trees, a rope from a patch of hemp, and clothes from flax or wool.\",\n \"Choose raw materials that you can see within range. You can fabricate a Large or smaller object (contained within a 10-foot cube, or eight connected 5-foot cubes), given a sufficient quantity of raw material. If you are working with metal, stone, or another mineral substance, however, the fabricated object can be no larger than Medium (contained within a single 5-foot cube). The quality of objects made by the spell is commensurate with the quality of the raw materials.\",\n \"Creatures or magic items can't be created or transmuted by this spell. You also can't use it to create items that ordinarily require a high degree of craftsmanship, such as jewelry, weapons, glass, or armor, unless you have proficiency with the type of artisan's tools used to craft such objects.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 4,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/fabricate\"\n },\n {\n \"index\": \"faerie-fire\",\n \"name\": \"Faerie Fire\",\n \"desc\": [\n \"Each object in a 20-foot cube within range is outlined in blue, green, or violet light (your choice). Any creature in the area when the spell is cast is also outlined in light if it fails a dexterity saving throw. For the duration, objects and affected creatures shed dim light in a 10-foot radius.\",\n \"Any attack roll against an affected creature or object has advantage if the attacker can see it, and the affected creature or object can't benefit from being invisible.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/faerie-fire\"\n },\n {\n \"index\": \"faithful-hound\",\n \"name\": \"Faithful Hound\",\n \"desc\": [\n \"You conjure a phantom watchdog in an unoccupied space that you can see within range, where it remains for the duration, until you dismiss it as an action, or until you move more than 100 feet away from it.\",\n \"The hound is invisible to all creatures except you and can't be harmed. When a Small or larger creature comes within 30 feet of it without first speaking the password that you specify when you cast this spell, the hound starts barking loudly. The hound sees invisible creatures and can see into the Ethereal Plane. It ignores illusions.\",\n \"At the start of each of your turns, the hound attempts to bite one creature within 5 feet of it that is hostile to you. The hound's attack bonus is equal to your spellcasting ability modifier + your proficiency bonus. On a hit, it deals 4d8 piercing damage.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny silver whistle, a piece of bone, and a thread\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"piercing\",\n \"name\": \"Piercing\",\n \"url\": \"/api/damage-types/piercing\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/faithful-hound\"\n },\n {\n \"index\": \"false-life\",\n \"name\": \"False Life\",\n \"desc\": [\n \"Bolstering yourself with a necromantic facsimile of life, you gain 1d4 + 4 temporary hit points for the duration.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you gain 5 additional temporary hit points for each slot level above 1st.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small amount of alcohol or distilled spirits.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"heal_at_slot_level\": {\n \"1\": \"1d4 + 4\",\n \"2\": \"1d4 + 9\",\n \"3\": \"1d4 + 14\",\n \"4\": \"1d4 + 19\",\n \"5\": \"1d4 + 24\",\n \"6\": \"1d4 + 29\",\n \"7\": \"1d4 + 34\",\n \"8\": \"1d4 + 39\",\n \"9\": \"1d4 + 44\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/false-life\"\n },\n {\n \"index\": \"fear\",\n \"name\": \"Fear\",\n \"desc\": [\n \"You project a phantasmal image of a creature's worst fears. Each creature in a 30-foot cone must succeed on a wisdom saving throw or drop whatever it is holding and become frightened for the duration.\",\n \"While frightened by this spell, a creature must take the Dash action and move away from you by the safest available route on each of its turns, unless there is nowhere to move. If the creature ends its turn in a location where it doesn't have line of sight to you, the creature can make a wisdom saving throw. On a successful save, the spell ends for that creature.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A white feather or the heart of a hen.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On fail, A creature drop whatever it is holding and become frightened for the duration.\"\n },\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/fear\"\n },\n {\n \"index\": \"feather-fall\",\n \"name\": \"Feather Fall\",\n \"desc\": [\n \"Choose up to five falling creatures within range. A falling creature's rate of descent slows to 60 feet per round until the spell ends. If the creature lands before the spell ends, it takes no falling damage and can land on its feet, and the spell ends for that creature.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A small feather or a piece of down.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 reaction\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/feather-fall\"\n },\n {\n \"index\": \"feeblemind\",\n \"name\": \"Feeblemind\",\n \"desc\": [\n \"You blast the mind of a creature that you can see within range, attempting to shatter its intellect and personality. The target takes 4d6 psychic damage and must make an intelligence saving throw.\",\n \"On a failed save, the creature's Intelligence and Charisma scores become 1. The creature can't cast spells, activate magic items, understand language, or communicate in any intelligible way. The creature can, however, identify its friends, follow them, and even protect them.\",\n \"At the end of every 30 days, the creature can repeat its saving throw against this spell. If it succeeds on its saving throw, the spell ends.\",\n \"The spell can also be ended by greater restoration, heal, or wish.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A handful of clay, crystal, glass, or mineral spheres.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"psychic\",\n \"name\": \"Psychic\",\n \"url\": \"/api/damage-types/psychic\"\n },\n \"damage_at_slot_level\": {\n \"8\": \"4d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"int\",\n \"name\": \"INT\",\n \"url\": \"/api/ability-scores/int\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"The target always takes the damage. On a failed save, the creature's Intelligence and Charisma scores become 1.\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/feeblemind\"\n },\n {\n \"index\": \"find-familiar\",\n \"name\": \"Find Familiar\",\n \"desc\": [\n \"You gain the service of a familiar, a spirit that takes an animal form you choose: bat, cat, crab, frog (toad), hawk, lizard, octopus, owl, poisonous snake, fish (quipper), rat, raven, sea horse, spider, or weasel. Appearing in an unoccupied space within range, the familiar has the statistics of the chosen form, though it is a celestial, fey, or fiend (your choice) instead of a beast.\",\n \"Your familiar acts independently of you, but it always obeys your commands. In combat, it rolls its own initiative and acts on its own turn. A familiar can't attack, but it can take other actions as normal.\",\n \"When the familiar drops to 0 hit points, it disappears, leaving behind no physical form. It reappears after you cast this spell again.\",\n \"While your familiar is within 100 feet of you, you can communicate with it telepathically. Additionally, as an action, you can see through your familiar's eyes and hear what it hears until the start of your next turn, gaining the benefits of any special senses that the familiar has. During this time, you are deaf and blind with regard to your own senses.\",\n \"As an action, you can temporarily dismiss your familiar. It disappears into a pocket dimension where it awaits your summons. Alternatively, you can dismiss it forever. As an action while it is temporarily dismissed, you can cause it to reappear in any unoccupied space within 30 feet of you.\",\n \"You can't have more than one familiar at a time. If you cast this spell while you already have a familiar, you instead cause it to adopt a new form. Choose one of the forms from the above list. Your familiar transforms into the chosen creature.\",\n \"Finally, when you cast a spell with a range of touch, your familiar can deliver the spell as if it had cast the spell. Your familiar must be within 100 feet of you, and it must use its reaction to deliver the spell when you cast it. If the spell requires an attack roll, you use your action modifier for the roll.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"10gp worth of charcoal, incense, and herbs that must be consumed by fire in a brass brazier.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 1,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/find-familiar\"\n },\n {\n \"index\": \"find-steed\",\n \"name\": \"Find Steed\",\n \"desc\": [\n \"You summon a spirit that assumes the form of an unusually intelligent, strong, and loyal steed, creating a long-lasting bond with it. Appearing in an unoccupied space within range, the steed takes on a form that you choose, such as a warhorse, a pony, a camel, an elk, or a mastiff. (Your GM might allow other animals to be summoned as steeds.) The steed has the statistics of the chosen form, though it is a celestial, fey, or fiend (your choice) instead of its normal type. Additionally, if your steed has an Intelligence of 5 or less, its Intelligence becomes 6, and it gains the ability to understand one language of your choice that you speak.\",\n \"Your steed serves you as a mount, both in combat and out, and you have an instinctive bond with it that allows you to fight as a seamless unit. While mounted on your steed, you can make any spell you cast that targets only you also target your steed.\",\n \"When the steed drops to 0 hit points, it disappears, leaving behind no physical form. You can also dismiss your steed at any time as an action, causing it to disappear. In either case, casting this spell again summons the same steed, restored to its hit point maximum.\",\n \"While your steed is within 1 mile of you, you can communicate with it telepathically.\",\n \"You can't have more than one steed bonded by this spell at a time. As an action, you can release the steed from its bond at any time, causing it to disappear.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 2,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/find-steed\"\n },\n {\n \"index\": \"find-traps\",\n \"name\": \"Find Traps\",\n \"desc\": [\n \"You sense the presence of any trap within range that is within line of sight. A trap, for the purpose of this spell, includes anything that would inflict a sudden or unexpected effect you consider harmful or undesirable, which was specifically intended as such by its creator. Thus, the spell would sense an area affected by the alarm spell, a glyph of warding, or a mechanical pit trap, but it would not reveal a natural weakness in the floor, an unstable ceiling, or a hidden sinkhole.\",\n \"This spell merely reveals that a trap is present. You don't learn the location of each trap, but you do learn the general nature of the danger posed by a trap you sense.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/find-traps\"\n },\n {\n \"index\": \"find-the-path\",\n \"name\": \"Find the Path\",\n \"desc\": [\n \"This spell allows you to find the shortest, most direct physical route to a specific fixed location that you are familiar with on the same plane of existence. If you name a destination on another plane of existence, a destination that moves (such as a mobile fortress), or a destination that isn't specific (such as \\\"a green dragon's lair\\\"), the spell fails.\",\n \"For the duration, as long as you are on the same plane of existence as the destination, you know how far it is and in what direction it lies. While you are traveling there, whenever you are presented with a choice of paths along the way, you automatically determine which path is the shortest and most direct route (but not necessarily the safest route) to the destination.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A set of divinatory tools--such as bones, ivory sticks, cards, teeth, or carved runes--worth 100gp and an object from the location you wish to find.\",\n \"ritual\": false,\n \"duration\": \"Up to 24 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/find-the-path\"\n },\n {\n \"index\": \"finger-of-death\",\n \"name\": \"Finger of Death\",\n \"desc\": [\n \"You send negative energy coursing through a creature that you can see within range, causing it searing pain. The target must make a constitution saving throw. It takes 7d8 + 30 necrotic damage on a failed save, or half as much damage on a successful one.\",\n \"A humanoid killed by this spell rises at the start of your next turn as a zombie that is permanently under your command, following your verbal orders to the best of its ability.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"7\": \"7d8 + 30\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/finger-of-death\"\n },\n {\n \"index\": \"fire-bolt\",\n \"name\": \"Fire Bolt\",\n \"desc\": [\n \"You hurl a mote of fire at a creature or object within range. Make a ranged spell attack against the target. On a hit, the target takes 1d10 fire damage. A flammable object hit by this spell ignites if it isn't being worn or carried.\",\n \"This spell's damage increases by 1d10 when you reach 5th level (2d10), 11th level (3d10), and 17th level (4d10).\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d10\",\n \"5\": \"2d10\",\n \"11\": \"3d10\",\n \"17\": \"4d10\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/fire-bolt\"\n },\n {\n \"index\": \"fire-shield\",\n \"name\": \"Fire Shield\",\n \"desc\": [\n \"Thin and vaporous flame surround your body for the duration of the spell, radiating a bright light bright light in a 10-foot radius and dim light for an additional 10 feet. You can end the spell using an action to make it disappear.\",\n \"The flames are around you a heat shield or cold, your choice. The heat shield gives you cold damage resistance and the cold resistance to fire damage.\",\n \"In addition, whenever a creature within 5 feet of you hits you with a melee attack, flames spring from the shield. The attacker then suffers 2d8 points of fire damage or cold, depending on the model.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A little phosphorus or a firefly.\",\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"2d8\"\n }\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/fire-shield\"\n },\n {\n \"index\": \"fire-storm\",\n \"name\": \"Fire Storm\",\n \"desc\": [\n \"A storm made up of sheets of roaring flame appears in a location you choose within range. The area of the storm consists of up to ten 10-foot cubes, which you can arrange as you wish. Each cube must have at least one face adjacent to the face of another cube. Each creature in the area must make a dexterity saving throw. It takes 7d10 fire damage on a failed save, or half as much damage on a successful one.\",\n \"The fire damages objects in the area and ignites flammable objects that aren't being worn or carried. If you choose, plant life in the area is unaffected by this spell.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"7\": \"7d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/fire-storm\"\n },\n {\n \"index\": \"fireball\",\n \"name\": \"Fireball\",\n \"desc\": [\n \"A bright streak flashes from your pointing finger to a point you choose within range and then blossoms with a low roar into an explosion of flame. Each creature in a 20-foot-radius sphere centered on that point must make a dexterity saving throw. A target takes 8d6 fire damage on a failed save, or half as much damage on a successful one.\",\n \"The fire spreads around corners. It ignites flammable objects in the area that aren't being worn or carried.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d6 for each slot level above 3rd.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny ball of bat guano and sulfur.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"8d6\",\n \"4\": \"9d6\",\n \"5\": \"10d6\",\n \"6\": \"11d6\",\n \"7\": \"12d6\",\n \"8\": \"13d6\",\n \"9\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/fireball\"\n },\n {\n \"index\": \"flame-blade\",\n \"name\": \"Flame Blade\",\n \"desc\": [\n \"You evoke a fiery blade in your free hand. The blade is similar in size and shape to a scimitar, and it lasts for the duration. If you let go of the blade, it disappears, but you can evoke the blade again as a bonus action.\",\n \"You can use your action to make a melee spell attack with the fiery blade. On a hit, the target takes 3d6 fire damage.\",\n \"The flaming blade sheds bright light in a 10-foot radius and dim light for an additional 10 feet.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d6 for every two slot levels above 2nd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Leaf of sumac.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"3d6\",\n \"4\": \"4d6\",\n \"6\": \"5d6\",\n \"8\": \"6d6\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/flame-blade\"\n },\n {\n \"index\": \"flame-strike\",\n \"name\": \"Flame Strike\",\n \"desc\": [\n \"A vertical column of divine fire roars down from the heavens in a location you specify. Each creature in a 10-foot-radius, 40-foot-high cylinder centered on a point within range must make a dexterity saving throw. A creature takes 4d6 fire damage and 4d6 radiant damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the fire damage or the radiant damage (your choice) increases by 1d6 for each slot level above 5th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Pinch of sulfur.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"4d6 + 4d6\",\n \"6\": \"4d6 + 5d6\",\n \"7\": \"4d6 + 6d6\",\n \"8\": \"4d6 + 7d6\",\n \"9\": \"4d6 + 8d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/flame-strike\"\n },\n {\n \"index\": \"flaming-sphere\",\n \"name\": \"Flaming Sphere\",\n \"desc\": [\n \"A 5-foot-diameter sphere of fire appears in an unoccupied space of your choice within range and lasts for the duration. Any creature that ends its turn within 5 feet of the sphere must make a dexterity saving throw. The creature takes 2d6 fire damage on a failed save, or half as much damage on a successful one.\",\n \"As a bonus action, you can move the sphere up to 30 feet. If you ram the sphere into a creature, that creature must make the saving throw against the sphere's damage, and the sphere stops moving this turn.\",\n \"When you move the sphere, you can direct it over barriers up to 5 feet tall and jump it across pits up to 10 feet wide. The sphere ignites flammable objects not being worn or carried, and it sheds bright light in a 20-foot radius and dim light for an additional 20 feet.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage increases by 1d6 for each slot level above 2nd.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of tallow, a pinch of brimstone, and a dusting of powdered iron.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d6\",\n \"3\": \"3d6\",\n \"4\": \"4d6\",\n \"5\": \"5d6\",\n \"6\": \"6d6\",\n \"7\": \"7d6\",\n \"8\": \"8d6\",\n \"9\": \"9d6\"\n }\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/flaming-sphere\"\n },\n {\n \"index\": \"flesh-to-stone\",\n \"name\": \"Flesh to Stone\",\n \"desc\": [\n \"You attempt to turn one creature that you can see within range into stone. If the target's body is made of flesh, the creature must make a constitution saving throw. On a failed save, it is restrained as its flesh begins to harden. On a successful save, the creature isn't affected.\",\n \"A creature restrained by this spell must make another constitution saving throw at the end of each of its turns. If it successfully saves against this spell three times, the spell ends. If it fails its saves three times, it is turned to stone and subjected to the petrified condition for the duration. The successes and failures don't need to be consecutive; keep track of both until the target collects three of a kind.\",\n \"If the creature is physically broken while petrified, it suffers from similar deformities if it reverts to its original state.\",\n \"If you maintain your concentration on this spell for the entire possible duration, the creature is turned to stone until the effect is removed.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of lime, water, and earth.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, the target is restrained as its flesh begins to harden.\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/flesh-to-stone\"\n },\n {\n \"index\": \"floating-disk\",\n \"name\": \"Floating Disk\",\n \"desc\": [\n \"This spell creates a circular, horizontal plane of force, 3 feet in diameter and 1 inch thick, that floats 3 feet above the ground in an unoccupied space of your choice that you can see within range. The disk remains for the duration, and can hold up to 500 pounds. If more weight is placed on it, the spell ends, and everything on the disk falls to the ground.\",\n \"The disk is immobile while you are within 20 feet of it. If you move more than 20 feet away from it, the disk follows you so that it remains within 20 feet of you. If can move across uneven terrain, up or down stairs, slopes and the like, but it can't cross an elevation change of 10 feet or more. For example, the disk can't move across a 10-foot-deep pit, nor could it leave such a pit if it was created at the bottom.\",\n \"If you move more than 100 feet away from the disk (typically because it can't move around an obstacle to follow you), the spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of mercury.\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/floating-disk\"\n },\n {\n \"index\": \"fly\",\n \"name\": \"Fly\",\n \"desc\": [\n \"You touch a willing creature. The target gains a flying speed of 60 feet for the duration. When the spell ends, the target falls if it is still aloft, unless it can stop the fall.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, you can target one additional creature for each slot level above 3rd.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A wing feather from any bird.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/fly\"\n },\n {\n \"index\": \"fog-cloud\",\n \"name\": \"Fog Cloud\",\n \"desc\": [\n \"You create a 20-foot-radius sphere of fog centered on a point within range. The sphere spreads around corners, and its area is heavily obscured. It lasts for the duration or until a wind of moderate or greater speed (at least 10 miles per hour) disperses it.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the radius of the fog increases by 20 feet for each slot level above 1st.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/fog-cloud\"\n },\n {\n \"index\": \"forbiddance\",\n \"name\": \"Forbiddance\",\n \"desc\": [\n \"You create a ward against magical travel that protects up to 40,000 square feet of floor space to a height of 30 feet above the floor. For the duration, creatures can't teleport into the area or use portals, such as those created by the gate spell, to enter the area. The spell proofs the area against planar travel, and therefore prevents creatures from accessing the area by way of the Astral Plane, Ethereal Plane, Feywild, Shadowfell, or the plane shift spell.\",\n \"In addition, the spell damages types of creatures that you choose when you cast it. Choose one or more of the following: celestials, elementals, fey, fiends, and undead. When a chosen creature enters the spell's area for the first time on a turn or starts its turn there, the creature takes 5d10 radiant or necrotic damage (your choice when you cast this spell).\",\n \"When you cast this spell, you can designate a password. A creature that speaks the password as it enters the area takes no damage from the spell.\",\n \"The spell's area can't overlap with the area of another forbiddance spell. If you cast forbiddance every day for 30 days in the same location, the spell lasts until it is dispelled, and the material components are consumed on the last casting.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sprinkling of holy water, rare incense, and powdered ruby worth at least 1,000 gp.\",\n \"ritual\": true,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 40000\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/forbiddance\"\n },\n {\n \"index\": \"forcecage\",\n \"name\": \"Forcecage\",\n \"desc\": [\n \"An immobile, invisible, cube-shaped prison composed of magical force springs into existence around an area you choose within range. The prison can be a cage or a solid box, as you choose.\",\n \"A prison in the shape of a cage can be up to 20 feet on a side and is made from 1/2-inch diameter bars spaced 1/2 inch apart.\",\n \"A prison in the shape of a box can be up to 10 feet on a side, creating a solid barrier that prevents any matter from passing through it and blocking any spells cast into or out from the area.\",\n \"When you cast the spell, any creature that is completely inside the cage's area is trapped. Creatures only partially within the area, or those too large to fit inside the area, are pushed away from the center of the area until they are completely outside the area.\",\n \"A creature inside the cage can't leave it by nonmagical means. If the creature tries to use teleportation or interplanar travel to leave the cage, it must first make a charisma saving throw. On a success, the creature can use that magic to exit the cage. On a failure, the creature can't exit the cage and wastes the use of the spell or effect. The cage also extends into the Ethereal Plane, blocking ethereal travel.\",\n \"This spell can't be dispelled by dispel magic.\"\n ],\n \"range\": \"100 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Ruby dust worth 1,500 gp.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/forcecage\"\n },\n {\n \"index\": \"foresight\",\n \"name\": \"Foresight\",\n \"desc\": [\n \"You touch a willing creature and bestow a limited ability to see into the immediate future. For the duration, the target can't be surprised and has advantage on attack rolls, ability checks, and saving throws. Additionally, other creatures have disadvantage on attack rolls against the target for the duration.\",\n \"This spell immediately ends if you cast it again before its duration ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A hummingbird feather.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 9,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/foresight\"\n },\n {\n \"index\": \"freedom-of-movement\",\n \"name\": \"Freedom of Movement\",\n \"desc\": [\n \"You touch a willing creature. For the duration, the target's movement is unaffected by difficult terrain, and spells and other magical effects can neither reduce the target's speed nor cause the target to be paralyzed or restrained.\",\n \"The target can also spend 5 feet of movement to automatically escape from nonmagical restraints, such as manacles or a creature that has it grappled. Finally, being underwater imposes no penalties on the target's movement or attacks.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A leather strap, bound around the arm or a similar appendage.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/freedom-of-movement\"\n },\n {\n \"index\": \"freezing-sphere\",\n \"name\": \"Freezing Sphere\",\n \"desc\": [\n \"A frigid globe of cold energy streaks from your fingertips to a point of your choice within range, where it explodes in a 60-foot-radius sphere. Each creature within the area must make a constitution saving throw. On a failed save, a creature takes 10d6 cold damage. On a successful save, it takes half as much damage.\",\n \"If the globe strikes a body of water or a liquid that is principally water (not including water-based creatures), it freezes the liquid to a depth of 6 inches over an area 30 feet square. This ice lasts for 1 minute. Creatures that were swimming on the surface of frozen water are trapped in the ice. A trapped creature can use an action to make a Strength check against your spell save DC to break free.\",\n \"You can refrain from firing the globe after completing the spell, if you wish. A small globe about the size of a sling stone, cool to the touch, appears in your hand. At any time, you or a creature you give the globe to can throw the globe (to a range of 40 feet) or hurl it with a sling (to the sling's normal range). It shatters on impact, with the same effect as the normal casting of the spell. You can also set the globe down without shattering it. After 1 minute, if the globe hasn't already shattered, it explodes.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the damage increases by 1d6 for each slot level above 6th.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small crystal sphere.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"cold\",\n \"name\": \"Cold\",\n \"url\": \"/api/damage-types/cold\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"10d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/freezing-sphere\"\n },\n {\n \"index\": \"gaseous-form\",\n \"name\": \"Gaseous Form\",\n \"desc\": [\n \"You transform a willing creature you touch, along with everything it's wearing and carrying, into a misty cloud for the duration. The spell ends if the creature drops to 0 hit points. An incorporeal creature isn't affected.\",\n \"While in this form, the target's only method of movement is a flying speed of 10 feet. The target can enter and occupy the space of another creature. The target has resistance to nonmagical damage, and it has advantage on Strength, Dexterity, and constitution saving throws. The target can pass through small holes, narrow openings, and even mere cracks, though it treats liquids as though they were solid surfaces. The target can't fall and remains hovering in the air even when stunned or otherwise incapacitated.\",\n \"While in the form of a misty cloud, the target can't talk or manipulate objects, and any objects it was carrying or holding can't be dropped, used, or otherwise interacted with. The target can't attack or cast spells.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of gauze and a wisp of smoke.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/gaseous-form\"\n },\n {\n \"index\": \"gate\",\n \"name\": \"Gate\",\n \"desc\": [\n \"You conjure a portal linking an unoccupied space you can see within range to a precise location on a different plane of existence. The portal is a circular opening, which you can make 5 to 20 feet in diameter. You can orient the portal in any direction you choose. The portal lasts for the duration.\",\n \"The portal has a front and a back on each plane where it appears. Travel through the portal is possible only by moving through its front. Anything that does so is instantly transported to the other plane, appearing in the unoccupied space nearest to the portal.\",\n \"Deities and other planar rulers can prevent portals created by this spell from opening in their presence or anywhere within their domains.\",\n \"When you cast this spell, you can speak the name of a specific creature (a pseudonym, title, or nickname doesn't work). If that creature is on a plane other than the one you are on, the portal opens in the named creature's immediate vicinity and draws the creature through it to the nearest unoccupied space on your side of the portal. You gain no special power over the creature, and it is free to act as the GM deems appropriate. It might leave, attack you, or help you.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A diamond worth at least 5,000gp.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/gate\"\n },\n {\n \"index\": \"geas\",\n \"name\": \"Geas\",\n \"desc\": [\n \"You place a magical command on a creature that you can see within range, forcing it to carry out some service or refrain from some action or course of activity as you decide. If the creature can understand you, it must succeed on a wisdom saving throw or become charmed by you for the duration. While the creature is charmed by you, it takes 5d10 psychic damage each time it acts in a manner directly counter to your instructions, but no more than once each day. A creature that can't understand you is unaffected by the spell.\",\n \"You can issue any command you choose, short of an activity that would result in certain death. Should you issue a suicidal command, the spell ends.\",\n \"You can end the spell early by using an action to dismiss it. A remove curse, greater restoration, or wish spell also ends it.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th or 8th level, the duration is 1 year. When you cast this spell using a spell slot of 9th level, the spell lasts until it is ended by one of the spells mentioned above.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"30 days\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/geas\"\n },\n {\n \"index\": \"gentle-repose\",\n \"name\": \"Gentle Repose\",\n \"desc\": [\n \"You touch a corpse or other remains. For the duration, the target is protected from decay and can't become undead.\",\n \"The spell also effectively extends the time limit on raising the target from the dead, since days spent under the influence of this spell don't count against the time limit of spells such as raise dead.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of salt and one copper piece placed on each of the corpse's eyes, which must remain there for the duration.\",\n \"ritual\": true,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/gentle-repose\"\n },\n {\n \"index\": \"giant-insect\",\n \"name\": \"Giant Insect\",\n \"desc\": [\n \"You transform up to ten centipedes, three spiders, five wasps, or one scorpion within range into giant versions of their natural forms for the duration. A centipede becomes a giant centipede, a spider becomes a giant spider, a wasp becomes a giant wasp, and a scorpion becomes a giant scorpion.\",\n \"Each creature obeys your verbal commands, and in combat, they act on your turn each round. The GM has the statistics for these creatures and resolves their actions and movement.\",\n \"A creature remains in its giant size for the duration, until it drops to 0 hit points, or until you use an action to dismiss the effect on it.\",\n \"The GM might allow you to choose different targets. For example, if you transform a bee, its giant version might have the same statistics as a giant wasp.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/giant-insect\"\n },\n {\n \"index\": \"glibness\",\n \"name\": \"Glibness\",\n \"desc\": [\n \"Until the spell ends, when you make a Charisma check, you can replace the number you roll with a 15. Additionally, no matter what you say, magic that would determine if you are telling the truth indicates that you are being truthful.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/glibness\"\n },\n {\n \"index\": \"globe-of-invulnerability\",\n \"name\": \"Globe of Invulnerability\",\n \"desc\": [\n \"An immobile, faintly shimmering barrier springs into existence in a 10-foot radius around you and remains for the duration.\",\n \"Any spell of 5th level or lower cast from outside the barrier can't affect creatures or objects within it, even if the spell is cast using a higher level spell slot. Such a spell can target creatures and objects within the barrier, but the spell has no effect on them. Similarly, the area within the barrier is excluded from the areas affected by such spells.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the barrier blocks spells of one level higher for each slot level above 6th.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A glass or crystal bead that shatters when the spell ends.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/globe-of-invulnerability\"\n },\n {\n \"index\": \"glyph-of-warding\",\n \"name\": \"Glyph of Warding\",\n \"desc\": [\n \"When you cast this spell, you inscribe a glyph that harms other creatures, either upon a surface (such as a table or a section of floor or wall) or within an object that can be closed (such as a book, a scroll, or a treasure chest) to conceal the glyph. If you choose a surface, the glyph can cover an area of the surface no larger than 10 feet in diameter. If you choose an object, that object must remain in its place; if the object is moved more than 10 feet from where you cast this spell, the glyph is broken, and the spell ends without being triggered.\",\n \"The glyph is nearly invisible and requires a successful Intelligence (Investigation) check against your spell save DC to be found.\",\n \"You decide what triggers the glyph when you cast the spell. For glyphs inscribed on a surface, the most typical triggers include touching or standing on the glyph, removing another object covering the glyph, approaching within a certain distance of the glyph, or manipulating the object on which the glyph is inscribed. For glyphs inscribed within an object, the most common triggers include opening that object, approaching within a certain distance of the object, or seeing or reading the glyph. Once a glyph is triggered, this spell ends.\",\n \"You can further refine the trigger so the spell activates only under certain circumstances or according to physical characteristics (such as height or weight), creature kind (for example, the ward could be set to affect aberrations or drow), or alignment. You can also set conditions for creatures that don't trigger the glyph, such as those who say a certain password.\",\n \"When you inscribe the glyph, choose *explosive runes* or a *spell glyph*.\",\n \"***Explosive Runes.*** When triggered, the glyph erupts with magical energy in a 20-foot-radius sphere centered on the glyph. The sphere spreads around corners. Each creature in the area must make a Dexterity saving throw. A creature takes 5d8 acid, cold, fire, lightning, or thunder damage on a failed saving throw (your choice when you create the glyph), or half as much damage on a successful one.\",\n \"***Spell Glyph.*** You can store a prepared spell of 3rd level or lower in the glyph by casting it as part of creating the glyph. The spell must target a single creature or an area. The spell being stored has no immediate effect when cast in this way. When the glyph is triggered, the stored spell is cast. If the spell has a target, it targets the creature that triggered the glyph. If the spell affects an area, the area is centered on that creature. If the spell summons hostile creatures or creates harmful objects or traps, they appear as close as possible to the intruder and attack it. If the spell requires concentration, it lasts until the end of its full duration.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage of an explosive runes glyph increases by 1d8 for each slot level above 3rd. If you create a spell glyph, you can store any spell of up to the same level as the slot you use for the glyph of warding.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Incense and powdered diamond worth at least 200 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/glyph-of-warding\"\n },\n {\n \"index\": \"goodberry\",\n \"name\": \"Goodberry\",\n \"desc\": [\n \"Up to ten berries appear in your hand and are infused with magic for the duration. A creature can use its action to eat one berry. Eating a berry restores 1 hit point, and the berry provides enough nourishment to sustain a creature for a day.\",\n \"The berries lose their potency if they have not been consumed within 24 hours of the casting of this spell.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sprig of mistletoe.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/goodberry\"\n },\n {\n \"index\": \"grease\",\n \"name\": \"Grease\",\n \"desc\": [\n \"Slick grease covers the ground in a 10-foot square centered on a point within range and turns it into difficult terrain for the duration.\",\n \"When the grease appears, each creature standing in its area must succeed on a dexterity saving throw or fall prone. A creature that enters the area or ends its turn there must also succeed on a dexterity saving throw or fall prone.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of pork rind or butter.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/grease\"\n },\n {\n \"index\": \"greater-invisibility\",\n \"name\": \"Greater Invisibility\",\n \"desc\": [\n \"You or a creature you touch becomes invisible until the spell ends. Anything the target is wearing or carrying is invisible as long as it is on the target's person.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/greater-invisibility\"\n },\n {\n \"index\": \"greater-restoration\",\n \"name\": \"Greater Restoration\",\n \"desc\": [\n \"You imbue a creature you touch with positive energy to undo a debilitating effect. You can reduce the target's exhaustion level by one, or end one of the following effects on the target:\",\n \"- One effect that charmed or petrified the target\",\n \"- One curse, including the target's attunement to a cursed magic item\",\n \"- Any reduction to one of the target's ability scores\",\n \"- One effect reducing the target's hit point maximum\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Diamond dust worth at least 100gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/greater-restoration\"\n },\n {\n \"index\": \"guardian-of-faith\",\n \"name\": \"Guardian of Faith\",\n \"desc\": [\n \"A Large spectral guardian appears and hovers for the duration in an unoccupied space of your choice that you can see within range. The guardian occupies that space and is indistinct except for a gleaming sword and shield emblazoned with the symbol of your deity.\",\n \"Any creature hostile to you that moves to a space within 10 feet of the guardian for the first time on a turn must succeed on a dexterity saving throw. The creature takes 20 radiant damage on a failed save, or half as much damage on a successful one. The guardian vanishes when it has dealt a total of 60 damage.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"20\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/guardian-of-faith\"\n },\n {\n \"index\": \"guards-and-wards\",\n \"name\": \"Guards and Wards\",\n \"desc\": [\n \"You create a ward that protects up to 2,500 square feet of floor space (an area 50 feet square, or one hundred 5-foot squares or twenty-five 10-foot squares). The warded area can be up to 20 feet tall, and shaped as you desire. You can ward several stories of a stronghold by dividing the area among them, as long as you can walk into each contiguous area while you are casting the spell.\",\n \"When you cast this spell, you can specify individuals that are unaffected by any or all of the effects that you choose. You can also specify a password that, when spoken aloud, makes the speaker immune to these effects.\",\n \"Guards and wards creates the following effects within the warded area.\",\n \"***Corridors.*** Fog fills all the warded corridors, making them heavily obscured. In addition, at each intersection or branching passage offering a choice of direction, there is a 50 percent chance that a creature other than you will believe it is going in the opposite direction from the one it chooses.\",\n \"***Doors.*** All doors in the warded area are magically locked, as if sealed by an arcane lock spell. In addition, you can cover up to ten doors with an illusion (equivalent to the illusory object function of the minor illusion spell) to make them appear as plain sections of wall.\",\n \"***Stairs.*** Webs fill all stairs in the warded area from top to bottom, as the web spell. These strands regrow in 10 minutes if they are burned or torn away while guards and wards lasts.\",\n \"***Other Spell Effect.*** You can place your choice of one of the following magical effects within the warded area of the stronghold.\",\n \"- Place dancing lights in four corridors. You can designate a simple program that the lights repeat as long as guards and wards lasts.\",\n \"- Place magic mouth in two locations.\",\n \"- Place stinking cloud in two locations. The vapors appear in the places you designate; they return within 10 minutes if dispersed by wind while guards and wards lasts.\",\n \"- Place a constant gust of wind in one corridor or room.\",\n \"- Place a suggestion in one location. You select an area of up to 5 feet square, and any creature that enters or passes through the area receives the suggestion mentally.\",\n \"The whole warded area radiates magic. A dispel magic cast on a specific effect, if successful, removes only that effect.\",\n \"You can create a permanently guarded and warded structure by casting this spell there every day for one year.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Burning incense, a small measure of brimstone and oil, a knotted string, a small amount of umber hulk blood, and a small silver rod worth at least 10 gp.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 2500\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/guards-and-wards\"\n },\n {\n \"index\": \"guidance\",\n \"name\": \"Guidance\",\n \"desc\": [\n \"You touch one willing creature. Once before the spell ends, the target can roll a d4 and add the number rolled to one ability check of its choice. It can roll the die before or after making the ability check. The spell then ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/guidance\"\n },\n {\n \"index\": \"guiding-bolt\",\n \"name\": \"Guiding Bolt\",\n \"desc\": [\n \"A flash of light streaks toward a creature of your choice within range. Make a ranged spell attack against the target. On a hit, the target takes 4d6 radiant damage, and the next attack roll made against this target before the end of your next turn has advantage, thanks to the mystical dim light glittering on the target until then.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d6 for each slot level above 1st.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"4d6\",\n \"2\": \"5d6\",\n \"3\": \"6d6\",\n \"4\": \"7d6\",\n \"5\": \"8d6\",\n \"6\": \"9d6\",\n \"7\": \"10d6\",\n \"8\": \"11d6\",\n \"9\": \"12d6\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/guiding-bolt\"\n },\n {\n \"index\": \"gust-of-wind\",\n \"name\": \"Gust of Wind\",\n \"desc\": [\n \"A line of strong wind 60 feet long and 10 feet wide blasts from you in a direction you choose for the spell's duration. Each creature that starts its turn in the line must succeed on a strength saving throw or be pushed 15 feet away from you in a direction following the line.\",\n \"Any creature in the line must spend 2 feet of movement for every 1 foot it moves when moving closer to you.\",\n \"The gust disperses gas or vapor, and it extinguishes candles, torches, and similar unprotected flames in the area. It causes protected flames, such as those of lanterns, to dance wildly and has a 50 percent chance to extinguish them.\",\n \"As a bonus action on each of your turns before the spell ends, you can change the direction in which the line blasts from you.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A legume seed.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"str\",\n \"name\": \"STR\",\n \"url\": \"/api/ability-scores/str\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/gust-of-wind\"\n },\n {\n \"index\": \"hallow\",\n \"name\": \"Hallow\",\n \"desc\": [\n \"You touch a point and infuse an area around it with holy (or unholy) power. The area can have a radius up to 60 feet, and the spell fails if the radius includes an area already under the effect a hallow spell. The affected area is subject to the following effects.\",\n \"First, celestials, elementals, fey, fiends, and undead can't enter the area, nor can such creatures charm, frighten, or possess creatures within it. Any creature charmed, frightened, or possessed by such a creature is no longer charmed, frightened, or possessed upon entering the area. You can exclude one or more of those types of creatures from this effect.\",\n \"Second, you can bind an extra effect to the area. Choose the effect from the following list, or choose an effect offered by the GM. Some of these effects apply to creatures in the area; you can designate whether the effect applies to all creatures, creatures that follow a specific deity or leader, or creatures of a specific sort, such as ores or trolls. When a creature that would be affected enters the spell's area for the first time on a turn or starts its turn there, it can make a charisma saving throw. On a success, the creature ignores the extra effect until it leaves the area.\",\n \"***Courage.*** Affected creatures can't be frightened while in the area.\",\n \"***Darkness.*** Darkness fills the area. Normal light, as well as magical light created by spells of a lower level than the slot you used to cast this spell, can't illuminate the area.\",\n \"***Daylight.*** Bright light fills the area. Magical darkness created by spells of a lower level than the slot you used to cast this spell can't extinguish the light.\",\n \"***Energy Protection.*** Affected creatures in the area have resistance to one damage type of your choice, except for bludgeoning, piercing, or slashing.\",\n \"***Energy Vulnerability.*** Affected creatures in the area have vulnerability to one damage type of your choice, except for bludgeoning, piercing, or slashing.\",\n \"***Everlasting Rest.*** Dead bodies interred in the area can't be turned into undead.\",\n \"***Extradimensional Interference.*** Affected creatures can't move or travel using teleportation or by extradimensional or interplanar means.\",\n \"***Fear.*** Affected creatures are frightened while in the area.\",\n \"***Silence.*** No sound can emanate from within the area, and no sound can reach into it.\",\n \"***Tongues.*** Affected creatures can communicate with any other creature in the area, even if they don't share a common language.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Herbs, oils, and incense worth at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"24 hours\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/hallow\"\n },\n {\n \"index\": \"hallucinatory-terrain\",\n \"name\": \"Hallucinatory Terrain\",\n \"desc\": [\n \"You make natural terrain in a 150-foot cube in range look, sound, and smell like some other sort of natural terrain. Thus, open fields or a road can be made to resemble a swamp, hill, crevasse, or some other difficult or impassable terrain. A pond can be made to seem like a grassy meadow, a precipice like a gentle slope, or a rock-strewn gully like a wide and smooth road. Manufactured structures, equipment, and creatures within the area aren't changed in appearance.\",\n \"The tactile characteristics of the terrain are unchanged, so creatures entering the area are likely to see through the illusion. If the difference isn't obvious by touch, a creature carefully examining the illusion can attempt an Intelligence (Investigation) check against your spell save DC to disbelieve it. A creature who discerns the illusion for what it is, sees it as a vague image superimposed on the terrain.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A stone, a twig, and a bit of green plant.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 4,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 150\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/hallucinatory-terrain\"\n },\n {\n \"index\": \"harm\",\n \"name\": \"Harm\",\n \"desc\": [\n \"You unleash a virulent disease on a creature that you can see within range. The target must make a constitution saving throw. On a failed save, it takes 14d6 necrotic damage, or half as much damage on a successful save. The damage can't reduce the target's hit points below 1. If the target fails the saving throw, its hit point maximum is reduced for 1 hour by an amount equal to the necrotic damage it took. Any effect that removes a disease allows a creature's hit point maximum to return to normal before that time passes.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/harm\"\n },\n {\n \"index\": \"haste\",\n \"name\": \"Haste\",\n \"desc\": [\n \"Choose a willing creature that you can see within range. Until the spell ends, the target's speed is doubled, it gains a +2 bonus to AC, it has advantage on dexterity saving throws, and it gains an additional action on each of its turns. That action can be used only to take the Attack (one weapon attack only), Dash, Disengage, Hide, or Use an Object action.\",\n \"When the spell ends, the target can't move or take actions until after its next turn, as a wave of lethargy sweeps over it.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A shaving of licorice root.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/haste\"\n },\n {\n \"index\": \"heal\",\n \"name\": \"Heal\",\n \"desc\": [\n \"Choose a creature that you can see within range. A surge of positive energy washes through the creature, causing it to regain 70 hit points. This spell also ends blindness, deafness, and any diseases affecting the target. This spell has no effect on constructs or undead.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the amount of healing increases by 10 for each slot level above 6th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"heal_at_slot_level\": {\n \"6\": \"70\",\n \"7\": \"80\",\n \"8\": \"90\",\n \"9\": \"100\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/heal\"\n },\n {\n \"index\": \"healing-word\",\n \"name\": \"Healing Word\",\n \"desc\": [\n \"A creature of your choice that you can see within range regains hit points equal to 1d4 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the healing increases by 1d4 for each slot level above 1st.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"heal_at_slot_level\": {\n \"1\": \"1d4 + MOD\",\n \"2\": \"2d4 + MOD\",\n \"3\": \"3d4 + MOD\",\n \"4\": \"4d4 + MOD\",\n \"5\": \"5d4 + MOD\",\n \"6\": \"6d4 + MOD\",\n \"7\": \"7d4 + MOD\",\n \"8\": \"8d4 + MOD\",\n \"9\": \"9d4 + MOD\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/healing-word\"\n },\n {\n \"index\": \"heat-metal\",\n \"name\": \"Heat Metal\",\n \"desc\": [\n \"Choose a manufactured metal object, such as a metal weapon or a suit of heavy or medium metal armor, that you can see within range. You cause the object to glow red-hot. Any creature in physical contact with the object takes 2d8 fire damage when you cast the spell. Until the spell ends, you can use a bonus action on each of your subsequent turns to cause this damage again.\",\n \"If a creature is holding or wearing the object and takes the damage from it, the creature must succeed on a constitution saving throw or drop the object if it can. If it doesn't drop the object, it has disadvantage on attack rolls and ability checks until the start of your next turn.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage increases by 1d8 for each slot level above 2nd.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of iron and a flame.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d8\",\n \"3\": \"3d8\",\n \"4\": \"4d8\",\n \"5\": \"5d8\",\n \"6\": \"6d8\",\n \"7\": \"7d8\",\n \"8\": \"8d8\",\n \"9\": \"9d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"Can choose to not drop the object\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/heat-metal\"\n },\n {\n \"index\": \"hellish-rebuke\",\n \"name\": \"Hellish Rebuke\",\n \"desc\": [\n \"You point your finger, and the creature that damaged you is momentarily surrounded by hellish flames. The creature must make a dexterity saving throw. It takes 2d10 fire damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d10 for each slot level above 1st.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 reaction\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"2d10\",\n \"2\": \"3d10\",\n \"3\": \"4d10\",\n \"4\": \"5d10\",\n \"5\": \"6d10\",\n \"6\": \"7d10\",\n \"7\": \"8d10\",\n \"8\": \"9d10\",\n \"9\": \"10d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/hellish-rebuke\"\n },\n {\n \"index\": \"heroes-feast\",\n \"name\": \"Heroes' Feast\",\n \"desc\": [\n \"You bring forth a great feast, including magnificent food and drink. The feast takes 1 hour to consume and disappears at the end of that time, and the beneficial effects don't set in until this hour is over. Up to twelve other creatures can partake of the feast.\",\n \"A creature that partakes of the feast gains several benefits. The creature is cured of all diseases and poison, becomes immune to poison and being frightened, and makes all wisdom saving throws with advantage. Its hit point maximum also increases by 2d10, and it gains the same number of hit points. These benefits last for 24 hours.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A gem-encrusted bowl worth at least 1,000gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/heroes-feast\"\n },\n {\n \"index\": \"heroism\",\n \"name\": \"Heroism\",\n \"desc\": [\n \"A willing creature you touch is imbued with bravery. Until the spell ends, the creature is immune to being frightened and gains temporary hit points equal to your spellcasting ability modifier at the start of each of its turns. When the spell ends, the target loses any remaining temporary hit points from this spell.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/heroism\"\n },\n {\n \"index\": \"hideous-laughter\",\n \"name\": \"Hideous Laughter\",\n \"desc\": [\n \"A creature of your choice that you can see within range perceives everything as hilariously funny and falls into fits of laughter if this spell affects it. The target must succeed on a wisdom saving throw or fall prone, becoming incapacitated and unable to stand up for the duration. A creature with an Intelligence score of 4 or less isn't affected.\",\n \"At the end of each of its turns, and each time it takes damage, the target can make another wisdom saving throw. The target had advantage on the saving throw if it's triggered by damage. On a success, the spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Tiny tarts and a feather that is waved in the air.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/hideous-laughter\"\n },\n {\n \"index\": \"hold-monster\",\n \"name\": \"Hold Monster\",\n \"desc\": [\n \"Choose a creature you can see and reach. The target must make a saving throw of Wisdom or be paralyzed for the duration of the spell. This spell has no effect against the undead. At the end of each round, the target can make a new saving throw of Wisdom. If successful, the spell ends for the creature.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a level 6 or higher location, you can target an additional creature for each level of location beyond the fifth. The creatures must be within 30 feet o f each other when you target them.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small piece of iron.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/hold-monster\"\n },\n {\n \"index\": \"hold-person\",\n \"name\": \"Hold Person\",\n \"desc\": [\n \"Choose a humanoid that you can see within range. The target must succeed on a wisdom saving throw or be paralyzed for the duration. At the end of each of its turns, the target can make another wisdom saving throw. On a success, the spell ends on the target.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you can target one additional humanoid for each slot level above 2nd. The humanoids must be within 30 feet of each other when you target them.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small, straight piece of iron.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/hold-person\"\n },\n {\n \"index\": \"holy-aura\",\n \"name\": \"Holy Aura\",\n \"desc\": [\n \"Divine light washes out from you and coalesces in a soft radiance in a 30-foot radius around you. Creatures of your choice in that radius when you cast this spell shed dim light in a 5-foot radius and have advantage on all saving throws, and other creatures have disadvantage on attack rolls against them until the spell ends. In addition, when a fiend or an undead hits an affected creature with a melee attack, the aura flashes with brilliant light. The attacker must succeed on a constitution saving throw or be blinded until the spell ends.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny reliquary worth at least 1,000gp containing a sacred relic, such as a scrap of cloth from a saint's robe or a piece of parchment from a religious text.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/holy-aura\"\n },\n {\n \"index\": \"hunters-mark\",\n \"name\": \"Hunter's Mark\",\n \"desc\": [\n \"You choose a creature you can see within range and mystically mark it as your quarry. Until the spell ends, you deal an extra 1d6 damage to the target whenever you hit it with a weapon attack, and you have advantage on any Wisdom (Perception) or Wisdom (Survival) check you make to find it. If the target drops to 0 hit points before this spell ends, you can use a bonus action on a subsequent turn of yours to mark a new creature.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd or 4th level, you can maintain your concentration on the spell for up to 8 hours. When you use a spell slot of 5th level or higher, you can maintain your concentration on the spell for up to 24 hours.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/hunters-mark\"\n },\n {\n \"index\": \"hypnotic-pattern\",\n \"name\": \"Hypnotic Pattern\",\n \"desc\": [\n \"You create a twisting pattern of colors that weaves through the air inside a 30-foot cube within range. The pattern appears for a moment and vanishes. Each creature in the area who sees the pattern must make a wisdom saving throw. On a failed save, the creature becomes charmed for the duration. While charmed by this spell, the creature is incapacitated and has a speed of 0.\",\n \"The spell ends for an affected creature if it takes any damage or if someone else uses an action to shake the creature out of its stupor.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"S\", \"M\"],\n \"material\": \"A glowing stick of incense or a crystal vial filled with phosphorescent material.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, the creature becomes charmed for the duration.\"\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/hypnotic-pattern\"\n },\n {\n \"index\": \"ice-storm\",\n \"name\": \"Ice Storm\",\n \"desc\": [\n \"A hail of rock-hard ice pounds to the ground in a 20-foot-radius, 40-foot-high cylinder centered on a point within range. Each creature in the cylinder must make a dexterity saving throw. A creature takes 2d8 bludgeoning damage and 4d6 cold damage on a failed save, or half as much damage on a successful one.\",\n \"Hailstones turn the storm's area of effect into difficult terrain until the end of your next turn.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, the bludgeoning damage increases by 1d8 for each slot level above 4th.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of dust and a few drops of water.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"bludgeoning\",\n \"name\": \"Bludgeoning\",\n \"url\": \"/api/damage-types/bludgeoning\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"2d8 + 4d6\",\n \"5\": \"3d8 + 4d6\",\n \"6\": \"4d8 + 4d6\",\n \"7\": \"5d8 + 4d6\",\n \"8\": \"6d8 + 4d6\",\n \"9\": \"7d8 + 4d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/ice-storm\"\n },\n {\n \"index\": \"identify\",\n \"name\": \"Identify\",\n \"desc\": [\n \"You choose one object that you must touch throughout the casting of the spell. If it is a magic item or some other magic-imbued object, you learn its properties and how to use them, whether it requires attunement to use, and how many charges it has, if any. You learn whether any spells are affecting the item and what they are. If the item was created by a spell, you learn which spell created it.\",\n \"If you instead touch a creature throughout the casting, you learn what spells, if any, are currently affecting it.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pearl worth at least 100gp and an owl feather.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 1,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/identify\"\n },\n {\n \"index\": \"illusory-script\",\n \"name\": \"Illusory Script\",\n \"desc\": [\n \"You write on parchment, paper, or some other suitable writing material and imbue it with a potent illusion that lasts for the duration.\",\n \"To you and any creatures you designate when you cast the spell, the writing appears normal, written in your hand, and conveys whatever meaning you intended when you wrote the text. To all others, the writing appears as if it were written in an unknown or magical script that is unintelligible. Alternatively, you can cause the writing to appear to be an entirely different message, written in a different hand and language, though the language must be one you know.\",\n \"Should the spell be dispelled, the original script and the illusion both disappear.\",\n \"A creature with truesight can read the hidden message.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"S\", \"M\"],\n \"material\": \"A lead-based ink worth at least 10gp, which this spell consumes.\",\n \"ritual\": true,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 1,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/illusory-script\"\n },\n {\n \"index\": \"imprisonment\",\n \"name\": \"Imprisonment\",\n \"desc\": [\n \"You create a magical restraint to hold a creature that you can see within range. The target must succeed on a wisdom saving throw or be bound by the spell; if it succeeds, it is immune to this spell if you cast it again. While affected by this spell, the creature doesn't need to breathe, eat, or drink, and it doesn't age. Divination spells can't locate or perceive the target.\",\n \"When you cast the spell, you choose one of the following forms of imprisonment.\",\n \"***Burial.*** The target is entombed far beneath the earth in a sphere of magical force that is just large enough to contain the target. Nothing can pass through the sphere, nor can any creature teleport or use planar travel to get into or out of it.\",\n \"The special component for this version of the spell is a small mithral orb.\",\n \"***Chaining.*** Heavy chains, firmly rooted in the ground, hold the target in place. The target is restrained until the spell ends, and it can't move or be moved by any means until then.\",\n \"The special component for this version of the spell is a fine chain of precious metal.\",\n \"***Hedged Prison.*** The spell transports the target into a tiny demiplane that is warded against teleportation and planar travel. The demiplane can be a labyrinth, a cage, a tower, or any similar confined structure or area of your choice.\",\n \"The special component for this version of the spell is a miniature representation of the prison made from jade.\",\n \"***Minimus Containment.*** The target shrinks to a height of 1 inch and is imprisoned inside a gemstone or similar object. Light can pass through the gemstone normally (allowing the target to see out and other creatures to see in), but nothing else can pass through, even by means of teleportation or planar travel. The gemstone can't be cut or broken while the spell remains in effect.\",\n \"The special component for this version of the spell is a large, transparent gemstone, such as a corundum, diamond, or ruby.\",\n \"***Slumber.*** The target falls asleep and can't be awoken.\",\n \"The special component for this version of the spell consists of rare soporific herbs.\",\n \"***Ending the Spell.*** During the casting of the spell, in any of its versions, you can specify a condition that will cause the spell to end and release the target. The condition can be as specific or as elaborate as you choose, but the GM must agree that the condition is reasonable and has a likelihood of coming to pass. The conditions can be based on a creature's name, identity, or deity but otherwise must be based on observable actions or qualities and not based on intangibles such as level, class, or hit points.\",\n \"A dispel magic spell can end the spell only if it is cast as a 9th-level spell, targeting either the prison or the special component used to create it.\",\n \"You can use a particular special component to create only one prison at a time. If you cast the spell again using the same component, the target of the first casting is immediately freed from its binding.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A vellum depiction or a carved statuette in the likeness of the target, and a special component that varies according to the version of the spell you choose, worth at least 500gp per Hit Die of the target.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 9,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"If the creature succeeds, it is immune to this spell if you cast it again\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/imprisonment\"\n },\n {\n \"index\": \"incendiary-cloud\",\n \"name\": \"Incendiary Cloud\",\n \"desc\": [\n \"A swirling cloud of smoke shot through with white-hot embers appears in a 20-foot-radius sphere centered on a point within range. The cloud spreads around corners and is heavily obscured. It lasts for the duration or until a wind of moderate or greater speed (at least 10 miles per hour) disperses it.\",\n \"When the cloud appears, each creature in it must make a dexterity saving throw. A creature takes 10d8 fire damage on a failed save, or half as much damage on a successful one. A creature must also make this saving throw when it enters the spell's area for the first time on a turn or ends its turn there.\",\n \"The cloud moves 10 feet directly away from you in a direction that you choose at the start of each of your turns.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"8\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/incendiary-cloud\"\n },\n {\n \"index\": \"inflict-wounds\",\n \"name\": \"Inflict Wounds\",\n \"desc\": [\n \"Make a melee spell attack against a creature you can reach. On a hit, the target takes 3d10 necrotic damage.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d10 for each slot level above 1st.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"3d10\",\n \"2\": \"4d10\",\n \"3\": \"5d10\",\n \"4\": \"6d10\",\n \"5\": \"7d10\",\n \"6\": \"8d10\",\n \"7\": \"9d10\",\n \"8\": \"10d10\",\n \"9\": \"11d10\"\n }\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/inflict-wounds\"\n },\n {\n \"index\": \"insect-plague\",\n \"name\": \"Insect Plague\",\n \"desc\": [\n \"Swarming, biting locusts fill a 20-foot-radius sphere centered on a point you choose within range. The sphere spreads around corners. The sphere remains for the duration, and its area is lightly obscured. The sphere's area is difficult terrain.\",\n \"When the area appears, each creature in it must make a constitution saving throw. A creature takes 4d10 piercing damage on a failed save, or half as much damage on a successful one. A creature must also make this saving throw when it enters the spell's area for the first time on a turn or ends its turn there.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the damage increases by 1d10 for each slot level above 5th.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A few grains of sugar, some kernels of grain, and a smear of fat.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"piercing\",\n \"name\": \"Piercing\",\n \"url\": \"/api/damage-types/piercing\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"4d10\",\n \"6\": \"5d10\",\n \"7\": \"6d10\",\n \"8\": \"7d10\",\n \"9\": \"8d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/insect-plague\"\n },\n {\n \"index\": \"instant-summons\",\n \"name\": \"Instant Summons\",\n \"desc\": [\n \"You touch an object weighing 10 pounds or less whose longest dimension is 6 feet or less. The spell leaves an invisible mark on its surface and invisibly inscribes the name of the item on the sapphire you use as the material component. Each time you cast this spell, you must use a different sapphire.\",\n \"At any time thereafter, you can use your action to speak the item's name and crush the sapphire. The item instantly appears in your hand regardless of physical or planar distances, and the spell ends.\",\n \"If another creature is holding or carrying the item, crushing the sapphire doesn't transport the item to you, but instead you learn who the creature possessing the object is and roughly where that creature is located at that moment.\",\n \"Dispel magic or a similar effect successfully applied to the sapphire ends this spell's effect.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sapphire worth 1,000 gp.\",\n \"ritual\": true,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/instant-summons\"\n },\n {\n \"index\": \"invisibility\",\n \"name\": \"Invisibility\",\n \"desc\": [\n \"A creature you touch becomes invisible until the spell ends. Anything the target is wearing or carrying is invisible as long as it is on the target's person. The spell ends for a target that attacks or casts a spell.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you can target one additional creature for each slot level above 2nd.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An eyelash encased in gum arabic.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/invisibility\"\n },\n {\n \"index\": \"irresistible-dance\",\n \"name\": \"Irresistible Dance\",\n \"desc\": [\n \"Choose one creature that you can see within range. The target begins a comic dance in place: shuffling, tapping its feet, and capering for the duration. Creatures that can't be charmed are immune to this spell.\",\n \"A dancing creature must use all its movement to dance without leaving its space and has disadvantage on dexterity saving throws and attack rolls. While the target is affected by this spell, other creatures have advantage on attack rolls against it. As an action, a dancing creature makes a wisdom saving throw to regain control of itself. On a successful save, the spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/irresistible-dance\"\n },\n {\n \"index\": \"jump\",\n \"name\": \"Jump\",\n \"desc\": [\n \"You touch a creature. The creature's jump distance is tripled until the spell ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A grasshopper's hind leg.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/jump\"\n },\n {\n \"index\": \"knock\",\n \"name\": \"Knock\",\n \"desc\": [\n \"Choose an object that you can see within range. The object can be a door, a box, a chest, a set of manacles, a padlock, or another object that contains a mundane or magical means that prevents access.\",\n \"A target that is held shut by a mundane lock or that is stuck or barred becomes unlocked, unstuck, or unbarred. If the object has multiple locks, only one of them is unlocked.\",\n \"If you choose a target that is held shut with arcane lock, that spell is suppressed for 10 minutes, during which time the target can be opened and shut normally.\",\n \"When you cast the spell, a loud knock, audible from as far away as 300 feet, emanates from the target object.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/knock\"\n },\n {\n \"index\": \"legend-lore\",\n \"name\": \"Legend Lore\",\n \"desc\": [\n \"Name or describe a person, place, or object. The spell brings to your mind a brief summary of the significant lore about the thing you named. The lore might consist of current tales, forgotten stories, or even secret lore that has never been widely known. If the thing you named isn't of legendary importance, you gain no information. The more information you already have about the thing, the more precise and detailed the information you receive is.\",\n \"The information you learn is accurate but might be couched in figurative language. For example, if you have a mysterious magic axe on hand the spell might yield this information: \\\"Woe to the evildoer whose hand touches the axe, for even the haft slices the hand of the evil ones. Only a true Child of Stone, lover and beloved of Moradin, may awaken the true powers of the axe, and only with the sacred word *Rudnogg* on the lips.\\\"\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Incense worth at least 250 gp, which the spell consumes, and four ivory strips worth at least 50 gp each.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 5,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/legend-lore\"\n },\n {\n \"index\": \"lesser-restoration\",\n \"name\": \"Lesser Restoration\",\n \"desc\": [\n \"You touch a creature and can end either one disease or one condition afflicting it. The condition can be blinded, deafened, paralyzed, or poisoned.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/lesser-restoration\"\n },\n {\n \"index\": \"levitate\",\n \"name\": \"Levitate\",\n \"desc\": [\n \"One creature or object of your choice that you can see within range rises vertically, up to 20 feet, and remains suspended there for the duration. The spell can levitate a target that weighs up to 500 pounds. An unwilling creature that succeeds on a constitution saving throw is unaffected.\",\n \"The target can move only by pushing or pulling against a fixed object or surface within reach (such as a wall or a ceiling), which allows it to move as if it were climbing. You can change the target's altitude by up to 20 feet in either direction on your turn. If you are the target, you can move up or down as part of your move. Otherwise, you can use your action to move the target, which must remain within the spell's range.\",\n \"When the spell ends, the target floats gently to the ground if it is still aloft.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Either a small leather loop or a piece of golden wire bent into a cup shape with a long shank on one end.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/levitate\"\n },\n {\n \"index\": \"light\",\n \"name\": \"Light\",\n \"desc\": [\n \"You touch one object that is no larger than 10 feet in any dimension. Until the spell ends, the object sheds bright light in a 20-foot radius and dim light for an additional 20 feet. The light can be colored as you like. Completely covering the object with something opaque blocks the light. The spell ends if you cast it again or dismiss it as an action.\",\n \"If you target an object held or worn by a hostile creature, that creature must succeed on a dexterity saving throw to avoid the spell.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A firefly or phosphorescent moss.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/light\"\n },\n {\n \"index\": \"lightning-bolt\",\n \"name\": \"Lightning Bolt\",\n \"desc\": [\n \"A stroke of lightning forming a line 100 feet long and 5 feet wide blasts out from you in a direction you choose. Each creature in the line must make a dexterity saving throw. A creature takes 8d6 lightning damage on a failed save, or half as much damage on a successful one.\",\n \"The lightning ignites flammable objects in the area that aren't being worn or carried.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d6 for each slot level above 3rd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fur and a rod of amber, crystal, or glass.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"lightning\",\n \"name\": \"Lightning\",\n \"url\": \"/api/damage-types/lightning\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"8d6\",\n \"4\": \"9d6\",\n \"5\": \"10d6\",\n \"6\": \"11d6\",\n \"7\": \"12d6\",\n \"8\": \"13d6\",\n \"9\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/lightning-bolt\"\n },\n {\n \"index\": \"locate-animals-or-plants\",\n \"name\": \"Locate Animals or Plants\",\n \"desc\": [\n \"Describe or name a specific kind of beast or plant. Concentrating on the voice of nature in your surroundings, you learn the direction and distance to the closest creature or plant of that kind within 5 miles, if any are present.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fur from a bloodhound.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/locate-animals-or-plants\"\n },\n {\n \"index\": \"locate-creature\",\n \"name\": \"Locate Creature\",\n \"desc\": [\n \"Describe or name a creature that is familiar to you. You sense the direction to the creature's location, as long as that creature is within 1,000 feet of you. If the creature is moving, you know the direction of its movement.\",\n \"The spell can locate a specific creature known to you, or the nearest creature of a specific kind (such as a human or a unicorn), so long as you have seen such a creature up close--within 30 feet--at least once. If the creature you described or named is in a different form, such as being under the effects of a polymorph spell, this spell doesn't locate the creature.\",\n \"This spell can't locate a creature if running water at least 10 feet wide blocks a direct path between you and the creature.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fur from a bloodhound.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/locate-creature\"\n },\n {\n \"index\": \"locate-object\",\n \"name\": \"Locate Object\",\n \"desc\": [\n \"Describe or name an object that is familiar to you. You sense the direction to the object's location, as long as that object is within 1,000 feet of you. If the object is in motion, you know the direction of its movement.\",\n \"The spell can locate a specific object known to you, as long as you have seen it up close--within 30 feet--at least once. Alternatively, the spell can locate the nearest object of a particular kind, such as a certain kind of apparel, jewelry, furniture, tool, or weapon.\",\n \"This spell can't locate an object if any thickness of lead, even a thin sheet, blocks a direct path between you and the object.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A forked twig.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/locate-object\"\n },\n {\n \"index\": \"longstrider\",\n \"name\": \"Longstrider\",\n \"desc\": [\n \"You touch a creature. The target's speed increases by 10 feet until the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can target one additional creature for each spell slot above 1st.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of dirt.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/longstrider\"\n },\n {\n \"index\": \"mage-armor\",\n \"name\": \"Mage Armor\",\n \"desc\": [\n \"You touch a willing creature who isn't wearing armor, and a protective magical force surrounds it until the spell ends. The target's base AC becomes 13 + its Dexterity modifier. The spell ends if the target dons armor or if you dismiss the spell as an action.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of cured leather.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/mage-armor\"\n },\n {\n \"index\": \"mage-hand\",\n \"name\": \"Mage Hand\",\n \"desc\": [\n \"A spectral, floating hand appears at a point you choose within range. The hand lasts for the duration or until you dismiss it as an action. The hand vanishes if it is ever more than 30 feet away from you or if you cast this spell again.\",\n \"You can use your action to control the hand. You can use the hand to manipulate an object, open an unlocked door or container, stow or retrieve an item from an open container, or pour the contents out of a vial. You can move the hand up to 30 feet each time you use it.\",\n \"The hand can't attack, activate magic items, or carry more than 10 pounds.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/mage-hand\"\n },\n {\n \"index\": \"magic-circle\",\n \"name\": \"Magic Circle\",\n \"desc\": [\n \"You create a 10-foot radius, 20-foot-tall cylinder of magical energy centered on a point on the ground that you can see within range. Glowing runes appear whetever the cylinder intersects with the floor or other surface.\",\n \"Choose one or more of the following types of creatures: celestials, elementals, fey, fiends, or undead. The circle affects a creature of the chosen type in the following ways:\",\n \"- The creature can't willingly enter the cylinder by nonmagical means. If the creature tries to use teleportation or interplanar travel to do so, it must first succeed on a charisma saving throw.\",\n \"- The creature has disadvantage on attack rolls against targets within the cylinder.\",\n \"- Targets within the cylinder can't be charmed, frightened, or possessed by the creature.\",\n \"When you cast this spell, you can elect to cause its magic to operate in the reverse direction, preventing a creature of the specified type from leaving the cylinder and protecting targets outside it.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the duration increases by 1 hour for each slot level above 3rd.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Holy water or powdered silver and iron worth at least 100 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 10\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"If the creature tries to use teleportation or interplanar travel to do so, it must first succeed on a Charisma saving throw.\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/magic-circle\"\n },\n {\n \"index\": \"magic-jar\",\n \"name\": \"Magic Jar\",\n \"desc\": [\n \"Your body falls into a catatonic state as your soul leaves it and enters the container you used for the spell's material component. While your soul inhabits the container, you are aware of your surroundings as if you were in the container's space. You can't move or use reactions. The only action you can take is to project your soul up to 100 feet out of the container, either returning to your living body (and ending the spell) or attempting to possess a humanoids body.\",\n \"You can attempt to possess any humanoid within 100 feet of you that you can see (creatures warded by a protection from evil and good or magic circle spell can't be possessed). The target must make a charisma saving throw. On a failure, your soul moves into the target's body, and the target's soul becomes trapped in the container. On a success, the target resists your efforts to possess it, and you can't attempt to possess it again for 24 hours.\",\n \"Once you possess a creature's body, you control it. Your game statistics are replaced by the statistics of the creature, though you retain your alignment and your Intelligence, Wisdom, and Charisma scores. You retain the benefit of your own class features. If the target has any class levels, you can't use any of its class features.\",\n \"Meanwhile, the possessed creature's soul can perceive from the container using its own senses, but it can't move or take actions at all.\",\n \"While possessing a body, you can use your action to return from the host body to the container if it is within 100 feet of you, returning the host creature's soul to its body. If the host body dies while you're in it, the creature dies, and you must make a charisma saving throw against your own spellcasting DC. On a success, you return to the container if it is within 100 feet of you. Otherwise, you die.\",\n \"If the container is destroyed or the spell ends, your soul immediately returns to your body. If your body is more than 100 feet away from you or if your body is dead when you attempt to return to it, you die. If another creature's soul is in the container when it is destroyed, the creature's soul returns to its body if the body is alive and within 100 feet. Otherwise, that creature dies.\",\n \"When the spell ends, the container is destroyed.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A gem, crystal, reliquary, or some other ornamental container worth at least 500 gp.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"On a failure, your soul moves into the target's body, and the target's soul becomes trapped in the container. On a success, the target resists your efforts to possess it, and you can't attempt to possess it again for 24 hours.\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/magic-jar\"\n },\n {\n \"index\": \"magic-missile\",\n \"name\": \"Magic Missile\",\n \"desc\": [\n \"You create three glowing darts of magical force. Each dart hits a creature of your choice that you can see within range. A dart deals 1d4 + 1 force damage to its target. The darts all strike simultaneously, and you can direct them to hit one creature or several.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the spell creates one more dart for each slot level above 1st.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"1d4 + 1\",\n \"2\": \"1d4 + 1\",\n \"3\": \"1d4 + 1\",\n \"4\": \"1d4 + 1\",\n \"5\": \"1d4 + 1\",\n \"6\": \"1d4 + 1\",\n \"7\": \"1d4 + 1\",\n \"8\": \"1d4 + 1\",\n \"9\": \"1d4 + 1\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/magic-missile\"\n },\n {\n \"index\": \"magic-mouth\",\n \"name\": \"Magic Mouth\",\n \"desc\": [\n \"You plant a message to an object in the range of the spell. The message is verbalized when the trigger conditions are met. Choose an object that you see, and that is not worn or carried by another creature. Then say the message, which should not exceed 25 words but listening can take up to 10 minutes. Finally, establish the circumstances that trigger the spell to deliver your message.\",\n \"When these conditions are satisfied, a magical mouth appears on the object and it articulates the message imitating your voice, the same tone used during implantation of the message. If the selected object has a mouth or something that approaches such as the mouth of a statue, the magic mouth come alive at this point, giving the illusion that the words come from the mouth of the object.\",\n \"When you cast this spell, you may decide that the spell ends when the message is delivered or it can persist and repeat the message whenever circumstances occur.\",\n \"The triggering circumstance can be as general or as detailed as you like, though it must be based on visual or audible conditions that occur within 30 feet of the object. For example, you could instruct the mouth to speak when any creature moves within 30 feet of the object or when a silver bell rings within 30 feet of it.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A honeycomb and jade dust of at least 10 inches, the spell consumes.\",\n \"ritual\": true,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/magic-mouth\"\n },\n {\n \"index\": \"magic-weapon\",\n \"name\": \"Magic Weapon\",\n \"desc\": [\n \"You touch a nonmagical weapon. Until the spell ends, that weapon becomes a magic weapon with a +1 bonus to attack rolls and damage rolls.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the bonus increases to +2. When you use a spell slot of 6th level or higher, the bonus increases to +3.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/magic-weapon\"\n },\n {\n \"index\": \"magnificent-mansion\",\n \"name\": \"Magnificent Mansion\",\n \"desc\": [\n \"You conjure an extradimensional dwelling in range that lasts for the duration. You choose where its one entrance is located. The entrance shimmers faintly and is 5 feet wide and 10 feet tall. You and any creature you designate when you cast the spell can enter the extradimensional dwelling as long as the portal remains open. You can open or close the portal if you are within 30 feet of it. While closed, the portal is invisible.\",\n \"Beyond the portal is a magnificent foyer with numerous chambers beyond. The atmosphere is clean, fresh, and warm.\",\n \"You can create any floor plan you like, but the space can't exceed 50 cubes, each cube being 10 feet on each side. The place is furnished and decorated as you choose. It contains sufficient food to serve a nine course banquet for up to 100 people. A staff of 100 near-transparent servants attends all who enter. You decide the visual appearance of these servants and their attire. They are completely obedient to your orders. Each servant can perform any task a normal human servant could perform, but they can't attack or take any action that would directly harm another creature. Thus the servants can fetch things, clean, mend, fold clothes, light fires, serve food, pour wine, and so on. The servants can go anywhere in the mansion but can't leave it. Furnishings and other objects created by this spell dissipate into smoke if removed from the mansion. When the spell ends, any creatures inside the extradimensional space are expelled into the open spaces nearest to the entrance.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A miniature portal carved from ivory, a small piece of polished marble, and a tiny silver spoon, each item worth at least 5 gp.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/magnificent-mansion\"\n },\n {\n \"index\": \"major-image\",\n \"name\": \"Major Image\",\n \"desc\": [\n \"You create the image of an object, a creature, or some other visible phenomenon that is no larger than a 20-foot cube. The image appears at a spot that you can see within range and lasts for the duration. It seems completely real, including sounds, smells, and temperature appropriate to the thing depicted. You can't create sufficient heat or cold to cause damage, a sound loud enough to deal thunder damage or deafen a creature, or a smell that might sicken a creature (like a troglodyte's stench).\",\n \"As long as you are within range of the illusion, you can use your action to cause the image to move to any other spot within range. As the image changes location, you can alter its appearance so that its movements appear natural for the image. For example, if you create an image of a creature and move it, you can alter the image so that it appears to be walking. Similarly, you can cause the illusion to make different sounds at different times, even making it carry on a conversation, for example.\",\n \"Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image, and its other sensory qualities become faint to the creature.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the spell lasts until dispelled, without requiring your concentration.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fleece.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/major-image\"\n },\n {\n \"index\": \"mass-cure-wounds\",\n \"name\": \"Mass Cure Wounds\",\n \"desc\": [\n \"A wave of healing energy washes out from a point of your choice within range. Choose up to six creatures in a 30-foot-radius sphere centered on that point. Each target regains hit points equal to 3d8 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the healing increases by 1d8 for each slot level above 5th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"heal_at_slot_level\": {\n \"5\": \"3d8 + MOD\",\n \"6\": \"4d8 + MOD\",\n \"7\": \"5d8 + MOD\",\n \"8\": \"6d8 + MOD\",\n \"9\": \"7d8 + MOD\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/mass-cure-wounds\"\n },\n {\n \"index\": \"mass-heal\",\n \"name\": \"Mass Heal\",\n \"desc\": [\n \"A flood of healing energy flows from you into injured creatures around you. You restore up to 700 hit points, divided as you choose among any number of creatures that you can see within range. Creatures healed by this spell are also cured of all diseases and any effect making them blinded or deafened. This spell has no effect on undead or constructs.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"heal_at_slot_level\": {\n \"9\": \"700\"\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mass-heal\"\n },\n {\n \"index\": \"mass-healing-word\",\n \"name\": \"Mass Healing Word\",\n \"desc\": [\n \"As you call out words of restoration, up to six creatures of your choice that you can see within range regain hit points equal to 1d4 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the healing increases by 1d4 for each slot level above 3rd.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 3,\n \"heal_at_slot_level\": {\n \"3\": \"1d4 + MOD\",\n \"4\": \"2d4 + MOD\",\n \"5\": \"3d4 + MOD\",\n \"6\": \"4d4 + MOD\",\n \"7\": \"5d4 + MOD\",\n \"8\": \"6d4 + MOD\",\n \"9\": \"7d4 + MOD\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/mass-healing-word\"\n },\n {\n \"index\": \"mass-suggestion\",\n \"name\": \"Mass Suggestion\",\n \"desc\": [\n \"You suggest a course of activity (limited to a sentence or two) and magically influence up to twelve creatures of your choice that you can see within range and that can hear and understand you. Creatures that can't be charmed are immune to this effect. The suggestion must be worded in such a manner as to make the course of action sound reasonable. Asking the creature to stab itself, throw itself onto a spear, immolate itself, or do some other obviously harmful act automatically negates the effect of the spell.\",\n \"Each target must make a wisdom saving throw. On a failed save, it pursues the course of action you described to the best of its ability. The suggested course of action can continue for the entire duration. If the suggested activity can be completed in a shorter time, the spell ends when the subject finishes what it was asked to do.\",\n \"You can also specify conditions that will trigger a special activity during the duration. For example, you might suggest that a group of soldiers give all their money to the first beggar they meet. If the condition isn't met before the spell ends, the activity isn't performed.\",\n \"If you or any of your companions damage a creature affected by this spell, the spell ends for that creature.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 7th-level spell slot, the duration is 10 days. When you use an 8th-level spell slot, the duration is 30 days. When you use a 9th-level spell slot, the duration is a year and a day.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A snake's tongue and either a bit of honeycomb or a drop of sweet oil.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mass-suggestion\"\n },\n {\n \"index\": \"maze\",\n \"name\": \"Maze\",\n \"desc\": [\n \"You banish a creature that you can see within range into a labyrinthine demiplane. The target remains there for the duration or until it escapes the maze.\",\n \"The target can use its action to attempt to escape. When it does so, it makes a DC 20 Intelligence check. If it succeeds, it escapes, and the spell ends (a minotaur or goristro demon automatically succeeds).\",\n \"When the spell ends, the target reappears in the space it left or, if that space is occupied, in the nearest unoccupied space.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/maze\"\n },\n {\n \"index\": \"meld-into-stone\",\n \"name\": \"Meld Into Stone\",\n \"desc\": [\n \"You step into a stone object or surface large enough to fully contain your body, melding yourself and all the equipment you carry with the stone for the duration. Using your movement, you step into the stone at a point you can touch. Nothing of your presence remains visible or otherwise detectable by nonmagical senses.\",\n \"While merged with the stone, you can't see what occurs outside it, and any Wisdom (Perception) checks you make to hear sounds outside it are made with disadvantage. You remain aware of the passage of time and can cast spells on yourself while merged in the stone. You can use your movement to leave the stone where you entered it, which ends the spell. You otherwise can't move.\",\n \"Minor physical damage to the stone doesn't harm you, but its partial destruction or a change in its shape (to the extent that you no longer fit within it) expels you and deals 6d6 bludgeoning damage to you. The stone's complete destruction (or transmutation into a different substance) expels you and deals 50 bludgeoning damage to you. If expelled, you fall prone in an unoccupied space closest to where you first entered.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/meld-into-stone\"\n },\n {\n \"index\": \"mending\",\n \"name\": \"Mending\",\n \"desc\": [\n \"This spell repairs a single break or tear in an object you touch, such as a broken key, a torn cloak, or a leaking wineskin. As long as the break or tear is no longer than 1 foot in any dimension, you mend it, leaving no trace of the former damage.\",\n \"This spell can physically repair a magic item or construct, but the spell can't restore magic to such an object.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Two lodestones.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/mending\"\n },\n {\n \"index\": \"message\",\n \"name\": \"Message\",\n \"desc\": [\n \"You point your finger toward a creature within range and whisper a message. The target (and only the target) hears the message and can reply in a whisper that only you can hear.\",\n \"You can cast this spell through solid objects if you are familiar with the target and know it is beyond the barrier. Magical silence, 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood blocks the spell. The spell doesn't have to follow a straight line and can travel freely around corners or through openings.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A short piece of copper wire.\",\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/message\"\n },\n {\n \"index\": \"meteor-swarm\",\n \"name\": \"Meteor Swarm\",\n \"desc\": [\n \"Blazing orbs of fire plummet to the ground at four different points you can see within range. Each creature in a 40-foot-radius sphere centered on each point you choose must make a dexterity saving throw. The sphere spreads around corners. A creature takes 20d6 fire damage and 20d6 bludgeoning damage on a failed save, or half as much damage on a successful one. A creature in the area of more than one fiery burst is affected only once.\",\n \"The spell damages objects in the area and ignites flammable objects that aren't being worn or carried.\"\n ],\n \"range\": \"1 mile\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"9\": \"20d6 + 20d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/meteor-swarm\"\n },\n {\n \"index\": \"mind-blank\",\n \"name\": \"Mind Blank\",\n \"desc\": [\n \"Until the spell ends, one willing creature you touch is immune to psychic damage, any effect that would sense its emotions or read its thoughts, divination spells, and the charmed condition. The spell even foils wish spells and spells or effects of similar power used to affect the target's mind or to gain information about the target.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mind-blank\"\n },\n {\n \"index\": \"minor-illusion\",\n \"name\": \"Minor Illusion\",\n \"desc\": [\n \"You create a sound or an image of an object within range that lasts for the duration. The illusion also ends if you dismiss it as an action or cast this spell again.\",\n \"If you create a sound, its volume can range from a whisper to a scream. It can be your voice, someone else's voice, a lion's roar, a beating of drums, or any other sound you choose. The sound continues unabated throughout the duration, or you can make discrete sounds at different times before the spell ends.\",\n \"If you create an image of an object--such as a chair, muddy footprints, or a small chest--it must be no larger than a 5-foot cube. The image can't create sound, light, smell, or any other sensory effect. Physical interaction with the image reveals it to be an illusion, because things can pass through it.\",\n \"If a creature uses its action to examine the sound or image, the creature can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the illusion becomes faint to the creature.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"S\", \"M\"],\n \"material\": \"A bit of fleece.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/minor-illusion\"\n },\n {\n \"index\": \"mirage-arcane\",\n \"name\": \"Mirage Arcane\",\n \"desc\": [\n \"You make terrain in an area up to 1 mile square look, sound, smell, and even feel like some other sort of terrain. The terrain's general shape remains the same, however. Open fields or a road could be made to resemble a swamp, hill, crevasse, or some other difficult or impassable terrain. A pond can be made to seem like a grassy meadow, a precipice like a gentle slope, or a rock-strewn gully like a wide and smooth road.\",\n \"Similarly, you can alter the appearance of structures, or add them where none are present. The spell doesn't disguise, conceal, or add creatures.\",\n \"The illusion includes audible, visual, tactile, and olfactory elements, so it can turn clear ground into difficult terrain (or vice versa) or otherwise impede movement through the area. Any piece of the illusory terrain (such as a rock or stick) that is removed from the spell's area disappears immediately.\",\n \"Creatures with truesight can see through the illusion to the terrain's true form; however, all other elements of the illusion remain, so while the creature is aware of the illusion's presence, the creature can still physically interact with the illusion.\"\n ],\n \"range\": \"Sight\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 5280\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mirage-arcane\"\n },\n {\n \"index\": \"mirror-image\",\n \"name\": \"Mirror Image\",\n \"desc\": [\n \"Three illusory duplicates of yourself appear in your space. Until the spell ends, the duplicates move with you and mimic your actions, shifting position so it's impossible to track which image is real. You can use your action to dismiss the illusory duplicates.\",\n \"Each time a creature targets you with an attack during the spell's duration, roll a d20 to determine whether the attack instead targets one of your duplicates.\",\n \"If you have three duplicates, you must roll a 6 or higher to change the attack's target to a duplicate. With two duplicates, you must roll an 8 or higher. With one duplicate, you must roll an 11 or higher.\",\n \"A duplicate's AC equals 10 + your Dexterity modifier. If an attack hits a duplicate, the duplicate is destroyed. A duplicate can be destroyed only by an attack that hits it. It ignores all other damage and effects. The spell ends when all three duplicates are destroyed.\",\n \"A creature is unaffected by this spell if it can't see, if it relies on senses other than sight, such as blindsight, or if it can perceive illusions as false, as with truesight.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/mirror-image\"\n },\n {\n \"index\": \"mislead\",\n \"name\": \"Mislead\",\n \"desc\": [\n \"You become invisible at the same time that an illusory double of you appears where you are standing. The double lasts for the duration, but the invisibility ends if you attack or cast a spell.\",\n \"You can use your action to move your illusory double up to twice your speed and make it gesture, speak, and behave in whatever way you choose.\",\n \"You can see through its eyes and hear through its ears as if you were located where it is. On each of your turns as a bonus action, you can switch from using its senses to using your own, or back again. While you are using its senses, you are blinded and deafened in regard to your own surroundings.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mislead\"\n },\n {\n \"index\": \"misty-step\",\n \"name\": \"Misty Step\",\n \"desc\": [\n \"Briefly surrounded by silvery mist, you teleport up to 30 feet to an unoccupied space that you can see.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/misty-step\"\n },\n {\n \"index\": \"modify-memory\",\n \"name\": \"Modify Memory\",\n \"desc\": [\n \"You attempt to reshape another creature's memories. One creature that you can see must make a wisdom saving throw. If you are fighting the creature, it has advantage on the saving throw. On a failed save, the target becomes charmed by you for the duration. The charmed target is incapacitated and unaware of its surroundings, though it can still hear you. If it takes any damage or is targeted by another spell, this spell ends, and none of the target's memories are modified.\",\n \"While this charm lasts, you can affect the target's memory of an event that it experienced within the last 24 hours and that lasted no more than 10 minutes. You can permanently eliminate all memory of the event, allow the target to recall the event with perfect clarity and exacting detail, change its memory of the details of the event, or create a memory of some other event.\",\n \"You must speak to the target to describe how its memories are affected, and it must be able to understand your language for the modified memories to take root. Its mind fills in any gaps in the details of your description. If the spell ends before you have finished describing the modified memories, the creature's memory isn't altered. Otherwise, the modified memories take hold when the spell ends.\",\n \"A modified memory doesn't necessarily affect how a creature behaves, particularly if the memory contradicts the creature's natural inclinations, alignment, or beliefs. An illogical modified memory, such as implanting a memory of how much the creature enjoyed dousing itself in acid, is dismissed, perhaps as a bad dream. The GM might deem a modified memory too nonsensical to affect a creature in a significant manner.\",\n \"A remove curse or greater restoration spell cast on the target restores the creature's true memory.\"\n ],\n \"higher_level\": [\n \"If you cast this spell using a spell slot of 6th level or higher, you can alter the target's memories of an event that took place up to 7 days ago (6th level), 30 days ago (7th level), 1 year ago (8th level), or any time in the creature's past (9th level).\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/modify-memory\"\n },\n {\n \"index\": \"moonbeam\",\n \"name\": \"Moonbeam\",\n \"desc\": [\n \"A silvery beam of pale light shines down in a 5-foot radius, 40-foot-high cylinder centered on a point within range. Until the spell ends, dim light fills the cylinder.\",\n \"When a creature enters the spell's area for the first time on a turn or starts its turn there, it is engulfed in ghostly flames that cause searing pain, and it must make a constitution saving throw. It takes 2d10 radiant damage on a failed save, or half as much damage on a successful one.\",\n \"A shapechanger makes its saving throw with disadvantage. If it fails, it also instantly reverts to its original form and can't assume a different form until it leaves the spell's light.\",\n \"On each of your turns after you cast this spell, you can use an action to move the beam 60 feet in any direction.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage increases by 1dl0 for each slot level above 2nd.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Several seeds of any moonseed plant and a piece of opalescent feldspar.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d10\",\n \"3\": \"3d10\",\n \"4\": \"4d10\",\n \"5\": \"5d10\",\n \"6\": \"6d10\",\n \"7\": \"7d10\",\n \"8\": \"8d10\",\n \"9\": \"9d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/moonbeam\"\n },\n {\n \"index\": \"move-earth\",\n \"name\": \"Move Earth\",\n \"desc\": [\n \"Choose an area of terrain no larger than 40 feet on a side within range. You can reshape dirt, sand, or clay in the area in any manner you choose for the duration. You can raise or lower the area's elevation, create or fill in a trench, erect or flatten a wall, or form a pillar. The extent of any such changes can't exceed half the area's largest dimension. So, if you affect a 40-foot square, you can create a pillar up to 20 feet high, raise or lower the square's elevation by up to 20 feet, dig a trench up to 20 feet deep, and so on. It takes 10 minutes for these changes to complete.\",\n \"At the end of every 10 minutes you spend concentrating on the spell, you can choose a new area of terrain to affect.\",\n \"Because the terrain's transformation occurs slowly, creatures in the area can't usually be trapped or injured by the ground's movement.\",\n \"This spell can't manipulate natural stone or stone construction. Rocks and structures shift to accommodate the new terrain. If the way you shape the terrain would make a structure unstable, it might collapse.\",\n \"Similarly, this spell doesn't directly affect plant growth. The moved earth carries any plants along with it.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An iron blade and a small bag containing a mixture of soils--clay, loam, and sand.\",\n \"ritual\": false,\n \"duration\": \"Up to 2 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/move-earth\"\n },\n {\n \"index\": \"nondetection\",\n \"name\": \"Nondetection\",\n \"desc\": [\n \"For the duration, you hide a target that you touch from divination magic. The target can be a willing creature or a place or an object no larger than 10 feet in any dimension. The target can't be targeted by any divination magic or perceived through magical scrying sensors.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of diamond dust worth 25 gp sprinkled over the target, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/nondetection\"\n },\n {\n \"index\": \"pass-without-trace\",\n \"name\": \"Pass Without Trace\",\n \"desc\": [\n \"A veil of shadows and silence radiates from you, masking you and your companions from detection. For the duration, each creature you choose within 30 feet of you (including you) has a +10 bonus to Dexterity (Stealth) checks and can't be tracked except by magical means. A creature that receives this bonus leaves behind no tracks or other traces of its passage.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Ashes from a burned leaf of mistletoe and a sprig of spruce.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/pass-without-trace\"\n },\n {\n \"index\": \"passwall\",\n \"name\": \"Passwall\",\n \"desc\": [\n \"A passage appears at a point of your choice that you can see on a wooden, plaster, or stone surface (such as a wall, a ceiling, or a floor) within range, and lasts for the duration. You choose the opening's dimensions: up to 5 feet wide, 8 feet tall, and 20 feet deep. The passage creates no instability in a structure surrounding it.\",\n \"When the opening disappears, any creatures or objects still in the passage created by the spell are safely ejected to an unoccupied space nearest to the surface on which you cast the spell.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of sesame seeds.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/passwall\"\n },\n {\n \"index\": \"phantasmal-killer\",\n \"name\": \"Phantasmal Killer\",\n \"desc\": [\n \"You tap into the nightmares of a creature you can see within range and create an illusory manifestation of its deepest fears, visible only to that creature. The target must make a wisdom saving throw. On a failed save, the target becomes frightened for the duration. At the start of each of the target's turns before the spell ends, the target must succeed on a wisdom saving throw or take 4d10 psychic damage. On a successful save, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, the damage increases by 1d10 for each slot level above 4th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"psychic\",\n \"name\": \"Psychic\",\n \"url\": \"/api/damage-types/psychic\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"4d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/phantasmal-killer\"\n },\n {\n \"index\": \"phantom-steed\",\n \"name\": \"Phantom Steed\",\n \"desc\": [\n \"A Large quasi-real, horselike creature appears on the ground in an unoccupied space of your choice within range. You decide the creature's appearance, but it is equipped with a saddle, bit, and bridle. Any of the equipment created by the spell vanishes in a puff of smoke if it is carried more than 10 feet away from the steed.\",\n \"For the duration, you or a creature you choose can ride the steed. The creature uses the statistics for a riding horse, except it has a speed of 100 feet and can travel 10 miles in an hour, or 13 miles at a fast pace. When the spell ends, the steed gradually fades, giving the rider 1 minute to dismount. The spell ends if you use an action to dismiss it or if the steed takes any damage.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 3,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/phantom-steed\"\n },\n {\n \"index\": \"planar-ally\",\n \"name\": \"Planar Ally\",\n \"desc\": [\n \"You beseech an otherworldly entity for aid. The being must be known to you: a god, a primordial, a demon prince, or some other being of cosmic power. That entity sends a celestial, an elemental, or a fiend loyal to it to aid you, making the creature appear in an unoccupied space within range. If you know a specific creature's name, you can speak that name when you cast this spell to request that creature, though you might get a different creature anyway (GM's choice).\",\n \"When the creature appears, it is under no compulsion to behave in any particular way. You can ask the creature to perform a service in exchange for payment, but it isn't obliged to do so. The requested task could range from simple (fly us across the chasm, or help us fight a battle) to complex (spy on our enemies, or protect us during our foray into the dungeon). You must be able to communicate with the creature to bargain for its services.\",\n \"Payment can take a variety of forms. A celestial might require a sizable donation of gold or magic items to an allied temple, while a fiend might demand a living sacrifice or a gift of treasure. Some creatures might exchange their service for a quest undertaken by you.\",\n \"As a rule of thumb, a task that can be measured in minutes requires a payment worth 100 gp per minute. A task measured in hours requires 1,000 gp per hour. And a task measured in days (up to 10 days) requires 10,000 gp per day. The GM can adjust these payments based on the circumstances under which you cast the spell. If the task is aligned with the creature's ethos, the payment might be halved or even waived. Nonhazardous tasks typically require only half the suggested payment, while especially dangerous tasks might require a greater gift. Creatures rarely accept tasks that seem suicidal.\",\n \"After the creature completes the task, or when the agreed-upon duration of service expires, the creature returns to its home plane after reporting back to you, if appropriate to the task and if possible. If you are unable to agree on a price for the creature's service, the creature immediately returns to its home plane.\",\n \"A creature enlisted to join your group counts as a member of it, receiving a full share of experience points awarded.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/planar-ally\"\n },\n {\n \"index\": \"planar-binding\",\n \"name\": \"Planar Binding\",\n \"desc\": [\n \"With this spell, you attempt to bind a celestial, an elemental, a fey, or a fiend to your service. The creature must be within range for the entire casting of the spell. (Typically, the creature is first summoned into the center of an inverted magic circle in order to keep it trapped while this spell is cast.) At the completion of the casting, the target must make a charisma saving throw. On a failed save, it is bound to serve you for the duration. If the creature was summoned or created by another spell, that spell's duration is extended to match the duration of this spell.\",\n \"A bound creature must follow your instructions to the best of its ability. You might command the creature to accompany you on an adventure, to guard a location, or to deliver a message. The creature obeys the letter of your instructions, but if the creature is hostile to you, it strives to twist your words to achieve its own objectives. If the creature carries out your instructions completely before the spell ends, it travels to you to report this fact if you are on the same plane of existence. If you are on a different plane of existence, it returns to the place where you bound it and remains there until the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of a higher level, the duration increases to 10 days with a 6th-level slot, to 30 days with a 7th-level slot, to 180 days with an 8th-level slot, and to a year and a day with a 9th-level spell slot.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A jewel worth at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/planar-binding\"\n },\n {\n \"index\": \"plane-shift\",\n \"name\": \"Plane Shift\",\n \"desc\": [\n \"You and up to eight willing creatures who link hands in a circle are transported to a different plane of existence. You can specify a target destination in general terms, such as the City of Brass on the Elemental Plane of Fire or the palace of Dispater on the second level of the Nine Hells, and you appear in or near that destination. If you are trying to reach the City of Brass, for example, you might arrive in its Street of Steel, before its Gate of Ashes, or looking at the city from across the Sea of Fire, at the GM's discretion.\",\n \"Alternatively, if you know the sigil sequence of a teleportation circle on another plane of existence, this spell can take you to that circle. If the teleportation circle is too small to hold all the creatures you transported, they appear in the closest unoccupied spaces next to the circle.\",\n \"You can use this spell to banish an unwilling creature to another plane. Choose a creature within your reach and make a melee spell attack against it. On a hit, the creature must make a charisma saving throw. If the creature fails this save, it is transported to a random location on the plane of existence you specify. A creature so transported must find its own way back to your current plane of existence.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A forked, metal rod worth at least 250 gp, attuned to a particular plane of existence.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"attack_type\": \"melee\",\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"If the creature fails this save, it is transported to a random location on the plane of existence you specify. A creature so transported must find its own way back to your current plane of existence.\"\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/plane-shift\"\n },\n {\n \"index\": \"plant-growth\",\n \"name\": \"Plant Growth\",\n \"desc\": [\n \"This spell channels vitality into plants within a specific area. There are two possible uses for the spell, granting either immediate or long-term benefits.\",\n \"If you cast this spell using 1 action, choose a point within range. All normal plants in a 100-foot radius centered on that point become thick and overgrown. A creature moving through the area must spend 4 feet of movement for every 1 foot it moves.\",\n \"You can exclude one or more areas of any size within the spell's area from being affected.\",\n \"If you cast this spell over 8 hours, you enrich the land. All plants in a half-mile radius centered on a point within range become enriched for 1 year. The plants yield twice the normal amount of food when harvested.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/plant-growth\"\n },\n {\n \"index\": \"poison-spray\",\n \"name\": \"Poison Spray\",\n \"desc\": [\n \"You extend your hand toward a creature you can see within range and project a puff of noxious gas from your palm. The creature must succeed on a constitution saving throw or take 1d12 poison damage.\",\n \"This spell's damage increases by 1d12 when you reach 5th level (2d12), 11th level (3d12), and 17th level (4d12).\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"poison\",\n \"name\": \"Poison\",\n \"url\": \"/api/damage-types/poison\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d12\",\n \"5\": \"2d12\",\n \"11\": \"3d12\",\n \"17\": \"4d12\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/poison-spray\"\n },\n {\n \"index\": \"polymorph\",\n \"name\": \"Polymorph\",\n \"desc\": [\n \"This spell transforms a creature that you can see within range into a new form. An unwilling creature must make a wisdom saving throw to avoid the effect. A shapechanger automatically succeeds on this saving throw.\",\n \"The transformation lasts for the duration, or until the target drops to 0 hit points or dies. The new form can be any beast whose challenge rating is equal to or less than the target's (or the target's level, if it doesn't have a challenge rating). The target's game statistics, including mental ability scores, are replaced by the statistics of the chosen beast. It retains its alignment and personality.\",\n \"The target assumes the hit points of its new form. When it reverts to its normal form, the creature returns to the number of hit points it had before it transformed. If it reverts as a result of dropping to 0 hit points, any excess damage carries over to its normal form. As long as the excess damage doesn't reduce the creature's normal form to 0 hit points, it isn't knocked unconscious.\",\n \"The creature is limited in the actions it can perform by the nature of its new form, and it can't speak, cast spells, or take any other action that requires hands or speech.\",\n \"The target's gear melds into the new form. The creature can't activate, use, wield, or otherwise benefit from any of its equipment.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A caterpillar cocoon.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/polymorph\"\n },\n {\n \"index\": \"power-word-kill\",\n \"name\": \"Power Word Kill\",\n \"desc\": [\n \"You utter a word of power that can compel one creature you can see within range to die instantly. If the creature you choose has 100 hit points or fewer, it dies. Otherwise, the spell has no effect.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/power-word-kill\"\n },\n {\n \"index\": \"power-word-stun\",\n \"name\": \"Power Word Stun\",\n \"desc\": [\n \"You speak a word of power that can overwhelm the mind of one creature you can see within range, leaving it dumbfounded. If the target has 150 hit points or fewer, it is stunned. Otherwise, the spell has no effect.\",\n \"The stunned target must make a constitution saving throw at the end of each of its turns. On a successful save, this stunning effect ends.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/power-word-stun\"\n },\n {\n \"index\": \"prayer-of-healing\",\n \"name\": \"Prayer of Healing\",\n \"desc\": [\n \"Up to six creatures of your choice that you can see within range each regain hit points equal to 2d8 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the healing increases by 1d8 for each slot level above 2nd.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 2,\n \"heal_at_slot_level\": {\n \"2\": \"2d8 + MOD\",\n \"3\": \"3d8 + MOD\",\n \"4\": \"4d8 + MOD\",\n \"5\": \"5d8 + MOD\",\n \"6\": \"6d8 + MOD\",\n \"7\": \"7d8 + MOD\",\n \"8\": \"8d8 + MOD\",\n \"9\": \"9d8 + MOD\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/prayer-of-healing\"\n },\n {\n \"index\": \"prestidigitation\",\n \"name\": \"Prestidigitation\",\n \"desc\": [\n \"This spell is a minor magical trick that novice spellcasters use for practice. You create one of the following magical effects within 'range':\",\n \"You create an instantaneous, harmless sensory effect, such as a shower of sparks, a puff of wind, faint musical notes, or an odd odor.\",\n \"You instantaneously light or snuff out a candle, a torch, or a small campfire.\",\n \"You instantaneously clean or soil an object no larger than 1 cubic foot.\",\n \"You chill, warm, or flavor up to 1 cubic foot of nonliving material for 1 hour.\",\n \"You make a color, a small mark, or a symbol appear on an object or a surface for 1 hour.\",\n \"You create a nonmagical trinket or an illusory image that can fit in your hand and that lasts until the end of your next turn.\",\n \"If you cast this spell multiple times, you can have up to three of its non-instantaneous effects active at a time, and you can dismiss such an effect as an action.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/prestidigitation\"\n },\n {\n \"index\": \"prismatic-spray\",\n \"name\": \"Prismatic Spray\",\n \"desc\": [\n \"Eight multicolored rays of light flash from your hand. Each ray is a different color and has a different power and purpose. Each creature in a 60-foot cone must make a dexterity saving throw. For each target, roll a d8 to determine which color ray affects it.\",\n \"***1. Red.*** The target takes 10d6 fire damage on a failed save, or half as much damage on a successful one.\",\n \"***2. Orange.*** The target takes 10d6 acid damage on a failed save, or half as much damage on a successful one.\",\n \"***3. Yellow.*** The target takes 10d6 lightning damage on a failed save, or half as much damage on a successful one.\",\n \"***4. Green.*** The target takes 10d6 poison damage on a failed save, or half as much damage on a successful one.\",\n \"***5. Blue.*** The target takes 10d6 cold damage on a failed save, or half as much damage on a successful one.\",\n \"***6. Indigo.*** On a failed save, the target is restrained. It must then make a constitution saving throw at the end of each of its turns. If it successfully saves three times, the spell ends. If it fails its save three times, it permanently turns to stone and is subjected to the petrified condition. The successes and failures don't need to be consecutive; keep track of both until the target collects three of a kind.\",\n \"***7. Violet.*** On a failed save, the target is blinded. It must then make a wisdom saving throw at the start of your next turn. A successful save ends the blindness. If it fails that save, the creature is transported to another plane of existence of the GM's choosing and is no longer blinded. (Typically, a creature that is on a plane that isn't its home plane is banished home, while other creatures are usually cast into the Astral or Ethereal planes.)\",\n \"***8. Special.*** The target is struck by two rays. Roll twice more, rerolling any 8.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"damage\": {\n \"damage_at_slot_level\": {\n \"7\": \"10d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"For each target, roll a d8 to determine which color ray affects it.\"\n },\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/prismatic-spray\"\n },\n {\n \"index\": \"prismatic-wall\",\n \"name\": \"Prismatic Wall\",\n \"desc\": [\n \"A shimmering, multicolored plane of light forms a vertical opaque wall--up to 90 feet long, 30 feet high, and 1 inch thick--centered on a point you can see within range. Alternatively, you can shape the wall into a sphere up to 30 feet in diameter centered on a point you choose within range. The wall remains in place for the duration. If you position the wall so that it passes through a space occupied by a creature, the spell fails, and your action and the spell slot are wasted.\",\n \"The wall sheds bright light out to a range of 100 feet and dim light for an additional 100 feet. You and creatures you designate at the time you cast the spell can pass through and remain near the wall without harm. If another creature that can see the wall moves to within 20 feet of it or starts its turn there, the creature must succeed on a constitution saving throw or become blinded for 1 minute.\",\n \"The wall consists of seven layers, each with a different color. When a creature attempts to reach into or pass through the wall, it does so one layer at a time through all the wall's layers. As it passes or reaches through each layer, the creature must make a dexterity saving throw or be affected by that layer's properties as described below.\",\n \"The wall can be destroyed, also one layer at a time, in order from red to violet, by means specific to each layer. Once a layer is destroyed, it remains so for the duration of the spell. A rod of cancellation destroys a prismatic wall, but an antimagic field has no effect on it.\",\n \"***1. Red.*** The creature takes 10d6 fire damage on a failed save, or half as much damage on a successful one. While this layer is in place, nonmagical ranged attacks can't pass through the wall. The layer can be destroyed by dealing at least 25 cold damage to it.\",\n \"***2. Orange.*** The creature takes 10d6 acid damage on a failed save, or half as much damage on a successful one. While this layer is in place, magical ranged attacks can't pass through the wall. The layer is destroyed by a strong wind.\",\n \"***3. Yellow.*** The creature takes 10d6 lightning damage on a failed save, or half as much damage on a successful one. This layer can be destroyed by dealing at least 60 force damage to it.\",\n \"***4. Green.*** The creature takes 10d6 poison damage on a failed save, or half as much damage on a successful one. A passwall spell, or another spell of equal or greater level that can open a portal on a solid surface, destroys this layer.\",\n \"***5. Blue.*** The creature takes 10d6 cold damage on a failed save, or half as much damage on a successful one. This layer can be destroyed by dealing at least 25 fire damage to it.\",\n \"***6. Indigo.*** On a failed save, the creature is restrained. It must then make a constitution saving throw at the end of each of its turns. If it successfully saves three times, the spell ends. If it fails its save three times, it permanently turns to stone and is subjected to the petrified condition. The successes and failures don't need to be consecutive; keep track of both until the creature collects three of a kind.\",\n \"While this layer is in place, spells can't be cast through the wall. The layer is destroyed by bright light shed by a daylight spell or a similar spell of equal or higher level.\",\n \"***7. Violet.*** On a failed save, the creature is blinded. It must then make a wisdom saving throw at the start of your next turn. A successful save ends the blindness. If it fails that save, the creature is transported to another plane of the GM's choosing and is no longer blinded. (Typically, a creature that is on a plane that isn't its home plane is banished home, while other creatures are usually cast into the Astral or Ethereal planes.) This layer is destroyed by a dispel magic spell or a similar spell of equal or higher level that can end spells and magical effects.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 90\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/prismatic-wall\"\n },\n {\n \"index\": \"private-sanctum\",\n \"name\": \"Private Sanctum\",\n \"desc\": [\n \"You make an area within range magically secure. The area is a cube that can be as small as 5 feet to as large as 100 feet on each side. The spell lasts for the duration or until you use an action to dismiss it.\",\n \"When you cast the spell, you decide what sort of security the spell provides, choosing any or all of the following properties:\",\n \"- Sound can't pass through the barrier at the edge of the warded area.\",\n \"- The barrier of the warded area appears dark and foggy, preventing vision (including darkvision) through it.\",\n \"- Sensors created by divination spells can't appear inside the protected area or pass through the barrier at its perimeter.\",\n \"- Creatures in the area can't be targeted by divination spells.\",\n \"- Nothing can teleport into or out of the warded area.\",\n \"- Planar travel is blocked within the warded area.\",\n \"Casting this spell on the same spot every day for a year makes this effect permanent.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, you can increase the size of the cube by 100 feet for each slot level beyond 4th. Thus you could protect a cube that can be up to 200 feet on one side by using a spell slot of 5th level.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A thin sheet of lead, a piece of opaque glass, a wad of cotton or cloth, and powdered chrysolite.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 4,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/private-sanctum\"\n },\n {\n \"index\": \"produce-flame\",\n \"name\": \"Produce Flame\",\n \"desc\": [\n \"A flickering flame appears in your hand. The flame remains there for the duration and harms neither you nor your equipment. The flame sheds bright light in a 10-foot radius and dim light for an additional 10 feet. The spell ends if you dismiss it as an action or if you cast it again.\",\n \"You can also attack with the flame, although doing so ends the spell. When you cast this spell, or as an action on a later turn, you can hurl the flame at a creature within 30 feet of you. Make a ranged spell attack. On a hit, the target takes 1d8 fire damage.\",\n \"This spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/produce-flame\"\n },\n {\n \"index\": \"programmed-illusion\",\n \"name\": \"Programmed Illusion\",\n \"desc\": [\n \"You create an illusion of an object, a creature, or some other visible phenomenon within range that activates when a specific condition occurs. The illusion is imperceptible until then. It must be no larger than a 30-foot cube, and you decide when you cast the spell how the illusion behaves and what sounds it makes. This scripted performance can last up to 5 minutes.\",\n \"When the condition you specify occurs, the illusion springs into existence and performs in the manner you described. Once the illusion finishes performing, it disappears and remains dormant for 10 minutes. After this time, the illusion can be activated again.\",\n \"The triggering condition can be as general or as detailed as you like, though it must be based on visual or audible conditions that occur within 30 feet of the area. For example, you could create an illusion of yourself to appear and warn off others who attempt to open a trapped door, or you could set the illusion to trigger only when a creature says the correct word or phrase.\",\n \"Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image, and any noise it makes sounds hollow to the creature.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fleece and jade dust worth at least 25 gp.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/programmed-illusion\"\n },\n {\n \"index\": \"project-image\",\n \"name\": \"Project Image\",\n \"desc\": [\n \"You create an illusory copy of yourself that lasts for the duration. The copy can appear at any location within range that you have seen before, regardless of intervening obstacles. The illusion looks and sounds like you but is intangible. If the illusion takes any damage, it disappears, and the spell ends.\",\n \"You can use your action to move this illusion up to twice your speed, and make it gesture, speak, and behave in whatever way you choose. It mimics your mannerisms perfectly.\",\n \"You can see through its eyes and hear through its ears as if you were in its space. On your turn as a bonus action, you can switch from using its senses to using your own, or back again. While you are using its senses, you are blinded and deafened in regard to your own surroundings.\",\n \"Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image, and any noise it makes sounds hollow to the creature.\"\n ],\n \"range\": \"500 miles\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small replica of you made from materials worth at least 5 gp.\",\n \"ritual\": false,\n \"duration\": \"Up to 24 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/project-image\"\n },\n {\n \"index\": \"protection-from-energy\",\n \"name\": \"Protection From Energy\",\n \"desc\": [\n \"For the duration, the willing creature you touch has resistance to one damage type of your choice: acid, cold, fire, lightning, or thunder.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/protection-from-energy\"\n },\n {\n \"index\": \"protection-from-evil-and-good\",\n \"name\": \"Protection from Evil and Good\",\n \"desc\": [\n \"Until the spell ends, one willing creature you touch is protected against certain types of creatures: aberrations, celestials, elementals, fey, fiends, and undead.\",\n \"The protection grants several benefits. Creatures of those types have disadvantage on attack rolls against the target. The target also can't be charmed, frightened, or possessed by them. If the target is already charmed, frightened, or possessed by such a creature, the target has advantage on any new saving throw against the relevant effect.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Holy water or powdered silver and iron, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/protection-from-evil-and-good\"\n },\n {\n \"index\": \"protection-from-poison\",\n \"name\": \"Protection from Poison\",\n \"desc\": [\n \"You touch a creature. If it is poisoned, you neutralize the poison. If more than one poison afflicts the target, you neutralize one poison that you know is present, or you neutralize one at random.\",\n \"For the duration, the target has advantage on saving throws against being poisoned, and it has resistance to poison damage.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/protection-from-poison\"\n },\n {\n \"index\": \"purify-food-and-drink\",\n \"name\": \"Purify Food and Drink\",\n \"desc\": [\n \"All nonmagical food and drink within a 5-foot radius sphere centered on a point of your choice within range is purified and rendered free of poison and disease.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/purify-food-and-drink\"\n },\n {\n \"index\": \"raise-dead\",\n \"name\": \"Raise Dead\",\n \"desc\": [\n \"You return a dead creature you touch to life, provided that it has been dead no longer than 10 days. If the creature's soul is both willing and at liberty to rejoin the body, the creature returns to life with 1 hit point.\",\n \"This spell also neutralizes any poisons and cures nonmagical diseases that affected the creature at the time it died. This spell doesn't, however, remove magical diseases, curses, or similar effects; if these aren't first removed prior to casting the spell, they take effect when the creature returns to life. The spell can't return an undead creature to life.\",\n \"This spell closes all mortal wounds, but it doesn't restore missing body parts. If the creature is lacking body parts or organs integral for its survival--its head, for instance--the spell automatically fails.\",\n \"Coming back from the dead is an ordeal. The target takes a -4 penalty to all attack rolls, saving throws, and ability checks. Every time the target finishes a long rest, the penalty is reduced by 1 until it disappears.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A diamond worth at least 500gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 5,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/raise-dead\"\n },\n {\n \"index\": \"ray-of-enfeeblement\",\n \"name\": \"Ray of Enfeeblement\",\n \"desc\": [\n \"A black beam of enervating energy springs from your finger toward a creature within range. Make a ranged spell attack against the target. On a hit, the target deals only half damage with weapon attacks that use Strength until the spell ends.\",\n \"At the end of each of the target's turns, it can make a constitution saving throw against the spell. On a success, the spell ends.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\"\n },\n \"attack_type\": \"ranged\",\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/ray-of-enfeeblement\"\n },\n {\n \"index\": \"ray-of-frost\",\n \"name\": \"Ray of Frost\",\n \"desc\": [\n \"A frigid beam of blue-white light streaks toward a creature within range. Make a ranged spell attack against the target. On a hit, it takes 1d8 cold damage, and its speed is reduced by 10 feet until the start of your next turn.\",\n \"The spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"cold\",\n \"name\": \"Cold\",\n \"url\": \"/api/damage-types/cold\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/ray-of-frost\"\n },\n {\n \"index\": \"regenerate\",\n \"name\": \"Regenerate\",\n \"desc\": [\n \"You touch a creature and stimulate its natural healing ability. The target regains 4d8 + 15 hit points. For the duration of the spell, the target regains 1 hit point at the start of each of its turns (10 hit points each minute).\",\n \"The target's severed body members (fingers, legs, tails, and so on), if any, are restored after 2 minutes. If you have the severed part and hold it to the stump, the spell instantaneously causes the limb to knit to the stump.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A prayer wheel and holy water.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 7,\n \"heal_at_slot_level\": {\n \"7\": \"4d8 + 15\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/regenerate\"\n },\n {\n \"index\": \"reincarnate\",\n \"name\": \"Reincarnate\",\n \"desc\": [\n \"You touch a dead humanoid or a piece of a dead humanoid. Provided that the creature has been dead no longer than 10 days, the spell forms a new adult body for it and then calls the soul to enter that body. If the target's soul isn't free or willing to do so, the spell fails.\",\n \"The magic fashions a new body for the creature to inhabit, which likely causes the creature's race to change. The GM rolls a d 100 and consults the following table to determine what form the creature takes when restored to life, or the GM chooses a form.\",\n \"| d100 | Race |\",\n \"|---|---|\",\n \"| 01-04 | Dragonborn |\",\n \"| 05-13 | Dwarf, hill |\",\n \"| 14-21 | Dwarf, mountain |\",\n \"| 22-25 | Elf, dark |\",\n \"| 26-34 | Elf, high |\",\n \"| 35-42 | Elf, wood |\",\n \"| 43-46 | Gnome, forest |\",\n \"| 47-52 | Gnome, rock |\",\n \"| 53-56 | Half-elf |\",\n \"| 57-60 | Half-orc |\",\n \"| 61-68 | Halfling, lightfoot |\",\n \"| 69-76 | Halfling, stout |\",\n \"| 77-96 | Human |\",\n \"| 97-00 | Tiefling |\",\n \"The reincarnated creature recalls its former life and experiences. It retains the capabilities it had in its original form, except it exchanges its original race for the new one and changes its racial traits accordingly.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Rare oils and unguents worth at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 5,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/reincarnate\"\n },\n {\n \"index\": \"remove-curse\",\n \"name\": \"Remove Curse\",\n \"desc\": [\n \"At your touch, all curses affecting one creature or object end. If the object is a cursed magic item, its curse remains, but the spell breaks its owner's attunement to the object so it can be removed or discarded.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/remove-curse\"\n },\n {\n \"index\": \"resilient-sphere\",\n \"name\": \"Resilient Sphere\",\n \"desc\": [\n \"A sphere of shimmering force encloses a creature or object of Large size or smaller within range. An unwilling creature must make a dexterity saving throw. On a failed save, the creature is enclosed for the duration.\",\n \"Nothing--not physical objects, energy, or other spell effects--can pass through the barrier, in or out, though a creature in the sphere can breathe there. The sphere is immune to all damage, and a creature or object inside can't be damaged by attacks or effects originating from outside, nor can a creature inside the sphere damage anything outside it.\",\n \"The sphere is weightless and just large enough to contain the creature or object inside. An enclosed creature can use its action to push against the sphere's walls and thus roll the sphere at up to half the creature's speed. Similarly, the globe can be picked up and moved by other creatures.\",\n \"A disintegrate spell targeting the globe destroys it without harming anything inside it.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A hemispherical piece of clear crystal and a matching hemispherical piece of gum arabic.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/resilient-sphere\"\n },\n {\n \"index\": \"resistance\",\n \"name\": \"Resistance\",\n \"desc\": [\n \"You touch one willing creature. Once before the spell ends, the target can roll a d4 and add the number rolled to one saving throw of its choice. It can roll the die before or after making the saving throw. The spell then ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A miniature cloak.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/resistance\"\n },\n {\n \"index\": \"resurrection\",\n \"name\": \"Resurrection\",\n \"desc\": [\n \"You touch a dead creature that has been dead for no more than a century, that didn't die of old age, and that isn't undead. If its soul is free and willing, the target returns to life with all its hit points.\",\n \"This spell neutralizes any poisons and cures normal diseases afflicting the creature when it died. It doesn't, however, remove magical diseases, curses, and the like; if such effects aren't removed prior to casting the spell, they afflict the target on its return to life.\",\n \"This spell closes all mortal wounds and restores any missing body parts.\",\n \"Coming back from the dead is an ordeal. The target takes a -4 penalty to all attack rolls, saving throws, and ability checks. Every time the target finishes a long rest, the penalty is reduced by 1 until it disappears.\",\n \"Casting this spell to restore life to a creature that has been dead for one year or longer taxes you greatly. Until you finish a long rest, you can't cast spells again, and you have disadvantage on all attack rolls, ability checks, and saving throws.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A diamond worth at least 1,000gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 7,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/resurrection\"\n },\n {\n \"index\": \"reverse-gravity\",\n \"name\": \"Reverse Gravity\",\n \"desc\": [\n \"This spell reverses gravity in a 50-foot-radius, 100-foot high cylinder centered on a point within range. All creatures and objects that aren't somehow anchored to the ground in the area fall upward and reach the top of the area when you cast this spell. A creature can make a dexterity saving throw to grab onto a fixed object it can reach, thus avoiding the fall.\",\n \"If some solid object (such as a ceiling) is encountered in this fall, falling objects and creatures strike it just as they would during a normal downward fall. If an object or creature reaches the top of the area without striking anything, it remains there, oscillating slightly, for the duration.\",\n \"At the end of the duration, affected objects and creatures fall back down.\"\n ],\n \"range\": \"100 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A lodestone and iron filings.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"A creature can make a dexterity saving throw to grab onto a fixed object it can reach, thus avoiding the fall.\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 50\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/reverse-gravity\"\n },\n {\n \"index\": \"revivify\",\n \"name\": \"Revivify\",\n \"desc\": [\n \"You touch a creature that has died within the last minute. That creature returns to life with 1 hit point. This spell can't return to life a creature that has died of old age, nor can it restore any missing body parts.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Diamonds worth 300gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/revivify\"\n },\n {\n \"index\": \"rope-trick\",\n \"name\": \"Rope Trick\",\n \"desc\": [\n \"You touch a length of rope that is up to 60 feet long. One end of the rope then rises into the air until the whole rope hangs perpendicular to the ground. At the upper end of the rope, an invisible entrance opens to an extradimensional space that lasts until the spell ends.\",\n \"The extradimensional space can be reached by climbing to the top of the rope. The space can hold as many as eight Medium or smaller creatures. The rope can be pulled into the space, making the rope disappear from view outside the space.\",\n \"Attacks and spells can't cross through the entrance into or out of the extradimensional space, but those inside can see out of it as if through a 3-foot-by-5-foot window centered on the rope.\",\n \"Anything inside the extradimensional space drops out when the spell ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Powdered corn extract and a twisted loop of parchment.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/rope-trick\"\n },\n {\n \"index\": \"sacred-flame\",\n \"name\": \"Sacred Flame\",\n \"desc\": [\n \"Flame-like radiance descends on a creature that you can see within range. The target must succeed on a dexterity saving throw or take 1d8 radiant damage. The target gains no benefit from cover for this saving throw.\",\n \"The spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/sacred-flame\"\n },\n {\n \"index\": \"sanctuary\",\n \"name\": \"Sanctuary\",\n \"desc\": [\n \"You ward a creature within range against attack. Until the spell ends, any creature who targets the warded creature with an attack or a harmful spell must first make a wisdom saving throw. On a failed save, the creature must choose a new target or lose the attack or spell. This spell doesn't protect the warded creature from area effects, such as the explosion of a fireball.\",\n \"If the warded creature makes an attack or casts a spell that affects an enemy creature, this spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small silver mirror.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/sanctuary\"\n },\n {\n \"index\": \"scorching-ray\",\n \"name\": \"Scorching Ray\",\n \"desc\": [\n \"You create three rays of fire and hurl them at targets within range. You can hurl them at one target or several.\",\n \"Make a ranged spell attack for each ray. On a hit, the target takes 2d6 fire damage.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you create one additional ray for each slot level above 2nd.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d6\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/scorching-ray\"\n },\n {\n \"index\": \"scrying\",\n \"name\": \"Scrying\",\n \"desc\": [\n \"You can see and hear a particular creature you choose that is on the same plane of existence as you. The target must make a wisdom saving throw, which is modified by how well you know the target and the sort of physical connection you have to it. If a target knows you're casting this spell, it can fail the saving throw voluntarily if it wants to be observed.\",\n \"| Knowledge | Save Modifier |\",\n \"|---|---|\",\n \"| Secondhand (you have heard of the target) | +5 |\",\n \"| Firsthand (you have met the target) | +0 |\",\n \"| Familiar (you know the target well) | -5 |\",\n \"\",\n \"| Connection | Save Modifier |\",\n \"|---|---|\",\n \"| Likeness or picture | -2 |\",\n \"| Possession or garment | -4 |\",\n \"| Body part, lock of hair, bit of nail, or the like | -10 |\",\n \"On a successful save, the target isn't affected, and you can't use this spell against it again for 24 hours.\",\n \"On a failed save, the spell creates an invisible sensor within 10 feet of the target. You can see and hear through the sensor as if you were there. The sensor moves with the target, remaining within 10 feet of it for the duration. A creature that can see invisible objects sees the sensor as a luminous orb about the size of your fist.\",\n \"Instead of targeting a creature, you can choose a location you have seen before as the target of this spell. When you do, the sensor appears at that location and doesn't move.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A focus worth at least 1,000 gp, such as a crystal ball, a silver mirror, or a font filled with holy water.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"10 minutes\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/scrying\"\n },\n {\n \"index\": \"secret-chest\",\n \"name\": \"Secret Chest\",\n \"desc\": [\n \"You hide a chest, and all its contents, on the Ethereal Plane. You must touch the chest and the miniature replica that serves as a material component for the spell. The chest can contain up to 12 cubic feet of nonliving material (3 feet by 2 feet by 2 feet).\",\n \"While the chest remains on the Ethereal Plane, you can use an action and touch the replica to recall the chest. It appears in an unoccupied space on the ground within 5 feet of you. You can send the chest back to the Ethereal Plane by using an action and touching both the chest and the replica.\",\n \"After 60 days, there is a cumulative 5 percent chance per day that the spell's effect ends. This effect ends if you cast this spell again, if the smaller replica chest is destroyed, or if you choose to end the spell as an action. If the spell ends and the larger chest is on the Ethereal Plane, it is irretrievably lost.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An exquisite chest, 3 feet by 2 feet by 2 feet, constructed from rare materials worth at least 5,000 gp, and a Tiny replica made from the same materials worth at least 50 gp.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/secret-chest\"\n },\n {\n \"index\": \"see-invisibility\",\n \"name\": \"See Invisibility\",\n \"desc\": [\n \"For the duration of the spell, you see invisible creatures and objects as if they were visible, and you can see through Ethereal. The ethereal objects and creatures appear ghostly translucent.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A dash of talc and a small amount of silver powder.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/see-invisibility\"\n },\n {\n \"index\": \"seeming\",\n \"name\": \"Seeming\",\n \"desc\": [\n \"This spell allows you to change the appearance of any number of creatures that you can see within range. You give each target you choose a new, illusory appearance. An unwilling target can make a charisma saving throw, and if it succeeds, it is unaffected by this spell.\",\n \"The spell disguises physical appearance as well as clothing, armor, weapons, and equipment. You can make each creature seem 1 foot shorter or taller and appear thin, fat, or in between. You can't change a target's body type, so you must choose a form that has the same basic arrangement of limbs. Otherwise, the extent of the illusion is up to you. The spell lasts for the duration, unless you use your action to dismiss it sooner.\",\n \"The changes wrought by this spell fail to hold up to physical inspection. For example, if you use this spell to add a hat to a creature's outfit, objects pass through the hat, and anyone who touches it would feel nothing or would feel the creature's head and hair. If you use this spell to appear thinner than you are, the hand of someone who reaches out to touch you would bump into you while it was seemingly still in midair.\",\n \"A creature can use its action to inspect a target and make an Intelligence (Investigation) check against your spell save DC. If it succeeds, it becomes aware that the target is disguised.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/seeming\"\n },\n {\n \"index\": \"sending\",\n \"name\": \"Sending\",\n \"desc\": [\n \"You send a short message of twenty-five words or less to a creature with which you are familiar. The creature hears the message in its mind, recognizes you as the sender if it knows you, and can answer in a like manner immediately. The spell enables creatures with Intelligence scores of at least 1 to understand the meaning of your message.\",\n \"You can send the message across any distance and even to other planes of existence, but if the target is on a different plane than you, there is a 5 percent chance that the message doesn't arrive.\"\n ],\n \"range\": \"Unlimited\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A short piece of fine copper wire.\",\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/sending\"\n },\n {\n \"index\": \"sequester\",\n \"name\": \"Sequester\",\n \"desc\": [\n \"By means of this spell, a willing creature or an object can be hidden away, safe from detection for the duration. When you cast the spell and touch the target, it becomes invisible and can't be targeted by divination spells or perceived through scrying sensors created by divination spells.\",\n \"If the target is a creature, it falls into a state of suspended animation. Time ceases to flow for it, and it doesn't grow older.\",\n \"You can set a condition for the spell to end early. The condition can be anything you choose, but it must occur or be visible within 1 mile of the target. Examples include \\\"after 1,000 years\\\" or \\\"when the tarrasque awakens.\\\" This spell also ends if the target takes any damage.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A powder composed of diamond, emerald, ruby, and sapphire dust worth at least 5,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/sequester\"\n },\n {\n \"index\": \"shapechange\",\n \"name\": \"Shapechange\",\n \"desc\": [\n \"You assume the form of a different creature for the duration. The new form can be of any creature with a challenge rating equal to your level or lower. The creature can't be a construct or an undead, and you must have seen the sort of creature at least once. You transform into an average example of that creature, one without any class levels or the Spellcasting trait.\",\n \"Your game statistics are replaced by the statistics of the chosen creature, though you retain your alignment and Intelligence, Wisdom, and Charisma scores. You also retain all of your skill and saving throw proficiencies, in addition to gaining those of the creature. If the creature has the same proficiency as you and the bonus listed in its statistics is higher than yours, use the creature's bonus in place of yours. You can't use any legendary actions or lair actions of the new form.\",\n \"You assume the hit points and Hit Dice of the new form. When you revert to your normal form, you return to the number of hit points you had before you transformed. If you revert as a result of dropping to 0 hit points, any excess damage carries over to your normal form. As long as the excess damage doesn't reduce your normal form to 0 hit points, you aren't knocked unconscious.\",\n \"You retain the benefit of any features from your class, race, or other source and can use them, provided that your new form is physically capable of doing so. You can't use any special senses you have (for example, darkvision) unless your new form also has that sense. You can only speak if the creature can normally speak.\",\n \"When you transform, you choose whether your equipment falls to the ground, merges into the new form, or is worn by it. Worn equipment functions as normal. The GM determines whether it is practical for the new form to wear a piece of equipment, based on the creature's shape and size. Your equipment doesn't change shape or size to match the new form, and any equipment that the new form can't wear must either fall to the ground or merge into your new form. Equipment that merges has no effect in that state.\",\n \"During this spell's duration, you can use your action to assume a different form following the same restrictions and rules for the original form, with one exception: if your new form has more hit points than your current one, your hit points remain at their current value.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A jade circlet worth at least 1,500 gp, which you must place on your head before you cast the spell.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/shapechange\"\n },\n {\n \"index\": \"shatter\",\n \"name\": \"Shatter\",\n \"desc\": [\n \"A sudden loud ringing noise, painfully intense, erupts from a point of your choice within range. Each creature in a 10-foot-radius sphere centered on that point must make a Constitution saving throw. A creature takes 3d8 thunder damage on a failed save, or half as much damage on a successful one. A creature made of inorganic material such as stone, crystal, or metal has disadvantage on this saving throw.\",\n \"A non-magical item that is not worn or carried also suffers damage if it is in the area of the spell.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 3 or higher level spell slot, the damage of the spell increases by 1d8 for each level of higher spell slot 2.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A burst of mica.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"thunder\",\n \"name\": \"Thunder\",\n \"url\": \"/api/damage-types/thunder\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"3d8\",\n \"3\": \"4d8\",\n \"4\": \"5d8\",\n \"5\": \"6d8\",\n \"6\": \"7d8\",\n \"7\": \"8d8\",\n \"8\": \"9d8\",\n \"9\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shatter\"\n },\n {\n \"index\": \"shield\",\n \"name\": \"Shield\",\n \"desc\": [\n \"An invisible barrier of magical force appears and protects you. Until the start of your next turn, you have a +5 bonus to AC, including against the triggering attack, and you take no damage from magic missile.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 reaction\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shield\"\n },\n {\n \"index\": \"shield-of-faith\",\n \"name\": \"Shield of Faith\",\n \"desc\": [\n \"A shimmering field appears and surrounds a creature of your choice within range, granting it a +2 bonus to AC for the duration.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small parchment with a bit of holy text written on it.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shield-of-faith\"\n },\n {\n \"index\": \"shillelagh\",\n \"name\": \"Shillelagh\",\n \"desc\": [\n \"The wood of a club or a quarterstaff you are holding is imbued with nature's power. For the duration, you can use your spellcasting ability instead of Strength for the attack and damage rolls of melee attacks using that weapon, and the weapon's damage die becomes a d8. The weapon also becomes magical, if it isn't already. The spell ends if you cast it again or if you let go of the weapon.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Mistletoe, a shamrock leaf, and a club or quarterstaff.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shillelagh\"\n },\n {\n \"index\": \"shocking-grasp\",\n \"name\": \"Shocking Grasp\",\n \"desc\": [\n \"Lightning springs from your hand to deliver a shock to a creature you try to touch. Make a melee spell attack against the target. You have advantage on the attack roll if the target is wearing armor made of metal. On a hit, the target takes 1d8 lightning damage, and it can't take reactions until the start of its next turn.\",\n \"The spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"lightning\",\n \"name\": \"Lightning\",\n \"url\": \"/api/damage-types/lightning\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shocking-grasp\"\n },\n {\n \"index\": \"silence\",\n \"name\": \"Silence\",\n \"desc\": [\n \"For the duration, no sound can be created within or pass through a 20-foot-radius sphere centered on a point you choose within range. Any creature or object entirely inside the sphere is immune to thunder damage, and creatures are deafened while entirely inside it.\",\n \"Casting a spell that includes a verbal component is impossible there.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/silence\"\n },\n {\n \"index\": \"silent-image\",\n \"name\": \"Silent Image\",\n \"desc\": [\n \"You create the image of an object, a creature, or some other visible phenomenon that is no larger than a 15-foot cube. The image appears at a spot within range and lasts for the duration. The image is purely visual; it isn't accompanied by sound, smell, or other sensory effects.\",\n \"You can use your action to cause the image to move to any spot within range. As the image changes location, you can alter its appearance so that its movements appear natural for the image. For example, if you create an image of a creature and move it, you can alter the image so that it appears to be walking.\",\n \"Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fleece.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/silent-image\"\n },\n {\n \"index\": \"simulacrum\",\n \"name\": \"Simulacrum\",\n \"desc\": [\n \"You shape an illusory duplicate of one beast or humanoid that is within range for the entire casting time of the spell. The duplicate is a creature, partially real and formed from ice or snow, and it can take actions and otherwise be affected as a normal creature. It appears to be the same as the original, but it has half the creature's hit point maximum and is formed without any equipment. Otherwise, the illusion uses all the statistics of the creature it duplicates.\",\n \"The simulacrum is friendly to you and creatures you designate. It obeys your spoken commands, moving and acting in accordance with your wishes and acting on your turn in combat. The simulacrum lacks the ability to learn or become more powerful, so it never increases its level or other abilities, nor can it regain expended spell slots.\",\n \"If the simulacrum is damaged, you can repair it in an alchemical laboratory, using rare herbs and minerals worth 100 gp per hit point it regains. The simulacrum lasts until it drops to 0 hit points, at which point it reverts to snow and melts instantly.\",\n \"If you cast this spell again, any currently active duplicates you created with this spell are instantly destroyed.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Snow or ice in quantities sufficient to made a life-size copy of the duplicated creature; some hair, fingernail clippings, or other piece of that creature's body placed inside the snow or ice; and powdered ruby worth 1,500 gp, sprinkled over the duplicate and consumed by the spell.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"12 hours\",\n \"level\": 7,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/simulacrum\"\n },\n {\n \"index\": \"sleep\",\n \"name\": \"Sleep\",\n \"desc\": [\n \"This spell sends creatures into a magical slumber. Roll 5d8; the total is how many hit points of creatures this spell can affect. Creatures within 20 feet of a point you choose within range are affected in ascending order of their current hit points (ignoring unconscious creatures).\",\n \"Starting with the creature that has the lowest current hit points, each creature affected by this spell falls unconscious until the spell ends, the sleeper takes damage, or someone uses an action to shake or slap the sleeper awake. Subtract each creature's hit points from the total before moving on to the creature with the next lowest hit points. A creature's hit points must be equal to or less than the remaining total for that creature to be affected.\",\n \"Undead and creatures immune to being charmed aren't affected by this spell.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, roll an additional 2d8 for each slot level above 1st.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of fine sand, rose petals, or a cricket.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"damage\": {\n \"damage_at_slot_level\": {\n \"1\": \"5d8\"\n }\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/sleep\"\n },\n {\n \"index\": \"sleet-storm\",\n \"name\": \"Sleet Storm\",\n \"desc\": [\n \"Until the spell ends, freezing rain and sleet fall in a 20-foot-tall cylinder with a 40-foot radius centered on a point you choose within range. The area is heavily obscured, and exposed flames in the area are doused.\",\n \"The ground in the area is covered with slick ice, making it difficult terrain. When a creature enters the spell's area for the first time on a turn or starts its turn there, it must make a dexterity saving throw. On a failed save, it falls prone.\",\n \"If a creature is concentrating in the spell's area, the creature must make a successful constitution saving throw against your spell save DC or lose concentration.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of dust and a few drops of water.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/sleet-storm\"\n },\n {\n \"index\": \"slow\",\n \"name\": \"Slow\",\n \"desc\": [\n \"You alter time around up to six creatures of your choice in a 40-foot cube within range. Each target must succeed on a wisdom saving throw or be affected by this spell for the duration.\",\n \"An affected target's speed is halved, it takes a -2 penalty to AC and dexterity saving throws, and it can't use reactions. On its turn, it can use either an action or a bonus action, not both. Regardless of the creature's abilities or magic items, it can't make more than one melee or ranged attack during its turn.\",\n \"If the creature attempts to cast a spell with a casting time of 1 action, roll a d20. On an 11 or higher, the spell doesn't take effect until the creature's next turn, and the creature must use its action on that turn to complete the spell. If it can't, the spell is wasted.\",\n \"A creature affected by this spell makes another wisdom saving throw at the end of its turn. On a successful save, the effect ends for it.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of molasses.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On failed save, the creature is slowed.\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/slow\"\n },\n {\n \"index\": \"spare-the-dying\",\n \"name\": \"Spare the Dying\",\n \"desc\": [\n \"You touch a living creature that has 0 hit points. The creature becomes stable. This spell has no effect on undead or constructs.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/spare-the-dying\"\n },\n {\n \"index\": \"speak-with-animals\",\n \"name\": \"Speak with Animals\",\n \"desc\": [\n \"You gain the ability to comprehend and verbally communicate with beasts for the duration. The knowledge and awareness of many beasts is limited by their intelligence, but at a minimum, beasts can give you information about nearby locations and monsters, including whatever they can perceive or have perceived within the past day. You might be able to persuade a beast to perform a small favor for you, at the GM's discretion.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/speak-with-animals\"\n },\n {\n \"index\": \"speak-with-dead\",\n \"name\": \"Speak with Dead\",\n \"desc\": [\n \"You grant the semblance of life and intelligence to a corpse of your choice within range, allowing it to answer the questions you pose. The corpse must still have a mouth and can't be undead. The spell fails if the corpse was the target of this spell within the last 10 days.\",\n \"Until the spell ends, you can ask the corpse up to five questions. The corpse knows only what it knew in life, including the languages it knew. Answers are usually brief, cryptic, or repetitive, and the corpse is under no compulsion to offer a truthful answer if you are hostile to it or it recognizes you as an enemy. This spell doesn't return the creature's soul to its body, only its animating spirit. Thus, the corpse can't learn new information, doesn't comprehend anything that has happened since it died, and can't speculate about future events.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Burning incense.\",\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/speak-with-dead\"\n },\n {\n \"index\": \"speak-with-plants\",\n \"name\": \"Speak with Plants\",\n \"desc\": [\n \"You imbue plants within 30 feet of you with limited sentience and animation, giving them the ability to communicate with you and follow your simple commands. You can question plants about events in the spell's area within the past day, gaining information about creatures that have passed, weather, and other circumstances.\",\n \"You can also turn difficult terrain caused by plant growth (such as thickets and undergrowth) into ordinary terrain that lasts for the duration. Or you can turn ordinary terrain where plants are present into difficult terrain that lasts for the duration, causing vines and branches to hinder pursuers, for example.\",\n \"Plants might be able to perform other tasks on your behalf, at the GM's discretion. The spell doesn't enable plants to uproot themselves and move about, but they can freely move branches, tendrils, and stalks.\",\n \"If a plant creature is in the area, you can communicate with it as if you shared a common language, but you gain no magical ability to influence it.\",\n \"This spell can cause the plants created by the entangle spell to release a restrained creature.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/speak-with-plants\"\n },\n {\n \"index\": \"spider-climb\",\n \"name\": \"Spider Climb\",\n \"desc\": [\n \"Until the spell ends, one willing creature you touch gains the ability to move up, down, and across vertical surfaces and upside down along ceilings, while leaving its hands free. The target also gains a climbing speed equal to its walking speed.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of bitumen and a spider.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/spider-climb\"\n },\n {\n \"index\": \"spike-growth\",\n \"name\": \"Spike Growth\",\n \"desc\": [\n \"The ground in a 20-foot radius centered on a point within range twists and sprouts hard spikes and thorns. The area becomes difficult terrain for the duration. When a creature moves into or within the area, it takes 2d4 piercing damage for every 5 feet it travels.\",\n \"The transformation of the ground is camouflaged to look natural. Any creature that can't see the area at the time the spell is cast can make a Wisdom (Perception) check against your spell save DC to recognize the terrain as hazardous before entering it.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Seven sharp thorns or seven small twigs, each sharpened to a point.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/spike-growth\"\n },\n {\n \"index\": \"spirit-guardians\",\n \"name\": \"Spirit Guardians\",\n \"desc\": [\n \"You call forth spirits to protect you. They flit around you to a distance of 15 feet for the duration. If you are good or neutral, their spectral form appears angelic or fey (your choice). If you are evil, they appear fiendish.\",\n \"When you cast this spell, you can designate any number of creatures you can see to be unaffected by it. An affected creature's speed is halved in the area, and when the creature enters the area for the first time on a turn or starts its turn there, it must make a wisdom saving throw. On a failed save, the creature takes 3d8 radiant damage (if you are good or neutral) or 3d8 necrotic damage (if you are evil). On a successful save, the creature takes half as much damage.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d8 for each slot level above 3rd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A holy symbol.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/spirit-guardians\"\n },\n {\n \"index\": \"spiritual-weapon\",\n \"name\": \"Spiritual Weapon\",\n \"desc\": [\n \"You create a floating, spectral weapon within range that lasts for the duration or until you cast this spell again. When you cast the spell, you can make a melee spell attack against a creature within 5 feet of the weapon. On a hit, the target takes force damage equal to 1d8 + your spellcasting ability modifier.\",\n \"As a bonus action on your turn, you can move the weapon up to 20 feet and repeat the attack against a creature within 5 feet of it.\",\n \"The weapon can take whatever form you choose. Clerics of deities who are associated with a particular weapon (as St. Cuthbert is known for his mace and Thor for his hammer) make this spell's effect resemble that weapon.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage increases by 1d8 for every two slot levels above the 2nd.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"1d8 + MOD\",\n \"3\": \"1d8 + MOD\",\n \"4\": \"2d8 + MOD\",\n \"5\": \"2d8 + MOD\",\n \"6\": \"3d8 + MOD\",\n \"7\": \"3d8 + MOD\",\n \"8\": \"4d8 + MOD\",\n \"9\": \"4d8 + MOD\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/spiritual-weapon\"\n },\n {\n \"index\": \"stinking-cloud\",\n \"name\": \"Stinking Cloud\",\n \"desc\": [\n \"You create a 20-foot-radius sphere of yellow, nauseating gas centered on a point within range. The cloud spreads around corners, and its area is heavily obscured. The cloud lingers in the air for the duration.\",\n \"Each creature that is completely within the cloud at the start of its turn must make a constitution saving throw against poison. On a failed save, the creature spends its action that turn retching and reeling. Creatures that don't need to breathe or are immune to poison automatically succeed on this saving throw.\",\n \"A moderate wind (at least 10 miles per hour) disperses the cloud after 4 rounds. A strong wind (at least 20 miles per hour) disperses it after 1 round.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A rotten egg or several skunk cabbage leaves.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, the creature spends its action that turn retching and reeling.\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/stinking-cloud\"\n },\n {\n \"index\": \"stone-shape\",\n \"name\": \"Stone Shape\",\n \"desc\": [\n \"You touch a stone object of Medium size or smaller or a section of stone no more than 5 feet in any dimension and form it into any shape that suits your purpose. So, for example, you could shape a large rock into a weapon, idol, or coffer, or make a small passage through a wall, as long as the wall is less than 5 feet thick. You could also shape a stone door or its frame to seal the door shut. The object you create can have up to two hinges and a latch, but finer mechanical detail isn't possible.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Soft clay, to be crudely worked into the desired shape for the stone object.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/stone-shape\"\n },\n {\n \"index\": \"stoneskin\",\n \"name\": \"Stoneskin\",\n \"desc\": [\n \"This spell turns the flesh of a willing creature you touch as hard as stone. Until the spell ends, the target has resistance to nonmagical bludgeoning, piercing, and slashing damage.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Diamond dust worth 100 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/stoneskin\"\n },\n {\n \"index\": \"storm-of-vengeance\",\n \"name\": \"Storm of Vengeance\",\n \"desc\": [\n \"A churning storm cloud forms, centered on a point you can see and spreading to a radius of 360 feet. Lightning flashes in the area, thunder booms, and strong winds roar. Each creature under the cloud (no more than 5,000 feet beneath the cloud) when it appears must make a constitution saving throw. On a failed save, a creature takes 2d6 thunder damage and becomes deafened for 5 minutes.\",\n \"Each round you maintain concentration on this spell, the storm produces additional effects on your turn.\",\n \"***Round 2.*** Acidic rain falls from the cloud. Each creature and object under the cloud takes 1d6 acid damage.\",\n \"***Round 3.*** You call six bolts of lightning from the cloud to strike six creatures or objects of your choice beneath the cloud. A given creature or object can't be struck by more than one bolt. A struck creature must make a dexterity saving throw. The creature takes 10d6 lightning damage on a failed save, or half as much damage on a successful one.\",\n \"***Round 4.*** Hailstones rain down from the cloud. Each creature under the cloud takes 2d6 bludgeoning damage.\",\n \"***Round 5-10.*** Gusts and freezing rain assail the area under the cloud. The area becomes difficult terrain and is heavily obscured. Each creature there takes 1d6 cold damage. Ranged weapon attacks in the area are impossible. The wind and rain count as a severe distraction for the purposes of maintaining concentration on spells. Finally, gusts of strong wind (ranging from 20 to 50 miles per hour) automatically disperse fog, mists, and similar phenomena in the area, whether mundane or magical.\"\n ],\n \"range\": \"Sight\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"thunder\",\n \"name\": \"Thunder\",\n \"url\": \"/api/damage-types/thunder\"\n },\n \"damage_at_slot_level\": {\n \"9\": \"2d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, a creature takes 2d6 thunder damage and becomes deafened for 5 minutes.\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 360\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/storm-of-vengeance\"\n },\n {\n \"index\": \"suggestion\",\n \"name\": \"Suggestion\",\n \"desc\": [\n \"You suggest a course of activity (limited to a sentence or two) and magically influence a creature you can see within range that can hear and understand you. Creatures that can't be charmed are immune to this effect. The suggestion must be worded in such a manner as to make the course of action sound reasonable. Asking the creature to stab itself, throw itself onto a spear, immolate itself, or do some other obviously harmful act ends the spell.\",\n \"The target must make a wisdom saving throw. On a failed save, it pursues the course of action you described to the best of its ability. The suggested course of action can continue for the entire duration. If the suggested activity can be completed in a shorter time, the spell ends when the subject finishes what it was asked to do.\",\n \"You can also specify conditions that will trigger a special activity during the duration. For example, you might suggest that a knight give her warhorse to the first beggar she meets. If the condition isn't met before the spell expires, the activity isn't performed.\",\n \"If you or any of your companions damage the target, the spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A snake's tongue and either a bit of honeycomb or a drop of sweet oil.\",\n \"ritual\": false,\n \"duration\": \"Up to 8 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/suggestion\"\n },\n {\n \"index\": \"sunbeam\",\n \"name\": \"Sunbeam\",\n \"desc\": [\n \"A beam of brilliant light flashes out from your hand in a 5-foot-wide, 60-foot-long line. Each creature in the line must make a constitution saving throw. On a failed save, a creature takes 6d8 radiant damage and is blinded until your next turn. On a successful save, it takes half as much damage and isn't blinded by this spell. Undead and oozes have disadvantage on this saving throw.\",\n \"You can create a new line of radiance as your action on any turn until the spell ends.\",\n \"For the duration, a mote of brilliant radiance shines in your hand. It sheds bright light in a 30-foot radius and dim light for an additional 30 feet. This light is sunlight.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A magnifying glass.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"6d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\",\n \"desc\": \"On a failed save, the creature is blinded until your next turn. On a successful save, it isn't blinded by this spell.\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/sunbeam\"\n },\n {\n \"index\": \"sunburst\",\n \"name\": \"Sunburst\",\n \"desc\": [\n \"Brilliant sunlight flashes in a 60-foot radius centered on a point you choose within range. Each creature in that light must make a constitution saving throw. On a failed save, a creature takes 12d6 radiant damage and is blinded for 1 minute. On a successful save, it takes half as much damage and isn't blinded by this spell. Undead and oozes have disadvantage on this saving throw.\",\n \"A creature blinded by this spell makes another constitution saving throw at the end of each of its turns. On a successful save, it is no longer blinded.\",\n \"This spell dispels any darkness in its area that was created by a spell.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Fire and a piece of sunstone.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"8\": \"12d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\",\n \"desc\": \"On failure, the creature is also blinded for 1 minute.\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/sunburst\"\n },\n {\n \"index\": \"symbol\",\n \"name\": \"Symbol\",\n \"desc\": [\n \"When you cast this spell, you inscribe a harmful glyph either on a surface (such as a section of floor, a wall, or a table) or within an object that can be closed to conceal the glyph (such as a book, a scroll, or a treasure chest). If you choose a surface, the glyph can cover an area of the surface no larger than 10 feet in diameter. If you choose an object, that object must remain in its place; if the object is moved more than 10 feet from where you cast this spell, the glyph is broken, and the spell ends without being triggered.\",\n \"The glyph is nearly invisible, requiring an Intelligence (Investigation) check against your spell save DC to find it.\",\n \"You decide what triggers the glyph when you cast the spell. For glyphs inscribed on a surface, the most typical triggers include touching or stepping on the glyph, removing another object covering it, approaching within a certain distance of it, or manipulating the object that holds it. For glyphs inscribed within an object, the most common triggers are opening the object, approaching within a certain distance of it, or seeing or reading the glyph.\",\n \"You can further refine the trigger so the spell is activated only under certain circumstances or according to a creature's physical characteristics (such as height or weight), or physical kind (for example, the ward could be set to affect hags or shapechangers). You can also specify creatures that don't trigger the glyph, such as those who say a certain password.\",\n \"When you inscribe the glyph, choose one of the options below for its effect. Once triggered, the glyph glows, filling a 60-foot-radius sphere with dim light for 10 minutes, after which time the spell ends. Each creature in the sphere when the glyph activates is targeted by its effect, as is a creature that enters the sphere for the first time on a turn or ends its turn there.\",\n \"***Death.*** Each target must make a constitution saving throw, taking 10d 10 necrotic damage on a failed save, or half as much damage on a successful save.\",\n \"***Discord.*** Each target must make a constitution saving throw. On a failed save, a target bickers and argues with other creatures for 1 minute. During this time, it is incapable of meaningful communication and has disadvantage on attack rolls and ability checks.\",\n \"***Fear.*** Each target must make a wisdom saving throw and becomes frightened for 1 minute on a failed save. While frightened, the target drops whatever it is holding and must move at least 30 feet away from the glyph on each of its turns, if able.\",\n \"***Hopelessness.*** Each target must make a charisma saving throw. On a failed save, the target is overwhelmed with despair for 1 minute. During this time, it can't attack or target any creature with harmful abilities, spells, or other magical effects.\",\n \"***Insanity.*** Each target must make an intelligence saving throw. On a failed save, the target is driven insane for 1 minute. An insane creature can't take actions, can't understand what other creatures say, can't read, and speaks only in gibberish. The GM controls its movement, which is erratic.\",\n \"***Pain.*** Each target must make a constitution saving throw and becomes incapacitated with excruciating pain for 1 minute on a failed save.\",\n \"***Sleep.*** Each target must make a wisdom saving throw and falls unconscious for 10 minutes on a failed save. A creature awakens if it takes damage or if someone uses an action to shake or slap it awake.\",\n \"***Stunning.*** Each target must make a wisdom saving throw and becomes stunned for 1 minute on a failed save.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Mercury, phosphorus, and powdered diamond and opal with a total value of at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/symbol\"\n },\n {\n \"index\": \"telekinesis\",\n \"name\": \"Telekinesis\",\n \"desc\": [\n \"You gain the ability to move or manipulate creatures or objects by thought. When you cast the spell, and as your action each round for the duration, you can exert your will on one creature or object that you can see within range, causing the appropriate effect below. You can affect the same target round after round, or choose a new one at any time. If you switch targets, the prior target is no longer affected by the spell.\",\n \"***Creature.*** You can try to move a Huge or smaller creature. Make an ability check with your spellcasting ability contested by the creature's Strength check. If you win the contest, you move the creature up to 30 feet in any direction, including upward but not beyond the range of this spell. Until the end of your next turn, the creature is restrained in your telekinetic grip. A creature lifted upward is suspended in mid-air.\",\n \"On subsequent rounds, you can use your action to attempt to maintain your telekinetic grip on the creature by repeating the contest.\",\n \"***Object.*** You can try to move an object that weighs up to 1,000 pounds. If the object isn't being worn or carried, you automatically move it up to 30 feet in any direction, but not beyond the range of this spell.\",\n \"If the object is worn or carried by a creature, you must make an ability check with your spellcasting ability contested by that creature's Strength check. If you succeed, you pull the object away from that creature and can move it up to 30 feet in any direction but not beyond the range of this spell.\",\n \"You can exert fine control on objects with your telekinetic grip, such as manipulating a simple tool, opening a door or a container, stowing or retrieving an item from an open container, or pouring the contents from a vial.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/telekinesis\"\n },\n {\n \"index\": \"telepathic-bond\",\n \"name\": \"Telepathic Bond\",\n \"desc\": [\n \"You forge a telepathic link among up to eight willing creatures of your choice within range, psychically linking each creature to all the others for the duration. Creatures with Intelligence scores of 2 or less aren't affected by this spell.\",\n \"Until the spell ends, the targets can communicate telepathically through the bond whether or not they have a common language. The communication is possible over any distance, though it can't extend to other planes of existence.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Pieces of eggshell from two different kinds of creatures\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/telepathic-bond\"\n },\n {\n \"index\": \"teleport\",\n \"name\": \"Teleport\",\n \"desc\": [\n \"This spell instantly transports you and up to eight willing creatures of your choice that you can see within range, or a single object that you can see within range, to a destination you select. If you target an object, it must be able to fit entirely inside a 10-foot cube, and it can't be held or carried by an unwilling creature.\",\n \"The destination you choose must be known to you, and it must be on the same plane of existence as you. Your familiarity with the destination determines whether you arrive there successfully. The GM rolls d100 and consults the table.\",\n \"| Familiarity | Mishap | Similar Area | Off Target | On Target |\",\n \"|---|---|---|---|---|\",\n \"| Permanent circle | -- | -- | -- | 01-100 |\",\n \"| Associated object | -- | -- | -- | 01-100 |\",\n \"| Very familiar | 01-05 | 06-13 | 14-24 | 25-100 |\",\n \"| Seen casually | 01-33 | 34-43 | 44-53 | 54-100 |\",\n \"| Viewed once | 01-43 | 44-53 | 54-73 | 74-100 |\",\n \"| Description | 01-43 | 44-53 | 54-73 | 74-100 |\",\n \"| False destination | 01-50 | 51-100 | -- | -- |\",\n \"***Familiarity.*** \\\"Permanent circle\\\" means a permanent teleportation circle whose sigil sequence you know.\",\n \"\\\"Associated object\\\" means that you possess an object taken from the desired destination within the last six months, such as a book from a wizard's library, bed linen from a royal suite, or a chunk of marble from a lich's secret tomb.\",\n \"\\\"Very familiar\\\" is a place you have been very often, a place you have carefully studied, or a place you can see when you cast the spell.\",\n \"\\\"Seen casually\\\" is someplace you have seen more than once but with which you aren't very familiar.\",\n \"\\\"Viewed once\\\" is a place you have seen once, possibly using magic.\",\n \"\\\"Description\\\" is a place whose location and appearance you know through someone else's description, perhaps from a map.\",\n \"\\\"False destination\\\" is a place that doesn't exist. Perhaps you tried to scry an enemy's sanctum but instead viewed an illusion, or you are attempting to teleport to a familiar location that no longer exists.\",\n \"***On Target.*** You and your group (or the target object) appear where you want to.\",\n \"***Off Target.*** You and your group (or the target object) appear a random distance away from the destination in a random direction. Distance off target is 1d10 x 1d10 percent of the distance that was to be traveled. For example, if you tried to travel 120 miles, landed off target, and rolled a 5 and 3 on the two d10s, then you would be off target by 15 percent, or 18 miles. The GM determines the direction off target randomly by rolling a d8 and designating 1 as north, 2 as northeast, 3 as east, and so on around the points of the compass. If you were teleporting to a coastal city and wound up 18 miles out at sea, you could be in trouble.\",\n \"***Similar Area.*** You and your group (or the target object) wind up in a different area that's visually or thematically similar to the target area. If you are heading for your home laboratory, for example, you might wind up in another wizard's laboratory or in an alchemical supply shop that has many of the same tools and implements as your laboratory. Generally, you appear in the closest similar place, but since the spell has no range limit, you could conceivably wind up anywhere on the plane.\",\n \"***Mishap.*** The spell's unpredictable magic results in a difficult journey. Each teleporting creature (or the target object) takes 3d10 force damage, and the GM rerolls on the table to see where you wind up (multiple mishaps can occur, dealing damage each time).\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/teleport\"\n },\n {\n \"index\": \"teleportation-circle\",\n \"name\": \"Teleportation Circle\",\n \"desc\": [\n \"As you cast the spell, you draw a 10-foot-diameter circle on the ground inscribed with sigils that link your location to a permanent teleportation circle of your choice whose sigil sequence you know and that is on the same plane of existence as you. A shimmering portal opens within the circle you drew and remains open until the end of your next turn. Any creature that enters the portal instantly appears within 5 feet of the destination circle or in the nearest unoccupied space if that space is occupied.\",\n \"Many major temples, guilds, and other important places have permanent teleportation circles inscribed somewhere within their confines. Each such circle includes a unique sigil sequence--a string of magical runes arranged in a particular pattern. When you first gain the ability to cast this spell, you learn the sigil sequences for two destinations on the Material Plane, determined by the GM. You can learn additional sigil sequences during your adventures. You can commit a new sigil sequence to memory after studying it for 1 minute.\",\n \"You can create a permanent teleportation circle by casting this spell in the same location every day for one year. You need not use the circle to teleport when you cast the spell in this way.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"Rare chalks and inks infused with precious gems with 50 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/teleportation-circle\"\n },\n {\n \"index\": \"thaumaturgy\",\n \"name\": \"Thaumaturgy\",\n \"desc\": [\n \"You manifest a minor wonder, a sign of supernatural power, within range. You create one of the following magical effects within range.\",\n \"- Your voice booms up to three times as loud as normal for 1 minute.\",\n \"- You cause flames to flicker, brighten, dim, or change color for 1 minute.\",\n \"- You cause harmless tremors in the ground for 1 minute.\",\n \"- You create an instantaneous sound that originates from a point of your choice within range, such as a rumble of thunder, the cry of a raven, or ominous whispers.\",\n \"- You instantaneously cause an unlocked door or window to fly open or slam shut.\",\n \"- You alter the appearance of your eyes for 1 minute.\",\n \"If you cast this spell multiple times, you can have up to three of its 1-minute effects active at a time, and you can dismiss such an effect as an action.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/thaumaturgy\"\n },\n {\n \"index\": \"thunderwave\",\n \"name\": \"Thunderwave\",\n \"desc\": [\n \"A wave of thunderous force sweeps out from you. Each creature in a 15-foot cube originating from you must make a constitution saving throw. On a failed save, a creature takes 2d8 thunder damage and is pushed 10 feet away from you. On a successful save, the creature takes half as much damage and isn't pushed.\",\n \"In addition, unsecured objects that are completely within the area of effect are automatically pushed 10 feet away from you by the spell's effect, and the spell emits a thunderous boom audible out to 300 feet.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d8 for each slot level above 1st.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"thunder\",\n \"name\": \"Thunder\",\n \"url\": \"/api/damage-types/thunder\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"2d8\",\n \"2\": \"3d8\",\n \"3\": \"4d8\",\n \"4\": \"5d8\",\n \"5\": \"6d8\",\n \"6\": \"7d8\",\n \"7\": \"8d8\",\n \"8\": \"9d8\",\n \"9\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/thunderwave\"\n },\n {\n \"index\": \"time-stop\",\n \"name\": \"Time Stop\",\n \"desc\": [\n \"You briefly stop the flow of time for everyone but yourself. No time passes for other creatures, while you take 1d4 + 1 turns in a row, during which you can use actions and move as normal.\",\n \"This spell ends if one of the actions you use during this period, or any effects that you create during this period, affects a creature other than you or an object being worn or carried by someone other than you. In addition, the spell ends if you move to a place more than 1,000 feet from the location where you cast it.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/time-stop\"\n },\n {\n \"index\": \"tiny-hut\",\n \"name\": \"Tiny Hut\",\n \"desc\": [\n \"A 10-foot-radius immobile dome of force springs into existence around and above you and remains stationary for the duration. The spell ends if you leave its area.\",\n \"Nine creatures of Medium size or smaller can fit inside the dome with you. The spell fails if its area includes a larger creature or more than nine creatures. Creatures and objects within the dome when you cast this spell can move through it freely. All other creatures and objects are barred from passing through it. Spells and other magical effects can't extend through the dome or be cast through it. The atmosphere inside the space is comfortable and dry, regardless of the weather outside.\",\n \"Until the spell ends, you can command the interior to become dimly lit or dark. The dome is opaque from the outside, of any color you choose, but it is transparent from the inside.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small crystal bead.\",\n \"ritual\": true,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/tiny-hut\"\n },\n {\n \"index\": \"tongues\",\n \"name\": \"Tongues\",\n \"desc\": [\n \"This spell grants the creature you touch the ability to understand any spoken language it hears. Moreover, when the target speaks, any creature that knows at least one language and can hear the target understands what it says.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A small clay model of a ziggurat.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/tongues\"\n },\n {\n \"index\": \"transport-via-plants\",\n \"name\": \"Transport via Plants\",\n \"desc\": [\n \"This spell creates a magical link between a Large or larger inanimate plant within range and another plant, at any distance, on the same plane of existence. You must have seen or touched the destination plant at least once before. For the duration, any creature can step into the target plant and exit from the destination plant by using 5 feet of movement.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/transport-via-plants\"\n },\n {\n \"index\": \"tree-stride\",\n \"name\": \"Tree Stride\",\n \"desc\": [\n \"You gain the ability to enter a tree and move from inside it to inside another tree of the same kind within 500 feet. Both trees must be living and at least the same size as you. You must use 5 feet of movement to enter a tree. You instantly know the location of all other trees of the same kind within 500 feet and, as part of the move used to enter the tree, can either pass into one of those trees or step out of the tree you're in. You appear in a spot of your choice within 5 feet of the destination tree, using another 5 feet of movement. If you have no movement left, you appear within 5 feet of the tree you entered.\",\n \"You can use this transportation ability once per round for the duration. You must end each turn outside a tree.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/tree-stride\"\n },\n {\n \"index\": \"true-polymorph\",\n \"name\": \"True Polymorph\",\n \"desc\": [\n \"Choose one creature or nonmagical object that you can see within range. You transform the creature into a different creature, the creature into an object, or the object into a creature (the object must be neither worn nor carried by another creature). The transformation lasts for the duration, or until the target drops to 0 hit points or dies. If you concentrate on this spell for the full duration, the transformation becomes permanent.\",\n \"Shapechangers aren't affected by this spell. An unwilling creature can make a wisdom saving throw, and if it succeeds, it isn't affected by this spell.\",\n \"***Creature into Creature.*** If you turn a creature into another kind of creature, the new form can be any kind you choose whose challenge rating is equal to or less than the target's (or its level, if the target doesn't have a challenge rating). The target's game statistics, including mental ability scores, are replaced by the statistics of the new form. It retains its alignment and personality.\",\n \"The target assumes the hit points of its new form, and when it reverts to its normal form, the creature returns to the number of hit points it had before it transformed. If it reverts as a result of dropping to 0 hit points, any excess damage carries over to its normal form. As long as the excess damage doesn't reduce the creature's normal form to 0 hit points, it isn't knocked unconscious.\",\n \"The creature is limited in the actions it can perform by the nature of its new form, and it can't speak, cast spells, or take any other action that requires hands or speech unless its new form is capable of such actions.\",\n \"The target's gear melds into the new form. The creature can't activate, use, wield, or otherwise benefit from any of its equipment.\",\n \"***Object into Creature.*** You can turn an object into any kind of creature, as long as the creature's size is no larger than the object's size and the creature's challenge rating is 9 or lower. The creature is friendly to you and your companions. It acts on each of your turns. You decide what action it takes and how it moves. The GM has the creature's statistics and resolves all of its actions and movement.\",\n \"If the spell becomes permanent, you no longer control the creature. It might remain friendly to you, depending on how you have treated it.\",\n \"***Creature into Object.*** If you turn a creature into an object, it transforms along with whatever it is wearing and carrying into that form. The creature's statistics become those of the object, and the creature has no memory of time spent in this form, after the spell ends and it returns to its normal form.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of mercury, a dollop of gum arabic, and a wisp of smoke.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/true-polymorph\"\n },\n {\n \"index\": \"true-resurrection\",\n \"name\": \"True Resurrection\",\n \"desc\": [\n \"You touch a creature that has been dead for no longer than 200 years and that died for any reason except old age. If the creature's soul is free and willing, the creature is restored to life with all its hit points.\",\n \"This spell closes all wounds, neutralizes any poison, cures all diseases, and lifts any curses affecting the creature when it died. The spell replaces damaged or missing organs and limbs.\",\n \"The spell can even provide a new body if the original no longer exists, in which case you must speak the creature's name. The creature then appears in an unoccupied space you choose within 10 feet of you.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sprinkle of holy water and diamonds worth at least 25,000gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 9,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/true-resurrection\"\n },\n {\n \"index\": \"true-seeing\",\n \"name\": \"True Seeing\",\n \"desc\": [\n \"This spell gives the willing creature you touch the ability to see things as they actually are. For the duration, the creature has truesight, notices secret doors hidden by magic, and can see into the Ethereal Plane, all out to a range of 120 feet.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An ointment for the eyes that costs 25gp; is made from mushroom powder, saffron, and fat; and is consumed by the spell.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/true-seeing\"\n },\n {\n \"index\": \"true-strike\",\n \"name\": \"True Strike\",\n \"desc\": [\n \"You extend your hand and point a finger at a target in range. Your magic grants you a brief insight into the target's defenses. On your next turn, you gain advantage on your first attack roll against the target, provided that this spell hasn't ended.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 round\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/true-strike\"\n },\n {\n \"index\": \"unseen-servant\",\n \"name\": \"Unseen Servant\",\n \"desc\": [\n \"This spell creates an invisible, mindless, shapeless force that performs simple tasks at your command until the spell ends. The servant springs into existence in an unoccupied space on the ground within range. It has AC 10, 1 hit point, and a Strength of 2, and it can't attack. If it drops to 0 hit points, the spell ends.\",\n \"Once on each of your turns as a bonus action, you can mentally command the servant to move up to 15 feet and interact with an object. The servant can perform simple tasks that a human servant could do, such as fetching things, cleaning, mending, folding clothes, lighting fires, serving food, and pouring wine. Once you give the command, the servant performs the task to the best of its ability until it completes the task, then waits for your next command.\",\n \"If you command the servant to perform a task that would move it more than 60 feet away from you, the spell ends.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of string and a bit of wood.\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/unseen-servant\"\n },\n {\n \"index\": \"vampiric-touch\",\n \"name\": \"Vampiric Touch\",\n \"desc\": [\n \"The touch of your shadow-wreathed hand can siphon life force from others to heal your wounds. Make a melee spell attack against a creature within your reach. On a hit, the target takes 3d6 necrotic damage, and you regain hit points equal to half the amount of necrotic damage dealt. Until the spell ends, you can make the attack again on each of your turns as an action.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d6 for each slot level above 3rd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"3d6\",\n \"4\": \"4d6\",\n \"5\": \"5d6\",\n \"6\": \"6d6\",\n \"7\": \"7d6\",\n \"8\": \"8d6\",\n \"9\": \"9d6\"\n }\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/vampiric-touch\"\n },\n {\n \"index\": \"vicious-mockery\",\n \"name\": \"Vicious Mockery\",\n \"desc\": [\n \"You unleash a string of insults laced with subtle enchantments at a creature you can see within range. If the target can hear you (though it need not understand you), it must succeed on a wisdom saving throw or take 1d4 psychic damage and have disadvantage on the next attack roll it makes before the end of its next turn.\",\n \"This spell's damage increases by 1d4 when you reach 5th level (2d4), 11th level (3d4), and 17th level (4d4).\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"psychic\",\n \"name\": \"Psychic\",\n \"url\": \"/api/damage-types/psychic\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d4\",\n \"5\": \"2d4\",\n \"11\": \"3d4\",\n \"17\": \"4d4\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/vicious-mockery\"\n },\n {\n \"index\": \"wall-of-fire\",\n \"name\": \"Wall of Fire\",\n \"desc\": [\n \"You create a wall of fire on a solid surface within range. You can make the wall up to 60 feet long, 20 feet high, and 1 foot thick, or a ringed wall up to 20 feet in diameter, 20 feet high, and 1 foot thick. The wall is opaque and lasts for the duration.\",\n \"When the wall appears, each creature within its area must make a Dexterity saving throw. On a failed save, a creature takes 5d8 fire damage, or half as much damage on a successful save.\",\n \"One side of the wall, selected by you when you cast this spell, deals 5d8 fire damage to each creature that ends its turn within 10 feet o f that side or inside the wall. A creature takes the same damage when it enters the wall for the first time on a turn or ends its turn there. The other side of the wall deals no damage.\",\n \"The other side of the wall deals no damage.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, the damage increases by 1d8 for each slot level above 4th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small piece of phosphorus.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"5d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/wall-of-fire\"\n },\n {\n \"index\": \"wall-of-force\",\n \"name\": \"Wall of Force\",\n \"desc\": [\n \"An invisible wall of force springs into existence at a point you choose within range. The wall appears in any orientation you choose, as a horizontal or vertical barrier or at an angle. It can be free floating or resting on a solid surface. You can form it into a hemispherical dome or a sphere with a radius of up to 10 feet, or you can shape a flat surface made up of ten 10-foot-by-10-foot panels. Each panel must be contiguous with another panel. In any form, the wall is 1/4 inch thick. It lasts for the duration. If the wall cuts through a creature's space when it appears, the creature is pushed to one side of the wall (your choice which side).\",\n \"Nothing can physically pass through the wall. It is immune to all damage and can't be dispelled by dispel magic. A disintegrate spell destroys the wall instantly, however. The wall also extends into the Ethereal Plane, blocking ethereal travel through the wall.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of powder made by crushing a clear gemstone.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wall-of-force\"\n },\n {\n \"index\": \"wall-of-ice\",\n \"name\": \"Wall of Ice\",\n \"desc\": [\n \"You create a wall of ice on a solid surface within range. You can form it into a hemispherical dome or a sphere with a radius of up to 10 feet, or you can shape a flat surface made up of ten 10-foot-square panels. Each panel must be contiguous with another panel. In any form, the wall is 1 foot thick and lasts for the duration.\",\n \"If the wall cuts through a creature's space when it appears, the creature within its area is pushed to one side of the wall and must make a dexterity saving throw. On a failed save, the creature takes 10d6 cold damage, or half as much damage on a successful save.\",\n \"The wall is an object that can be damaged and thus breached. It has AC 12 and 30 hit points per 10-foot section, and it is vulnerable to fire damage. Reducing a 10-foot section of wall to 0 hit points destroys it and leaves behind a sheet of frigid air in the space the wall occupied. A creature moving through the sheet of frigid air for the first time on a turn must make a constitution saving throw. That creature takes 5d6 cold damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the damage the wall deals when it appears increases by 2d6, and the damage from passing through the sheet of frigid air increases by 1d6, for each slot level above 6th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small piece of quartz.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"cold\",\n \"name\": \"Cold\",\n \"url\": \"/api/damage-types/cold\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"10d6\",\n \"7\": \"12d6\",\n \"8\": \"14d6\",\n \"9\": \"16d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wall-of-ice\"\n },\n {\n \"index\": \"wall-of-stone\",\n \"name\": \"Wall of Stone\",\n \"desc\": [\n \"A nonmagical wall of solid stone springs into existence at a point you choose within range. The wall is 6 inches thick and is composed of ten 10-foot-by-10-foot panels. Each panel must be contiguous with at least one other panel. Alternatively, you can create 10-foot-by-20-foot panels that are only 3 inches thick.\",\n \"If the wall cuts through a creature's space when it appears, the creature is pushed to one side of the wall (your choice). If a creature would be surrounded on all sides by the wall (or the wall and another solid surface), that creature can make a dexterity saving throw. On a success, it can use its reaction to move up to its speed so that it is no longer enclosed by the wall.\",\n \"The wall can have any shape you desire, though it can't occupy the same space as a creature or object. The wall doesn't need to be vertical or rest on any firm foundation. It must, however, merge with and be solidly supported by existing stone. Thus, you can use this spell to bridge a chasm or create a ramp.\",\n \"If you create a span greater than 20 feet in length, you must halve the size of each panel to create supports. You can crudely shape the wall to create crenellations, battlements, and so on.\",\n \"The wall is an object made of stone that can be damaged and thus breached. Each panel has AC 15 and 30 hit points per inch of thickness. Reducing a panel to 0 hit points destroys it and might cause connected panels to collapse at the GM's discretion.\",\n \"If you maintain your concentration on this spell for its whole duration, the wall becomes permanent and can't be dispelled. Otherwise, the wall disappears when the spell ends.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small block of granite.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/wall-of-stone\"\n },\n {\n \"index\": \"wall-of-thorns\",\n \"name\": \"Wall of Thorns\",\n \"desc\": [\n \"You create a wall of tough, pliable, tangled brush bristling with needle-sharp thorns. The wall appears within range on a solid surface and lasts for the duration. You choose to make the wall up to 60 feet long, 10 feet high, and 5 feet thick or a circle that has a 20-foot diameter and is up to 20 feet high and 5 feet thick. The wall blocks line of sight.\",\n \"When the wall appears, each creature within its area must make a dexterity saving throw. On a failed save, a creature takes 7d8 piercing damage, or half as much damage on a successful save.\",\n \"A creature can move through the wall, albeit slowly and painfully. For every 1 foot a creature moves through the wall, it must spend 4 feet of movement. Furthermore, the first time a creature enters the wall on a turn or ends its turn there, the creature must make a dexterity saving throw. It takes 7d8 slashing damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, both types of damage increase by 1d8 for each slot level above 6th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A handful of thorns.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"piercing\",\n \"name\": \"Piercing\",\n \"url\": \"/api/damage-types/piercing\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"7d8\",\n \"7\": \"8d8\",\n \"8\": \"9d8\",\n \"9\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wall-of-thorns\"\n },\n {\n \"index\": \"warding-bond\",\n \"name\": \"Warding Bond\",\n \"desc\": [\n \"This spell wards a willing creature you touch and creates a mystic connection between you and the target until the spell ends. While the target is within 60 feet of you, it gains a +1 bonus to AC and saving throws, and it has resistance to all damage. Also, each time it takes damage, you take the same amount of damage.\",\n \"The spell ends if you drop to 0 hit points or if you and the target become separated by more than 60 feet.\",\n \"It also ends if the spell is cast again on either of the connected creatures. You can also dismiss the spell as an action.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pair of platinum rings worth at least 50gp each, which you and the target must wear for the duration.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/warding-bond\"\n },\n {\n \"index\": \"water-breathing\",\n \"name\": \"Water Breathing\",\n \"desc\": [\n \"This spell gives a maximum of ten willing creatures within range and you can see, the ability to breathe underwater until the end of its term. Affected creatures also retain their normal breathing pattern.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A short piece of reed or straw.\",\n \"ritual\": true,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/water-breathing\"\n },\n {\n \"index\": \"water-walk\",\n \"name\": \"Water Walk\",\n \"desc\": [\n \"This spell grants the ability to move across any liquid surface--such as water, acid, mud, snow, quicksand, or lava--as if it were harmless solid ground (creatures crossing molten lava can still take damage from the heat). Up to ten willing creatures you can see within range gain this ability for the duration.\",\n \"If you target a creature submerged in a liquid, the spell carries the target to the surface of the liquid at a rate of 60 feet per round.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of cork.\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/water-walk\"\n },\n {\n \"index\": \"web\",\n \"name\": \"Web\",\n \"desc\": [\n \"You conjure a mass of thick, sticky webbing at a point of your choice within range. The webs fill a 20-foot cube from that point for the duration. The webs are difficult terrain and lightly obscure their area.\",\n \"If the webs aren't anchored between two solid masses (such as walls or trees) or layered across a floor, wall, or ceiling, the conjured web collapses on itself, and the spell ends at the start of your next turn. Webs layered over a flat surface have a depth of 5 feet.\",\n \"Each creature that starts its turn in the webs or that enters them during its turn must make a dexterity saving throw. On a failed save, the creature is restrained as long as it remains in the webs or until it breaks free.\",\n \"A creature restrained by the webs can use its action to make a Strength check against your spell save DC. If it succeeds, it is no longer restrained.\",\n \"The webs are flammable. Any 5-foot cube of webs exposed to fire burns away in 1 round, dealing 2d4 fire damage to any creature that starts its turn in the fire.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of spiderweb.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/web\"\n },\n {\n \"index\": \"weird\",\n \"name\": \"Weird\",\n \"desc\": [\n \"Drawing on the deepest fears of a group of creatures, you create illusory creatures in their minds, visible only to them. Each creature in a 30-foot-radius sphere centered on a point of your choice within range must make a wisdom saving throw. On a failed save, a creature becomes frightened for the duration. The illusion calls on the creature's deepest fears, manifesting its worst nightmares as an implacable threat. At the start of each of the frightened creature's turns, it must succeed on a wisdom saving throw or take 4d10 psychic damage. On a successful save, the spell ends for that creature.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/weird\"\n },\n {\n \"index\": \"wind-walk\",\n \"name\": \"Wind Walk\",\n \"desc\": [\n \"You and up to ten willing creatures you can see within range assume a gaseous form for the duration, appearing as wisps of cloud. While in this cloud form, a creature has a flying speed of 300 feet and has resistance to damage from nonmagical weapons. The only actions a creature can take in this form are the Dash action or to revert to its normal form. Reverting takes 1 minute, during which time a creature is incapacitated and can't move. Until the spell ends, a creature can revert to cloud form, which also requires the 1-minute transformation.\",\n \"If a creature is in cloud form and flying when the effect ends, the creature descends 60 feet per round for 1 minute until it lands, which it does safely. If it can't land after 1 minute, the creature falls the remaining distance.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Fire and holy water.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wind-walk\"\n },\n {\n \"index\": \"wind-wall\",\n \"name\": \"Wind Wall\",\n \"desc\": [\n \"A wall of strong wind rises from the ground at a point you choose within range. You can make the wall up to 50 feet long, 15 feet high, and 1 foot thick. You can shape the wall in any way you choose so long as it makes one continuous path along the ground. The wall lasts for the duration.\",\n \"When the wall appears, each creature within its area must make a strength saving throw. A creature takes 3d8 bludgeoning damage on a failed save, or half as much damage on a successful one.\",\n \"The strong wind keeps fog, smoke, and other gases at bay. Small or smaller flying creatures or objects can't pass through the wall. Loose, lightweight materials brought into the wall fly upward. Arrows, bolts, and other ordinary projectiles launched at targets behind the wall are deflected upward and automatically miss. (Boulders hurled by giants or siege engines, and similar projectiles, are unaffected.) Creatures in gaseous form can't pass through it.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny fan and a feather of exotic origin.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"bludgeoning\",\n \"name\": \"Bludgeoning\",\n \"url\": \"/api/damage-types/bludgeoning\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"3d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"str\",\n \"name\": \"STR\",\n \"url\": \"/api/ability-scores/str\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 50\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/wind-wall\"\n },\n {\n \"index\": \"wish\",\n \"name\": \"Wish\",\n \"desc\": [\n \"Wish is the mightiest spell a mortal creature can cast. By simply speaking aloud, you can alter the very foundations of reality in accord with your desires.\",\n \"The basic use of this spell is to duplicate any other spell of 8th level or lower. You don't need to meet any requirements in that spell, including costly components. The spell simply takes effect.\",\n \"Alternatively, you can create one of the following effects of your choice:\",\n \"- You create one object of up to 25,000 gp in value that isn't a magic item. The object can be no more than 300 feet in any dimension, and it appears in an unoccupied space you can see on the ground.\",\n \"- You allow up to twenty creatures that you can see to regain all hit points, and you end all effects on them described in the greater restoration spell.\",\n \"- You grant up to ten creatures that you can see resistance to a damage type you choose.\",\n \"- You grant up to ten creatures you can see immunity to a single spell or other magical effect for 8 hours. For instance, you could make yourself and all your companions immune to a lich's life drain attack.\",\n \"- You undo a single recent event by forcing a reroll of any roll made within the last round (including your last turn). Reality reshapes itself to accommodate the new result. For example, a wish spell could undo an opponent's successful save, a foe's critical hit, or a friend's failed save. You can force the reroll to be made with advantage or disadvantage, and you can choose whether to use the reroll or the original roll.\",\n \"You might be able to achieve something beyond the scope of the above examples. State your wish to the GM as precisely as possible. The GM has great latitude in ruling what occurs in such an instance; the greater the wish, the greater the likelihood that something goes wrong. This spell might simply fail, the effect you desire might only be partly achieved, or you might suffer some unforeseen consequence as a result of how you worded the wish. For example, wishing that a villain were dead might propel you forward in time to a period when that villain is no longer alive, effectively removing you from the game. Similarly, wishing for a legendary magic item or artifact might instantly transport you to the presence of the item's current owner.\",\n \"The stress of casting this spell to produce any effect other than duplicating another spell weakens you. After enduring that stress, each time you cast a spell until you finish a long rest, you take 1d10 necrotic damage per level of that spell. This damage can't be reduced or prevented in any way. In addition, your Strength drops to 3, if it isn't 3 or lower already, for 2d4 days. For each of those days that you spend resting and doing nothing more than light activity, your remaining recovery time decreases by 2 days. Finally, there is a 33 percent chance that you are unable to cast wish ever again if you suffer this stress.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wish\"\n },\n {\n \"index\": \"word-of-recall\",\n \"name\": \"Word of Recall\",\n \"desc\": [\n \"You and up to five willing creatures within 5 feet of you instantly teleport to a previously designated sanctuary. You and any creatures that teleport with you appear in the nearest unoccupied space to the spot you designated when you prepared your sanctuary (see below). If you cast this spell without first preparing a sanctuary, the spell has no effect.\",\n \"You must designate a sanctuary by casting this spell within a location, such as a temple, dedicated to or strongly linked to your deity. If you attempt to cast the spell in this manner in an area that isn't dedicated to your deity, the spell has no effect.\"\n ],\n \"range\": \"5 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/word-of-recall\"\n },\n {\n \"index\": \"zone-of-truth\",\n \"name\": \"Zone of Truth\",\n \"desc\": [\n \"You create a magical zone that guards against deception in a 15-foot-radius sphere centered on a point of your choice within range. Until the spell ends, a creature that enters the spell's area for the first time on a turn or starts its turn there must make a Charisma saving throw. On a failed save, a creature can't speak a deliberate lie while in the radius. You know whether each creature succeeds or fails on its saving throw.\",\n \"An affected creature is aware of the spell and can thus avoid answering questions to which it would normally respond with a lie. Such a creature can remain evasive in its answers as long as it remains within the boundaries of the truth.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/zone-of-truth\"\n }\n]\n", "import spellData from '../5e-SRD-Spells.json';\nimport { getCurrentCharacter } from '../services/CharacterService';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n
    \n
    \n
    \n \n \n
    \n
    \n
    \n
    \n
      \n
    • \n
    • \n
    • \n
    • \n
    • \n
    \n
    \n
    \n
    \n`;\n\nclass SpellItem extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.#setupElements();\n }\n\n connectedCallback () {\n this.#loadData();\n this.#populateSpellItem();\n\n this.#setupEventListeners();\n }\n\n disconnectedCallback () {\n this.#removeEventListeners();\n }\n\n // Group together html elements for readability\n #setupElements () {\n this.elements = {\n accordion: this.shadowRoot.querySelector('.accordion'),\n accordion_icon: this.shadowRoot.querySelector('.accordion-icon'),\n panel: this.shadowRoot.querySelector('.panel'),\n add_button: this.shadowRoot.querySelector('.spell-item-add'),\n stats: this.shadowRoot.querySelector('.spell-item-stats'),\n spell_range: this.shadowRoot.querySelector('.spell-item-range'),\n spell_components: this.shadowRoot.querySelector('.spell-item-comps'),\n spell_duration: this.shadowRoot.querySelector('.spell-item-dur'),\n spell_casting: this.shadowRoot.querySelector('.spell-item-casting'),\n spell_concentration: this.shadowRoot.querySelector('.spell-item-conc'),\n spell_name: this.shadowRoot.querySelector('.spell-item-name'),\n spell_description: this.shadowRoot.querySelector('.spell-item-desc'),\n spell_higher_level: this.shadowRoot.querySelector('.spell-item-hl'),\n added_indicator: this.shadowRoot.querySelector('.spell-item-added')\n };\n }\n\n #setupEventListeners () {\n this.elements.accordion.addEventListener('click', this._handleAccordionClick.bind(this));\n this.elements.add_button.addEventListener('click', this._handleAddNewSpell.bind(this));\n }\n\n #removeEventListeners () {\n this.elements.accordion.removeEventListener('click', this._handleAccordionClick);\n this.elements.add_button.removeEventListener('click', this._handleAddNewSpell);\n }\n \n #loadData () {\n this.cur_character = getCurrentCharacter();\n this.spell = spellData.filter((spell) => spell.name === this.dataset.name)[0]; // filter returns an array\n this.elements.accordion_icon.innerHTML = '⌄'; // down-chevron\n }\n\n // Declutters #populateSpellItem\n #setElementContent (selector, content) {\n this.elements[selector].innerHTML = content;\n }\n \n /**\n * Populate the content of the spell item\n */\n #populateSpellItem () {\n const spell = this.spell;\n\n this.#setElementContent('spell_name', `${spell.name}`);\n this.#setElementContent('spell_range', `Range: ${spell.range}`);\n this.#setElementContent('spell_components', `Components: ${spell.components}`);\n this.#setElementContent('spell_duration', `Duration: ${spell.duration}`);\n this.#setElementContent('spell_casting', `Casting Time: ${spell.casting_time}`);\n // Break up each section of the spell description\n this.#setElementContent('spell_description', `Description:
    ${spell.desc.join('

    ')}`);\n \n if (spell.concentration) {\n this.#setElementContent('spell_concentration', `Requires Concentration`);\n }\n\n if (spell.higher_level !== undefined) {\n this.#setElementContent('spell_higher_level', `At Higher Levels:
    ${spell.higher_level}`);\n }\n }\n\n #updateAddedIndicator () {\n const characterSpells = this.cur_character.getSpells(this.dataset.subfield);\n const spellWasAdded = characterSpells.includes(this.spell.name);\n\n if (spellWasAdded) {\n this.#setElementContent('added_indicator', `Added ✓`);\n };\n }\n\n _handleAddNewSpell (ev) {\n const level = this.dataset.subfield;\n\n this.cur_character.setSpells(this.spell, level);\n this.#updateAddedIndicator();\n }\n\n _handleAccordionClick (ev) {\n // Prevent the dropdown from opening on add\n if (ev.target === this.elements.add_button) {\n return;\n }\n\n const panelStyle = this.elements.panel.style;\n\n panelStyle.display = panelStyle.display === 'flex' ? 'none' : 'flex';\n this.elements.accordion_icon.innerHTML = panelStyle.display === 'flex' ? '⌃' : '⌄'; // up chevron and down chevron\n }\n}\n\nif (!window.customElements.get('spell-item')) {\n window.customElements.define('spell-item', SpellItem);\n}\n\nexport default SpellItem;\n", "import spellData from '../5e-SRD-Spells.json';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n`;\n\nclass AddSpellButton extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n this.addEventListener('click', this._handleClick.bind(this));\n }\n\n disconnectedCallback () {\n this.removeEventListener('click', this._handleClick.bind(this));\n }\n\n // Opens the spell modal\n _handleClick (ev) {\n this.spellDialog = this.spellDialog || document.getElementById('dialog-spells');\n this.spellDialog.clear();\n\n if (this.spellDialog.isOpen) {\n this.spellDialog.close();\n return;\n };\n\n const modal = document.getElementById('spellModal');\n const content = document.importNode(modal.content, true);\n const list = content.querySelector('ul');\n const spellLevel = ev.target.dataset.level;\n\n try {\n const spells = spellData.filter((spell) => spell.level === Number(spellLevel));\n\n spells.forEach(spell => {\n const spellItem = document.createElement('spell-item');\n\n spellItem.dataset.name = spell.name;\n spellItem.dataset.subfield = spell.level;\n\n list.appendChild(spellItem);\n });\n } catch (error) {\n console.log(error);\n const item = document.createElement('div');\n item.innerText = 'Unable to access this resource at the moment.';\n list.appendChild(item);\n };\n\n this.spellDialog.setContent([...content.children]);\n this.spellDialog.open();\n }\n}\n\nif (!window.customElements.get('add-spell-button')) {\n window.customElements.define('add-spell-button', AddSpellButton);\n}\n\nexport default AddSpellButton;\n", "/* eslint-disable no-unused-vars */\nimport EventEmitter from './services/EventEmitter.js';\nimport Manager from './views/Manager.js';\n\n// All the web components we need in the app.\nimport ActionMenu from './views/ActionMenu.js';\nimport NoteListItem from './components/NoteListItem.js';\nimport NoteList from './components/NoteList.js';\nimport SimpleList from './components/SimpleList.js';\nimport TableEditable from './components/TableEditable.js';\nimport SkillListing from './components/SkillListing.js';\nimport AttributeListing from './components/AttributeListing.js';\nimport DiceRoller from './components/DiceRoller.js';\nimport Die from './components/Die.js';\nimport EditableField from './components/EditableField.js';\nimport FooterNav from './components/FooterNav.js';\nimport ConfirmButton from './components/ConfirmButton.js';\nimport Modal from './components/Modal.js';\nimport SpellItem from './components/SpellItem.js';\nimport AddSpellButton from './components/AddSpellButton.js';\n\n/**\n* Register service worker if it's supported\n*/\nif ('serviceWorker' in navigator) {\n navigator.serviceWorker.register(\n './service_worker.js',\n {\n type: 'module'\n }\n );\n}\n\nconst emitter = new EventEmitter();\n\ndocument.querySelector('action-menu').setEmitter(emitter);\n\nManager.initialize({\n emitter,\n prefix: 'charsheet-app-',\n appname: 'character-sheet'\n});\n"], + "sourcesContent": ["/**\n * @prop {Object} events Store the events here.\n * @prop {Boolean} debug So you can more easily in dev see when events are triggered.\n */\nexport default class EventEmitter {\n constructor () {\n this.events = {};\n this.debug = false;\n }\n /**\n * Get index of listener in the event array.\n * -1 means it isn't there\n * @param {String} event Event to check.\n * @param {Function} listener Listener to check.\n * @return {Number}\n */\n listenerIndex (event, listener) {\n return this.events[event].findIndex((item) => {\n return item.listener === listener;\n });\n }\n /**\n * Listen to an event\n * @param {String} event Name of the event to listen for.\n * @param {Function|Array} listener Callback to trigger for event OR an array of [classname, methodName]\n * @param {Object} boundObj Object to bind the callback to.\n * @return {undefined}\n */\n on (event, listener, boundObj = null) {\n if (typeof listener !== 'function') {\n return;\n }\n this.events[event] = this.events[event] || [];\n if (this.events[event].length > 0) {\n const index = this.listenerIndex(event, listener);\n // Replace the listener if it already exists.\n if (index > -1) {\n this.events[event].splice(index, 1);\n }\n }\n this.events[event].push({ listener, boundObj });\n }\n /**\n * Stop listening to an event.\n * Remove event if it was the last listener.\n * @param {String} event Name of the event.\n * @param {Function} listener Callback to remove.\n * @return {undefined}\n */\n off (event, listener) {\n if (Array.isArray(this.events[event])) {\n const index = this.listenerIndex(event, listener);\n if (index === -1) {\n return;\n }\n this.events[event].splice(index, 1);\n if (this.events[event].length === 0) {\n delete this.events[event];\n }\n }\n }\n /**\n * Listen for an event but only trigger it once, then it is removed.\n * @param {String} event Name of the event to listen for.\n * @param {Function} listener Callback to trigger for event.\n * @param {Object} boundObj Object to bind the callback to.\n */\n once (event, listener, boundObj) {\n this.on(event, function wrap () {\n this.off(event, wrap);\n const binder = typeof boundObj === 'undefined' ? this : boundObj;\n listener.apply(binder, arguments);\n });\n }\n /**\n * Trigger an event. This will cause any listeners for that event to be called.\n * Any arguments after the event will be passed on to the callback(s).\n * @param {String} event Event to trigger.\n */\n trigger (event) {\n if (this.debug && console) {\n console.log(`EventEmitter triggered: ${event}`);\n }\n const args = [].slice.call(arguments, 1);\n\n if (Array.isArray(this.events[event])) {\n this.events[event].forEach((listenObj) => {\n const binder = listenObj.boundObj === null ? this : listenObj.boundObj;\n listenObj.listener.apply(binder, args);\n });\n }\n };\n};\n", "/** Note object */\nexport default class CharacterNote {\n constructor ({\n header = '',\n text = ''\n }) {\n this.header = header;\n this.text = text;\n }\n toJSON () {\n const obj = {};\n const props = Object.getOwnPropertyNames(this);\n props.forEach((prop) => {\n obj[prop] = this[prop];\n });\n return obj;\n }\n};\n", "import CharacterNote from './CharacterNote.js';\n\n/**\n * Generic Character Modal.\n * Extend for different rules/games/properties.\n * This is only props/methods that apply to all.\n * Another not set here, should only be used in the appropriate SheetView.\n *\n * @prop {String} key Unique (in one instance of the app) id for the character. 7 Random letters/numbers.\n * @prop {String} charname Name.\n * @prop {String} updated UTC date string.\n * @prop {String} key_prev If character was imported into app with identical key. This is that key and the character is given a new one on import.\n * @prop {String} version Version number (semver format) of app.\n */\nexport default class Character {\n constructor ({\n key = '',\n charname = '',\n updated = '',\n key_prev = '',\n version = ''\n }) {\n this.key = key;\n this.charname = charname;\n this.updated = updated;\n this.key_prev = key_prev;\n this.version = version;\n }\n /**\n * Localized last updated string.\n */\n get updatedTime () {\n const date = new Date(this.updated);\n return date.toLocaleString();\n }\n /**\n * Class name (for JSON (de)serialization). Override in children.\n */\n get className () {\n return 'Character';\n }\n /**\n * Ruleset name. Override in children.\n */\n get ruleset () {\n return 'Generic';\n }\n /**\n * A quick summary header for use in lists.\n */\n get summaryHeader () {\n return `${this.charname} (${this.ruleset})`;\n }\n /**\n * Convert notes arrays from Array[] or Object[] to CharacterNotes[]\n * @param {Array} noteArray\n * @returns\n */\n _convertNotes (noteArray) {\n const value = [];\n noteArray.forEach((item) => {\n // Remove null and non-objects\n if (item && typeof item !== 'object') {\n return;\n }\n if (item instanceof CharacterNote) {\n value.push(item);\n return;\n }\n // @version < 3.0.0 backwards compat\n if (Array.isArray(item)) {\n // convert\n value.push(new CharacterNote({\n header: item[0] || '',\n text: item[1] || ''\n }));\n return;\n }\n value.push(new CharacterNote(item));\n });\n return value;\n }\n /**\n * Converting _ props for saving.\n * @returns {Object}\n */\n toJSON () {\n const obj = {\n className: this.className\n };\n const props = Object.getOwnPropertyNames(this);\n props.forEach((prop) => {\n if (prop === 'emitter') {\n return;\n }\n let value = this[prop];\n if (Array.isArray(value)) {\n value = value.map((el) => {\n if (typeof el.toJSON === 'function') {\n return el.toJSON();\n }\n return el;\n });\n }\n if (prop.substring(0, 1) === '_') {\n obj[prop.substring(1)] = value;\n } else {\n obj[prop] = value;\n }\n });\n return obj;\n }\n}\n", "/**\n * Matching attribute full names to the character properties.\n */\nexport const attributes = Object.freeze({\n STRENGTH: 'str',\n DEXTERITY: 'dex',\n CONSTITUTION: 'con',\n INTELLIGENCE: 'intel',\n WISDOM: 'wis',\n CHARISMA: 'cha'\n});\n\n/**\n * Matching skills to attributes.\n */\nexport const skillAttributes = Object.freeze({\n acrobatics: attributes.DEXTERITY,\n animal_handling: attributes.WISDOM,\n arcana: attributes.INTELLIGENCE,\n athletics: attributes.STRENGTH,\n deception: attributes.CHARISMA,\n history: attributes.INTELLIGENCE,\n insight: attributes.WISDOM,\n intimidation: attributes.CHARISMA,\n investigation: attributes.INTELLIGENCE,\n medicine: attributes.WISDOM,\n nature: attributes.INTELLIGENCE,\n perception: attributes.WISDOM,\n performance: attributes.CHARISMA,\n persuasion: attributes.CHARISMA,\n religion: attributes.INTELLIGENCE,\n sleight_of_hand: attributes.DEXTERITY,\n stealth: attributes.DEXTERITY,\n survival: attributes.WISDOM\n});\n\nexport const skillLevels = Object.freeze({\n UNSKILLED: 0,\n PROFICIENT: 1,\n EXPERT: 2\n});\n", "/** Weapon object */\nexport default class Weapon {\n constructor ({\n name = '',\n attack = '',\n damage = '',\n notes = ''\n }) {\n this.name = name;\n this.attack = attack;\n this.damage = damage;\n this.notes = notes;\n }\n toJSON () {\n const obj = {};\n const props = Object.getOwnPropertyNames(this);\n props.forEach((prop) => {\n obj[prop] = this[prop];\n });\n return obj;\n }\n};\n", "/**\n * Model for 5e character data\n */\n\nimport { skillAttributes, skillLevels } from './CharacterConstants5e.js';\nimport Weapon from './Weapon.js';\nimport Character from './Character.js';\n\nexport default class Character5e extends Character {\n /**\n * Property notes...\n * @prop {String} key Unique (in one instance of the app) id for the character. 7 Random letters/numbers.\n * @prop {String} charname Name.\n * @prop {Object} class_points Class point like ki, sorcerer points, etc.\n * @prop {Number} class_points.cur\n * @prop {Number} class_points.max\n * @prop {Weapon[]} weapons Weapon data (name, att, dam, notes).\n * @prop {String[]} features Special features and abilities.\n * @prop {String[]} equipment Stuff the character carries.\n * @prop {CharacterNote[]} notes_adv Adventure notes\n * @prop {CharacterNote[]} notes_cam Campaign notes\n * @prop {CharacterNote[]} npcs NPC notes\n * @prop {CharacterNote[]} factions NPC notes\n * @prop {CharacterNote[]} partymembers Other party members.\n * @prop {Object} skills Skill and its level. 0/1/2 (See skillLevels).\n */\n constructor ({\n key = '',\n charname = '',\n charclass = '',\n race = '',\n background = '',\n alignment = '',\n level = 1,\n experience = 0,\n inspiration = '',\n armor_class = '',\n speed = 30,\n hp_cur = '',\n hp_max = '',\n hd_cur = '',\n hd_max = '',\n deathSave = {\n success: 0,\n fail: 0\n },\n class_points = {\n cur: 0,\n max: 0\n },\n str = 10,\n dex = 10,\n con = 10,\n intel = 10,\n wis = 10,\n cha = 10,\n saves = {\n str: 0,\n dex: 0,\n con: 0,\n intel: 0,\n wis: 0,\n cha: 0\n },\n skills = {\n acrobatics: 0,\n animal_handling: 0,\n arcana: 0,\n athletics: 0,\n deception: 0,\n history: 0,\n insight: 0,\n intimidation: 0,\n investigation: 0,\n medicine: 0,\n nature: 0,\n perception: 0,\n performance: 0,\n persuasion: 0,\n religion: 0,\n sleight_of_hand: 0,\n stealth: 0,\n survival: 0\n },\n weapons = [],\n proficiencies_other = '',\n languages = '',\n traits = '',\n ideals = '',\n bonds = '',\n flaws = '',\n appearance = '',\n equipment = [],\n cp = '',\n sp = '',\n gp = '',\n pp = '',\n features = [],\n notes = '',\n notes_adv = [],\n notes_cam = [],\n npcs = [],\n factions = [],\n partymembers = [],\n spell_ability = '',\n spell_save = '',\n spell_attack = '',\n spell_slots = {\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0,\n 7: 0,\n 8: 0,\n 9: 0\n },\n spell_slots_cur = {\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0,\n 7: 0,\n 8: 0,\n 9: 0\n },\n spells = {\n 0: [],\n 1: [],\n 2: [],\n 3: [],\n 4: [],\n 5: [],\n 6: [],\n 7: [],\n 8: [],\n 9: []\n },\n updated = '',\n key_prev = '',\n version = ''\n }) {\n super({\n key,\n charname,\n updated,\n key_prev,\n version\n });\n this.charclass = charclass;\n this.race = race;\n this.background = background;\n this.alignment = alignment;\n // use underscore so we can use getter/setters on level itself.\n this._level = level;\n this.experience = experience;\n this.inspiration = inspiration;\n this.armor_class = armor_class;\n this.speed = speed;\n this.hp_cur = hp_cur;\n this.hp_max = hp_max;\n this.hd_cur = hd_cur;\n this.hd_max = hd_max;\n this.deathSave = deathSave;\n this.class_points = class_points;\n this.str = str;\n this.dex = dex;\n this.con = con;\n this.intel = intel;\n this.wis = wis;\n this.cha = cha;\n this.saves = saves;\n this.skills = skills;\n // @version < 2.2.0 Backwards compatibile convert sleight_of_Hand to sleight_of_hand\n if (typeof this.skills.sleight_of_Hand !== 'undefined') {\n const sleight = this.skills.sleight_of_Hand;\n delete this.skills.sleight_of_Hand;\n this.skills.sleight_of_hand = sleight;\n }\n\n this.weapons = [];\n weapons.forEach((item) => {\n // Remove null and non-objects\n if (item && typeof item !== 'object') {\n return;\n }\n // @version < 3.0.0 backwards compat\n if (Array.isArray(item)) {\n // convert\n this.weapons.push(new Weapon({\n name: item[0] || '',\n attack: item[1] || '',\n damage: item[2] || '',\n notes: item[3] || ''\n }));\n return;\n }\n if (item instanceof Weapon) {\n this.weapons.push(item);\n return;\n }\n this.weapons.push(new Weapon(item));\n });\n\n this.proficiencies_other = proficiencies_other;\n this.languages = languages;\n this.traits = traits;\n this.ideals = ideals;\n this.bonds = bonds;\n this.flaws = flaws;\n this.appearance = appearance;\n this.equipment = equipment;\n this.cp = cp;\n this.sp = sp;\n this.gp = gp;\n this.pp = pp;\n this.features = features;\n this.notes = notes;\n this.notes_adv = this._convertNotes(notes_adv);\n this.notes_cam = this._convertNotes(notes_cam);\n this.npcs = this._convertNotes(npcs);\n this.factions = this._convertNotes(factions);\n this.partymembers = this._convertNotes(partymembers);\n this.spell_ability = spell_ability;\n this.spell_save = spell_save;\n this.spell_attack = spell_attack;\n this.spell_slots = spell_slots;\n this.spell_slots_cur = spell_slots_cur;\n this.spells = spells;\n\n this.emitter = null;\n }\n get className () {\n return 'Character5e';\n }\n get ruleset () {\n return '5e';\n }\n /**\n * Level getter.\n * @returns {Number}\n */\n get level () {\n return this._level;\n }\n /**\n * Set level and trigger proficiency update if necessary.\n * @param {Number}\n */\n set level (newVal) {\n const cur = this.level;\n if (newVal === cur) {\n return;\n }\n const prof = this.proficiency;\n this._level = newVal;\n const newProf = this.proficiency;\n if (prof === newProf) {\n return;\n }\n if (this.emitter) {\n this.emitter.trigger('character:proficiency:update');\n }\n }\n /**\n * Proficiency modifier as string.\n * @returns {String}\n */\n get proficiency () {\n const bonus = Math.ceil(this.level / 4) + 1;\n return `+${bonus}`;\n }\n /**\n * Set an attribute score.\n * @param {String} attribute\n * @param {Number} value\n */\n setAttribute (attribute, value) {\n if (!this[attribute]) {\n return;\n }\n const curVal = this[attribute];\n if (curVal === value) {\n return;\n }\n this[attribute] = value;\n if (this.emitter) {\n this.emitter.trigger('character:attribute:update', attribute);\n // Update any relevant skill mods.\n for (const skill in skillAttributes) {\n if (skillAttributes[skill] === attribute) {\n this.emitter.trigger('character:skill:update', skill, this.getSkillMod(skill));\n }\n }\n }\n }\n /**\n * Get modifier for an attribute.\n * @param {String} attribute Attribute short code\n * @returns {String}\n */\n attributeMod (attribute) {\n const score = this[attribute];\n if (Number.isNaN(score)) {\n return '0';\n }\n const raw = Math.floor((score - 10) / 2);\n return (raw > 0) ? `+${raw}` : raw.toString();\n }\n /**\n * Are they proficient in a skill.\n * @param {String} skill\n * @returns {Boolean}\n */\n isProficient (skill) {\n return this.skills[skill] > skillLevels.UNSKILLED;\n }\n /**\n * Are they expert in a skill.\n * @param {String} skill\n * @returns {Boolean}\n */\n isExpert (skill) {\n return this.skills[skill] === skillLevels.EXPERT;\n }\n /**\n * Get the modifier for a skill.\n * @param {String} skill\n * @returns {String}\n */\n getSkillMod (skill) {\n let raw = 0;\n const skillLevel = this.skills[skill];\n if (typeof skillLevel === 'undefined') {\n return 0;\n }\n const attribute = skillAttributes[skill];\n if (attribute) {\n raw += parseInt(this.attributeMod(attribute), 10);\n }\n const prof = parseInt(this.proficiency, 10);\n if (this.isProficient(skill)) {\n raw += prof;\n }\n if (this.isExpert(skill)) {\n raw += prof;\n }\n return (raw > 0) ? `+${raw}` : raw.toString();\n }\n /**\n * Get skill proficiency\n * @param {String} skill\n * @returns {Number}\n */\n getSkill (skill) {\n const value = this.skills[skill];\n if (typeof value === 'undefined') {\n return null;\n }\n return value;\n }\n /**\n * Set a skill proficiency.\n * @param {String} skill\n * @param {Number} newValue\n */\n setSkill (skill, newValue) {\n const curValue = this.getSkill(skill);\n if (curValue === null || curValue === newValue) {\n return;\n }\n this.skills[skill] = newValue;\n if (this.emitter) {\n this.emitter.trigger('character:skill:update', skill, this.getSkillMod(skill));\n }\n }\n /**\n * Is the attribute save proficient.\n * @param {String} attr\n * @returns {Number}\n */\n isSaveProficient (attr) {\n return (this.saves[attr] || 0);\n }\n /**\n * Get the save modifier for an attribute.\n * @param {String} attr\n * @returns {String}\n */\n saveMod (attr) {\n let profMod = 0;\n if (this.isSaveProficient(attr)) {\n profMod = parseInt(this.proficiency, 10);\n }\n const raw = 0 + profMod + parseInt(this.attributeMod(attr), 10);\n return (raw > 0) ? `+${raw}` : raw.toString();\n }\n /**\n * Set/unset a save proficiency.\n * @param {String} attr\n * @param {Number} checked\n */\n setSaveProficiency (attr, checked) {\n const cur = this.saves[attr];\n if (typeof cur === 'undefined') {\n return;\n }\n if (cur === checked) {\n return;\n }\n this.saves[attr] = (checked ? 1 : 0);\n if (this.emitter) {\n this.emitter.trigger('character:save:update', attr);\n }\n }\n\n /**\n * Returns the spells. Include the level to get by level\n * @param {Number} level\n * @returns {Array}\n */\n getSpells (level = undefined) {\n if (level in this.spells) {\n return this.spells[level];\n }\n\n return this.spells;\n }\n /**\n * Set the spells\n * @param {Object} spell\n * @param {Number} level\n */\n setSpells (spell, level) {\n const spells = this.spells[level];\n\n if (typeof spells === 'undefined') {\n return;\n }\n\n // Temporary\n if (typeof spell === 'object') {\n spell = spell.name;\n }\n\n const newSpellsList = [...spells, spell];\n const newSpellSlotsLength = this.spell_slots[level] + 1;\n\n this.spell_slots[level] = newSpellSlotsLength;\n this.spells[level] = newSpellsList;\n\n if (this.emitter) {\n this.emitter.trigger('character:update:spells');\n this.emitter.trigger('dialog:save:show');\n }\n }\n};\n", "/**\n * Model for Vagabonds of Dyfed character\n */\nimport Character from './Character.js';\n\nexport default class CharacterVagabonds extends Character {\n /**\n * @prop {String} key Unique (in one instance of the app) id for the character. 7 Random letters/numbers.\n * @prop {String} charname Name.\n * @prop {Number} level\n * @prop {String} conflict_approach\n * @prop {String} goal\n * @prop {String} gimmick\n * @prop {String} background\n * @prop {String} foreground\n * @prop {String} weakness\n * @prop {String} core_flaw\n * @prop {String[]} techniques\n * @prop {String[]} traits\n * @prop {Number} hp_cur\n * @prop {Number} hp_max\n * @prop {Number} armor\n * @prop {String} initiative\n * @prop {String[]} lineage\n * @prop {Number} experience\n * @prop {String} appearance\n * @prop {String} personality\n * @prop {String[]} inventory\n * @prop {Number} coins\n * @prop {String[]} injuries\n * @prop {String} notes\n * @prop {CharacterNote[]} notes_adv Adventure notes\n * @prop {CharacterNote[]} notes_cam Campaign notes\n * @prop {CharacterNote[]} npcs NPC notes\n * @prop {CharacterNote[]} factions NPC notes\n * @prop {CharacterNote[]} partymembers Other party members.\n * @prop {String} key_prev If character was imported into app with identical key. This is that key and the character is given a new one on import.\n */\n constructor ({\n key = '',\n charname = '',\n level = 1,\n conflict_approach = '',\n goal = '',\n gimmick = '',\n background = '',\n foreground = '',\n weakness = '',\n core_flaw = '',\n techniques = [],\n traits = [],\n hp_cur = 0,\n hp_max = 0,\n armor = 0,\n initiative = '0',\n lineage = [],\n experience = 0,\n appearance = '',\n personality = '',\n inventory = [],\n coins = 0,\n injuries = [],\n notes = '',\n notes_adv = [],\n notes_cam = [],\n npcs = [],\n factions = [],\n partymembers = [],\n updated = '',\n key_prev = '',\n version = ''\n }) {\n super({\n key,\n charname,\n updated,\n key_prev,\n version\n });\n this.level = level;\n this.conflict_approach = conflict_approach;\n this.goal = goal;\n this.gimmick = gimmick;\n this.background = background;\n this.foreground = foreground;\n this.weakness = weakness;\n this.core_flaw = core_flaw;\n this.techniques = techniques;\n this.traits = traits;\n this.hp_cur = hp_cur;\n this.hp_max = hp_max;\n this.armor = armor;\n this.initiative = initiative;\n this.lineage = lineage;\n this.experience = experience;\n this.appearance = appearance;\n this.personality = personality;\n this.inventory = inventory;\n this.coins = coins;\n this.injuries = injuries;\n this.notes = notes;\n this.notes_adv = this._convertNotes(notes_adv);\n this.notes_cam = this._convertNotes(notes_cam);\n this.npcs = this._convertNotes(npcs);\n this.factions = this._convertNotes(factions);\n this.partymembers = this._convertNotes(partymembers);\n\n this.emitter = null;\n }\n /**\n * Class name (for JSON (de)serialization). Override in children.\n */\n get className () {\n return 'CharacterVagabonds';\n }\n /**\n * Ruleset name. Override in children.\n */\n get ruleset () {\n return 'Vagabonds';\n }\n};\n", "/**\n * LocalStorage interface\n */\nconst Storage = {\n /**\n * A prefix to attack to the random keys to differentiate them from any other storage for the current location/domain\n */\n prefix: '',\n /**\n * Set the prefix\n * @param {String} prefix string to prefix the randomly generated key\n */\n setPrefix: function (prefix) {\n this.prefix = prefix;\n },\n /**\n * Returns blank or the value for the key\n * @param {String} key\n * @return {Object|Null} object or null\n */\n get: function (key) {\n try {\n const txt = localStorage.getItem(`${this.prefix}${key}`);\n return (txt !== null) ? JSON.parse(txt) : null;\n } catch (e) {\n return null;\n }\n },\n /**\n * Store a value for the key\n * Warning: browsers vary for the amount of data you can store (usually ~5mb)\n * @param {String} key\n * @param {Object} object\n * @return {Boolean} returns false on error\n */\n set: function (key, object) {\n try {\n localStorage.setItem(`${this.prefix}${key}`, JSON.stringify(object));\n } catch (e) {\n // Should only happen when over quota\n console.log(e.message);\n return false;\n }\n return true;\n },\n /**\n * Remove a key\n * @param {String} key\n * @return void\n */\n remove: function (key) {\n localStorage.removeItem(`${this.prefix}${key}`);\n },\n /**\n * Get an array of all keys with the key prefix\n * @return {Array}\n */\n getAllKeys: function () {\n const keys = [];\n if (localStorage.length > 0) {\n const key_regex = new RegExp(`^(${this.prefix})+`, 'i');\n for (let i = 0; i < localStorage.length; i++) {\n let key = localStorage.key(i);\n key = key.replace(key_regex, '');\n keys.push(key);\n }\n }\n return keys;\n },\n /**\n * Get all objects from the store.\n * @returns Object[]\n */\n getAll: function () {\n const keys = this.getAllKeys();\n const objects = [];\n keys.forEach((key) => {\n const char_obj = Storage.get(key);\n if (!char_obj || !char_obj.key) {\n return;\n }\n objects.push(char_obj);\n });\n return objects;\n }\n};\n\nexport default Storage;\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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_()\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';\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 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 promiseified 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 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';\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", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 * 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 */\nexport function isBrowser(): boolean {\n return typeof self === 'object' && self.self === self;\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/**\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 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 sychronously 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 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 * Copied from https://stackoverflow.com/a/2117523\n * Generates a new uuid.\n * @public\n */\nexport const uuidv4 = function (): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = (Math.random() * 16) | 0,\n v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\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/**\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 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 mulitple 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 mulitple 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/can not 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", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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", "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", "/**\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 {\n ComponentContainer,\n ComponentType,\n Provider,\n Name\n} from '@firebase/component';\nimport { PlatformLoggerService, VersionService } from './types';\n\nexport class PlatformLoggerServiceImpl implements PlatformLoggerService {\n constructor(private readonly container: ComponentContainer) {}\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString(): string {\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() as VersionService;\n return `${service.library}/${service.version}`;\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: Provider): boolean {\n const component = provider.getComponent();\n return component?.type === ComponentType.VERSION;\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 { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app');\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 { name as appName } from '../package.json';\nimport { name as appCompatName } from '../../app-compat/package.json';\nimport { name as analyticsCompatName } from '../../../packages/analytics-compat/package.json';\nimport { name as analyticsName } from '../../../packages/analytics/package.json';\nimport { name as appCheckCompatName } from '../../../packages/app-check-compat/package.json';\nimport { name as appCheckName } from '../../../packages/app-check/package.json';\nimport { name as authName } from '../../../packages/auth/package.json';\nimport { name as authCompatName } from '../../../packages/auth-compat/package.json';\nimport { name as databaseName } from '../../../packages/database/package.json';\nimport { name as databaseCompatName } from '../../../packages/database-compat/package.json';\nimport { name as functionsName } from '../../../packages/functions/package.json';\nimport { name as functionsCompatName } from '../../../packages/functions-compat/package.json';\nimport { name as installationsName } from '../../../packages/installations/package.json';\nimport { name as installationsCompatName } from '../../../packages/installations-compat/package.json';\nimport { name as messagingName } from '../../../packages/messaging/package.json';\nimport { name as messagingCompatName } from '../../../packages/messaging-compat/package.json';\nimport { name as performanceName } from '../../../packages/performance/package.json';\nimport { name as performanceCompatName } from '../../../packages/performance-compat/package.json';\nimport { name as remoteConfigName } from '../../../packages/remote-config/package.json';\nimport { name as remoteConfigCompatName } from '../../../packages/remote-config-compat/package.json';\nimport { name as storageName } from '../../../packages/storage/package.json';\nimport { name as storageCompatName } from '../../../packages/storage-compat/package.json';\nimport { name as firestoreName } from '../../../packages/firestore/package.json';\nimport { name as vertexName } from '../../../packages/vertexai/package.json';\nimport { name as firestoreCompatName } from '../../../packages/firestore-compat/package.json';\nimport { name as packageName } from '../../../packages/firebase/package.json';\n\n/**\n * The default app name\n *\n * @internal\n */\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\nexport const PLATFORM_LOG_STRING = {\n [appName]: 'fire-core',\n [appCompatName]: 'fire-core-compat',\n [analyticsName]: 'fire-analytics',\n [analyticsCompatName]: 'fire-analytics-compat',\n [appCheckName]: 'fire-app-check',\n [appCheckCompatName]: 'fire-app-check-compat',\n [authName]: 'fire-auth',\n [authCompatName]: 'fire-auth-compat',\n [databaseName]: 'fire-rtdb',\n [databaseCompatName]: 'fire-rtdb-compat',\n [functionsName]: 'fire-fn',\n [functionsCompatName]: 'fire-fn-compat',\n [installationsName]: 'fire-iid',\n [installationsCompatName]: 'fire-iid-compat',\n [messagingName]: 'fire-fcm',\n [messagingCompatName]: 'fire-fcm-compat',\n [performanceName]: 'fire-perf',\n [performanceCompatName]: 'fire-perf-compat',\n [remoteConfigName]: 'fire-rc',\n [remoteConfigCompatName]: 'fire-rc-compat',\n [storageName]: 'fire-gcs',\n [storageCompatName]: 'fire-gcs-compat',\n [firestoreName]: 'fire-fst',\n [firestoreCompatName]: 'fire-fst-compat',\n [vertexName]: 'fire-vertex',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [packageName]: 'fire-js-all'\n} as const;\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 {\n FirebaseApp,\n FirebaseOptions,\n FirebaseServerApp\n} from './public-types';\nimport { Component, Provider, Name } from '@firebase/component';\nimport { logger } from './logger';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { FirebaseServerAppImpl } from './firebaseServerApp';\n\n/**\n * @internal\n */\nexport const _apps = new Map();\n\n/**\n * @internal\n */\nexport const _serverApps = new Map();\n\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _components = new Map>();\n\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nexport function _addComponent(\n app: FirebaseApp,\n component: Component\n): void {\n try {\n (app as FirebaseAppImpl).container.addComponent(component);\n } catch (e) {\n logger.debug(\n `Component ${component.name} failed to register with FirebaseApp ${app.name}`,\n e\n );\n }\n}\n\n/**\n *\n * @internal\n */\nexport function _addOrOverwriteComponent(\n app: FirebaseApp,\n component: Component\n): void {\n (app as FirebaseAppImpl).container.addOrOverwriteComponent(component);\n}\n\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nexport function _registerComponent(\n component: Component\n): boolean {\n const componentName = component.name;\n if (_components.has(componentName)) {\n logger.debug(\n `There were multiple attempts to register component ${componentName}.`\n );\n\n return false;\n }\n\n _components.set(componentName, component);\n\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app as FirebaseAppImpl, component);\n }\n\n for (const serverApp of _serverApps.values()) {\n _addComponent(serverApp as FirebaseServerAppImpl, component);\n }\n\n return true;\n}\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 */\nexport function _getProvider(\n app: FirebaseApp,\n name: T\n): Provider {\n const heartbeatController = (app as FirebaseAppImpl).container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return (app as FirebaseAppImpl).container.getProvider(name);\n}\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 */\nexport function _removeServiceInstance(\n app: FirebaseApp,\n name: T,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n): void {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n\n/**\n *\n * @param obj - an object of type FirebaseApp or FirebaseOptions.\n *\n * @returns true if the provide object is of type FirebaseApp.\n *\n * @internal\n */\nexport function _isFirebaseApp(\n obj: FirebaseApp | FirebaseOptions\n): obj is FirebaseApp {\n return (obj as FirebaseApp).options !== undefined;\n}\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 */\nexport function _isFirebaseServerApp(\n obj: FirebaseApp | FirebaseServerApp\n): obj is FirebaseServerApp {\n return (obj as FirebaseServerApp).settings !== undefined;\n}\n\n/**\n * Test only\n *\n * @internal\n */\nexport function _clearComponents(): void {\n _components.clear();\n}\n\n/**\n * Exported in order to be used in app-compat package\n */\nexport { DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME };\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 { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\n BAD_APP_NAME = 'bad-app-name',\n DUPLICATE_APP = 'duplicate-app',\n APP_DELETED = 'app-deleted',\n SERVER_APP_DELETED = 'server-app-deleted',\n NO_OPTIONS = 'no-options',\n INVALID_APP_ARGUMENT = 'invalid-app-argument',\n INVALID_LOG_ARGUMENT = 'invalid-log-argument',\n IDB_OPEN = 'idb-open',\n IDB_GET = 'idb-get',\n IDB_WRITE = 'idb-set',\n IDB_DELETE = 'idb-delete',\n FINALIZATION_REGISTRY_NOT_SUPPORTED = 'finalization-registry-not-supported',\n INVALID_SERVER_APP_ENVIRONMENT = 'invalid-server-app-environment'\n}\n\nconst ERRORS: ErrorMap = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call initializeApp() first',\n [AppError.BAD_APP_NAME]: \"Illegal App name: '{$appName}'\",\n [AppError.DUPLICATE_APP]:\n \"Firebase App named '{$appName}' already exists with different options or config\",\n [AppError.APP_DELETED]: \"Firebase App named '{$appName}' already deleted\",\n [AppError.SERVER_APP_DELETED]: 'Firebase Server App has been deleted',\n [AppError.NO_OPTIONS]:\n 'Need to provide options, when not being deployed to hosting via source.',\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [AppError.INVALID_LOG_ARGUMENT]:\n 'First argument to `onLog` must be null or a function.',\n [AppError.IDB_OPEN]:\n 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_GET]:\n 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_WRITE]:\n 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_DELETE]:\n 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED]:\n 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\n [AppError.INVALID_SERVER_APP_ENVIRONMENT]:\n 'FirebaseServerApp is not for use in browser environments.'\n};\n\ninterface ErrorParams {\n [AppError.NO_APP]: { appName: string };\n [AppError.BAD_APP_NAME]: { appName: string };\n [AppError.DUPLICATE_APP]: { appName: string };\n [AppError.APP_DELETED]: { appName: string };\n [AppError.INVALID_APP_ARGUMENT]: { appName: string };\n [AppError.IDB_OPEN]: { originalErrorMessage?: string };\n [AppError.IDB_GET]: { originalErrorMessage?: string };\n [AppError.IDB_WRITE]: { originalErrorMessage?: string };\n [AppError.IDB_DELETE]: { originalErrorMessage?: string };\n [AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED]: { appName?: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory(\n 'app',\n 'Firebase',\n 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 */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport {\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { ERROR_FACTORY, AppError } from './errors';\n\nexport class FirebaseAppImpl implements FirebaseApp {\n protected readonly _options: FirebaseOptions;\n protected readonly _name: string;\n /**\n * Original config values passed in as a constructor parameter.\n * It is only used to compare with another config object to support idempotent initializeApp().\n *\n * Updating automaticDataCollectionEnabled on the App instance will not change its value in _config.\n */\n private readonly _config: Required;\n private _automaticDataCollectionEnabled: boolean;\n protected _isDeleted = false;\n private readonly _container: ComponentContainer;\n\n constructor(\n options: FirebaseOptions,\n config: Required,\n container: ComponentContainer\n ) {\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(\n new Component('app', () => this, ComponentType.PUBLIC)\n );\n }\n\n get automaticDataCollectionEnabled(): boolean {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val: boolean) {\n this.checkDestroyed();\n this._automaticDataCollectionEnabled = val;\n }\n\n get name(): string {\n this.checkDestroyed();\n return this._name;\n }\n\n get options(): FirebaseOptions {\n this.checkDestroyed();\n return this._options;\n }\n\n get config(): Required {\n this.checkDestroyed();\n return this._config;\n }\n\n get container(): ComponentContainer {\n return this._container;\n }\n\n get isDeleted(): boolean {\n return this._isDeleted;\n }\n\n set isDeleted(val: boolean) {\n this._isDeleted = val;\n }\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 protected checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.APP_DELETED, { appName: this._name });\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\nimport {\n FirebaseAppSettings,\n FirebaseServerApp,\n FirebaseServerAppSettings,\n FirebaseOptions\n} from './public-types';\nimport { deleteApp, registerVersion } from './api';\nimport { ComponentContainer } from '@firebase/component';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport { name as packageName, version } from '../package.json';\n\nexport class FirebaseServerAppImpl\n extends FirebaseAppImpl\n implements FirebaseServerApp\n{\n private readonly _serverConfig: FirebaseServerAppSettings;\n private _finalizationRegistry: FinalizationRegistry;\n private _refCount: number;\n\n constructor(\n options: FirebaseOptions | FirebaseAppImpl,\n serverConfig: FirebaseServerAppSettings,\n name: string,\n container: ComponentContainer\n ) {\n // Build configuration parameters for the FirebaseAppImpl base class.\n const automaticDataCollectionEnabled =\n serverConfig.automaticDataCollectionEnabled !== undefined\n ? serverConfig.automaticDataCollectionEnabled\n : false;\n\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\n const config: Required = {\n name,\n automaticDataCollectionEnabled\n };\n\n if ((options as FirebaseOptions).apiKey !== undefined) {\n // Construct the parent FirebaseAppImp object.\n super(options as FirebaseOptions, config, container);\n } else {\n const appImpl: FirebaseAppImpl = options as FirebaseAppImpl;\n super(appImpl.options, config, container);\n }\n\n // Now construct the data for the FirebaseServerAppImpl.\n this._serverConfig = {\n automaticDataCollectionEnabled,\n ...serverConfig\n };\n\n this._finalizationRegistry = new FinalizationRegistry(() => {\n this.automaticCleanup();\n });\n\n this._refCount = 0;\n this.incRefCount(this._serverConfig.releaseOnDeref);\n\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegisry\n // will never trigger.\n this._serverConfig.releaseOnDeref = undefined;\n serverConfig.releaseOnDeref = undefined;\n\n registerVersion(packageName, version, 'serverapp');\n }\n\n toJSON(): undefined {\n return undefined;\n }\n\n get refCount(): number {\n return this._refCount;\n }\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: object | undefined): void {\n if (this.isDeleted) {\n return;\n }\n this._refCount++;\n if (obj !== undefined) {\n this._finalizationRegistry.register(obj, this);\n }\n }\n\n // Decrement the reference count.\n decRefCount(): number {\n if (this.isDeleted) {\n return 0;\n }\n return --this._refCount;\n }\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 private automaticCleanup(): void {\n void deleteApp(this);\n }\n\n get settings(): FirebaseServerAppSettings {\n this.checkDestroyed();\n return this._serverConfig;\n }\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 protected checkDestroyed(): void {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(AppError.SERVER_APP_DELETED);\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\nimport {\n FirebaseApp,\n FirebaseServerApp,\n FirebaseOptions,\n FirebaseAppSettings,\n FirebaseServerAppSettings\n} from './public-types';\nimport { DEFAULT_ENTRY_NAME, PLATFORM_LOG_STRING } from './constants';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport {\n ComponentContainer,\n Component,\n Name,\n ComponentType\n} from '@firebase/component';\nimport { version } from '../../firebase/package.json';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { FirebaseServerAppImpl } from './firebaseServerApp';\nimport {\n _apps,\n _components,\n _isFirebaseApp,\n _registerComponent,\n _serverApps\n} from './internal';\nimport { logger } from './logger';\nimport {\n LogLevelString,\n setLogLevel as setLogLevelImpl,\n LogCallback,\n LogOptions,\n setUserLogHandler\n} from '@firebase/logger';\nimport { deepEqual, getDefaultAppConfig, isBrowser } from '@firebase/util';\n\nexport { FirebaseError } from '@firebase/util';\n\n/**\n * The current SDK version.\n *\n * @public\n */\nexport const SDK_VERSION = version;\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseApp} instance.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize default app\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * });\n * ```\n *\n * @example\n * ```javascript\n *\n * // Initialize another app\n * const otherApp = initializeApp({\n * databaseURL: \"https://.firebaseio.com\",\n * storageBucket: \".appspot.com\"\n * }, \"otherApp\");\n * ```\n *\n * @param options - Options to configure the app's services.\n * @param name - Optional name of the app to initialize. If no name\n * is provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The initialized app.\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n name?: string\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @param options - Options to configure the app's services.\n * @param config - FirebaseApp Configuration\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n config?: FirebaseAppSettings\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @public\n */\nexport function initializeApp(): FirebaseApp;\nexport function initializeApp(\n _options?: FirebaseOptions,\n rawConfig = {}\n): FirebaseApp {\n let options = _options;\n\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n\n const config: Required = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: false,\n ...rawConfig\n };\n const name = config.name;\n\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(AppError.BAD_APP_NAME, {\n appName: String(name)\n });\n }\n\n options ||= getDefaultAppConfig();\n\n if (!options) {\n throw ERROR_FACTORY.create(AppError.NO_OPTIONS);\n }\n\n const existingApp = _apps.get(name) as FirebaseAppImpl;\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (\n deepEqual(options, existingApp.options) &&\n deepEqual(config, existingApp.config)\n ) {\n return existingApp;\n } else {\n throw ERROR_FACTORY.create(AppError.DUPLICATE_APP, { appName: name });\n }\n }\n\n const container = new ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseAppImpl(options, config, container);\n\n _apps.set(name, newApp);\n\n return newApp;\n}\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseServerApp} instance.\n *\n * The `FirebaseServerApp` is similar to `FirebaseApp`, but is intended for execution in\n * server side rendering environments only. Initialization will fail if invoked from a\n * browser environment.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize an instance of `FirebaseServerApp`.\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeServerApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * },\n * {\n * authIdToken: \"Your Auth ID Token\"\n * });\n * ```\n *\n * @param options - `Firebase.AppOptions` to configure the app's services, or a\n * a `FirebaseApp` instance which contains the `AppOptions` within.\n * @param config - `FirebaseServerApp` configuration.\n *\n * @returns The initialized `FirebaseServerApp`.\n *\n * @public\n */\nexport function initializeServerApp(\n options: FirebaseOptions | FirebaseApp,\n config: FirebaseServerAppSettings\n): FirebaseServerApp;\n\nexport function initializeServerApp(\n _options: FirebaseOptions | FirebaseApp,\n _serverAppConfig: FirebaseServerAppSettings\n): FirebaseServerApp {\n if (isBrowser()) {\n // FirebaseServerApp isn't designed to be run in browsers.\n throw ERROR_FACTORY.create(AppError.INVALID_SERVER_APP_ENVIRONMENT);\n }\n\n if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {\n _serverAppConfig.automaticDataCollectionEnabled = false;\n }\n\n let appOptions: FirebaseOptions;\n if (_isFirebaseApp(_options)) {\n appOptions = _options.options;\n } else {\n appOptions = _options;\n }\n\n // Build an app name based on a hash of the configuration options.\n const nameObj = {\n ..._serverAppConfig,\n ...appOptions\n };\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\n const hashCode = (s: string): number => {\n return [...s].reduce(\n (hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0,\n 0\n );\n };\n\n if (_serverAppConfig.releaseOnDeref !== undefined) {\n if (typeof FinalizationRegistry === 'undefined') {\n throw ERROR_FACTORY.create(\n AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED,\n {}\n );\n }\n }\n\n const nameString = '' + hashCode(JSON.stringify(nameObj));\n const existingApp = _serverApps.get(nameString) as FirebaseServerApp;\n if (existingApp) {\n (existingApp as FirebaseServerAppImpl).incRefCount(\n _serverAppConfig.releaseOnDeref\n );\n return existingApp;\n }\n\n const container = new ComponentContainer(nameString);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseServerAppImpl(\n appOptions,\n _serverAppConfig,\n nameString,\n container\n );\n\n _serverApps.set(nameString, newApp);\n\n return newApp;\n}\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 */\nexport function getApp(name: string = DEFAULT_ENTRY_NAME): FirebaseApp {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n\n return app;\n}\n\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nexport function getApps(): FirebaseApp[] {\n return Array.from(_apps.values());\n}\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 */\nexport async function deleteApp(app: FirebaseApp): Promise {\n let cleanupProviders = false;\n const name = app.name;\n if (_apps.has(name)) {\n cleanupProviders = true;\n _apps.delete(name);\n } else if (_serverApps.has(name)) {\n const firebaseServerApp = app as FirebaseServerAppImpl;\n if (firebaseServerApp.decRefCount() <= 0) {\n _serverApps.delete(name);\n cleanupProviders = true;\n }\n }\n\n if (cleanupProviders) {\n await Promise.all(\n (app as FirebaseAppImpl).container\n .getProviders()\n .map(provider => provider.delete())\n );\n (app as FirebaseAppImpl).isDeleted = true;\n }\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 */\nexport function registerVersion(\n libraryKeyOrName: string,\n version: string,\n variant?: string\n): void {\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(\n `library name \"${library}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(\n `version name \"${version}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n logger.warn(warning.join(' '));\n return;\n }\n _registerComponent(\n new Component(\n `${library}-version` as Name,\n () => ({ library, version }),\n ComponentType.VERSION\n )\n );\n}\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 */\nexport function onLog(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(AppError.INVALID_LOG_ARGUMENT);\n }\n setUserLogHandler(logCallback, options);\n}\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 */\nexport function setLogLevel(logLevel: LogLevelString): void {\n setLogLevelImpl(logLevel);\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 { FirebaseError } from '@firebase/util';\nimport { DBSchema, openDB, IDBPDatabase } from 'idb';\nimport { AppError, ERROR_FACTORY } from './errors';\nimport { FirebaseApp } from './public-types';\nimport { HeartbeatsInIndexedDB } from './types';\nimport { logger } from './logger';\n\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\n\ninterface AppDB extends DBSchema {\n 'firebase-heartbeat-store': {\n key: string;\n value: HeartbeatsInIndexedDB;\n };\n}\n\nlet dbPromise: Promise> | null = null;\nfunction getDbPromise(): Promise> {\n if (!dbPromise) {\n dbPromise = 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 } 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(AppError.IDB_OPEN, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\n\nexport async function readHeartbeatsFromIndexedDB(\n app: FirebaseApp\n): Promise {\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 } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_GET, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nexport async function writeHeartbeatsToIndexedDB(\n app: FirebaseApp,\n heartbeatObject: HeartbeatsInIndexedDB\n): Promise {\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 } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_WRITE, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.name}!${app.options.appId}`;\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 { ComponentContainer } from '@firebase/component';\nimport {\n base64urlEncodeWithoutPadding,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport {\n readHeartbeatsFromIndexedDB,\n writeHeartbeatsToIndexedDB\n} from './indexeddb';\nimport { FirebaseApp } from './public-types';\nimport {\n HeartbeatsByUserAgent,\n HeartbeatService,\n HeartbeatsInIndexedDB,\n HeartbeatStorage,\n SingleDateHeartbeat\n} from './types';\n\nconst MAX_HEADER_BYTES = 1024;\n// 30 days\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\n\nexport class HeartbeatServiceImpl implements HeartbeatService {\n /**\n * The persistence layer for heartbeats\n * Leave public for easier testing.\n */\n _storage: HeartbeatStorageImpl;\n\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 _heartbeatsCache: HeartbeatsInIndexedDB | null = null;\n\n /**\n * the initialization promise for populating heartbeatCache.\n * If getHeartbeatsHeader() is called before the promise resolves\n * (hearbeatsCache == null), it should wait for this promise\n * Leave public for easier testing.\n */\n _heartbeatsCachePromise: Promise;\n constructor(private readonly container: ComponentContainer) {\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 /**\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(): Promise {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n\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 (\n this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(\n singleDateHeartbeat => singleDateHeartbeat.date === date\n )\n ) {\n return;\n } else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n }\n // Remove entries older than 30 days.\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(\n singleDateHeartbeat => {\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\n const now = Date.now();\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\n }\n );\n return this._storage.overwrite(this._heartbeatsCache);\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(): Promise {\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 (\n this._heartbeatsCache?.heartbeats == null ||\n this._heartbeatsCache.heartbeats.length === 0\n ) {\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(\n this._heartbeatsCache.heartbeats\n );\n const headerString = base64urlEncodeWithoutPadding(\n JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })\n );\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 } 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}\n\nfunction getUTCDateString(): string {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\n\nexport function extractHeartbeatsForHeader(\n heartbeatsCache: SingleDateHeartbeat[],\n maxSize = MAX_HEADER_BYTES\n): {\n heartbeatsToSend: HeartbeatsByUserAgent[];\n unsentEntries: SingleDateHeartbeat[];\n} {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend: HeartbeatsByUserAgent[] = [];\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(\n hb => hb.agent === singleDateHeartbeat.agent\n );\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 } 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}\n\nexport class HeartbeatStorageImpl implements HeartbeatStorage {\n private _canUseIndexedDBPromise: Promise;\n constructor(public app: FirebaseApp) {\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck(): Promise {\n if (!isIndexedDBAvailable()) {\n return false;\n } else {\n return validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read(): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n } else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n if (idbHeartbeatObject?.heartbeats) {\n return idbHeartbeatObject;\n } else {\n return { heartbeats: [] };\n }\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject: HeartbeatsInIndexedDB): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject: HeartbeatsInIndexedDB): Promise {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\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 */\nexport function countBytes(heartbeatsCache: HeartbeatsByUserAgent[]): number {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })\n ).length;\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 { Component, ComponentType } from '@firebase/component';\nimport { PlatformLoggerServiceImpl } from './platformLoggerService';\nimport { name, version } from '../package.json';\nimport { _registerComponent } from './internal';\nimport { registerVersion } from './api';\nimport { HeartbeatServiceImpl } from './heartbeatService';\n\nexport function registerCoreComponents(variant?: string): void {\n _registerComponent(\n new Component(\n 'platform-logger',\n container => new PlatformLoggerServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n _registerComponent(\n new Component(\n 'heartbeat',\n container => new HeartbeatServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n\n // Register `app` package.\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n", "/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\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\nimport { registerCoreComponents } from './registerCoreComponents';\n\nexport * from './api';\nexport * from './internal';\nexport * from './public-types';\n\nregisterCoreComponents('__RUNTIME_ENV__');\n", "/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n(function() {'use strict';var h;/** @license\n\n Copyright The Closure Library Authors.\n SPDX-License-Identifier: Apache-2.0\n*/\nfunction k(f,a){function c(){}c.prototype=a.prototype;f.D=a.prototype;f.prototype=new c;f.prototype.constructor=f;f.C=function(d,e,g){for(var b=Array(arguments.length-2),r=2;re;++e)d[e]=a.charCodeAt(c++)|a.charCodeAt(c++)<<8|a.charCodeAt(c++)<<16|a.charCodeAt(c++)<<24;else for(e=0;16>e;++e)d[e]=a[c++]|a[c++]<<8|a[c++]<<16|a[c++]<<24;a=f.g[0];c=f.g[1];e=f.g[2];var g=f.g[3];var b=a+(g^c&(e^g))+d[0]+3614090360&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[1]+3905402710&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[2]+606105819&4294967295;e=g+(b<<17&4294967295|b>>>15);\nb=c+(a^e&(g^a))+d[3]+3250441966&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[4]+4118548399&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[5]+1200080426&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[6]+2821735955&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[7]+4249261313&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[8]+1770035416&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[9]+2336552879&4294967295;g=a+(b<<12&4294967295|\nb>>>20);b=e+(c^g&(a^c))+d[10]+4294925233&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[11]+2304563134&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[12]+1804603682&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[13]+4254626195&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[14]+2792965006&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[15]+1236535329&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(e^g&(c^e))+d[1]+4129170786&4294967295;a=c+(b<<\n5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[6]+3225465664&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[11]+643717713&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[0]+3921069994&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[5]+3593408605&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[10]+38016083&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[15]+3634488961&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[4]+3889429448&4294967295;c=\ne+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[9]+568446438&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[14]+3275163606&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[3]+4107603335&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[8]+1163531501&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[13]+2850285829&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[2]+4243563512&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[7]+1735328473&4294967295;\ne=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[12]+2368359562&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(c^e^g)+d[5]+4294588738&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[8]+2272392833&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[11]+1839030562&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[14]+4259657740&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[1]+2763975236&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[4]+1272893353&4294967295;g=a+(b<<11&4294967295|\nb>>>21);b=e+(g^a^c)+d[7]+4139469664&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[10]+3200236656&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[13]+681279174&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[0]+3936430074&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[3]+3572445317&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[6]+76029189&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[9]+3654602809&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[12]+\n3873151461&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[15]+530742520&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[2]+3299628645&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(e^(c|~g))+d[0]+4096336452&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[7]+1126891415&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[14]+2878612391&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[5]+4237533241&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[12]+1700485571&\n4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[3]+2399980690&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[10]+4293915773&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[1]+2240044497&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[8]+1873313359&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[15]+4264355552&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[6]+2734768916&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[13]+1309151649&\n4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[4]+4149444226&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[11]+3174756917&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[2]+718787259&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[9]+3951481745&4294967295;f.g[0]=f.g[0]+a&4294967295;f.g[1]=f.g[1]+(e+(b<<21&4294967295|b>>>11))&4294967295;f.g[2]=f.g[2]+e&4294967295;f.g[3]=f.g[3]+g&4294967295}\nm.prototype.u=function(f,a){void 0===a&&(a=f.length);for(var c=a-this.blockSize,d=this.B,e=this.h,g=0;gthis.h?this.blockSize:2*this.blockSize)-this.h);f[0]=128;for(var a=1;aa;++a)for(var d=0;32>d;d+=8)f[c++]=this.g[a]>>>d&255;return f};function p(f,a){var c=q;return Object.prototype.hasOwnProperty.call(c,f)?c[f]:c[f]=a(f)};function t(f,a){this.h=a;for(var c=[],d=!0,e=f.length-1;0<=e;e--){var g=f[e]|0;d&&g==a||(c[e]=g,d=!1)}this.g=c}var q={};function u(f){return-128<=f&&128>f?p(f,function(a){return new t([a|0],0>a?-1:0)}):new t([f|0],0>f?-1:0)}function v(f){if(isNaN(f)||!isFinite(f))return w;if(0>f)return x(v(-f));for(var a=[],c=1,d=0;f>=c;d++)a[d]=f/c|0,c*=4294967296;return new t(a,0)}\nfunction y(f,a){if(0==f.length)throw Error(\"number format error: empty string\");a=a||10;if(2>a||36g?(g=v(Math.pow(a,g)),d=d.j(g).add(v(b))):(d=d.j(c),d=d.add(v(b)))}return d}var w=u(0),z=u(1),A=u(16777216);h=t.prototype;\nh.m=function(){if(B(this))return-x(this).m();for(var f=0,a=1,c=0;cf||36>>0).toString(f);c=e;if(C(c))return g+d;for(;6>g.length;)g=\"0\"+g;d=g+d}};\nh.i=function(f){return 0>f?0:f>>16)+(this.i(e)>>>16)+(f.i(e)>>>16);d=b>>>16;g&=65535;b&=65535;c[e]=b<<16|g}return new t(c,c[c.length-1]&-2147483648?-1:0)};function F(f,a){return f.add(x(a))}\nh.j=function(f){if(C(this)||C(f))return w;if(B(this))return B(f)?x(this).j(x(f)):x(x(this).j(f));if(B(f))return x(this.j(x(f)));if(0>this.l(A)&&0>f.l(A))return v(this.m()*f.m());for(var a=this.g.length+f.g.length,c=[],d=0;d<2*a;d++)c[d]=0;for(d=0;d>>16,b=this.i(d)&65535,r=f.i(e)>>>16,E=f.i(e)&65535;c[2*d+2*e]+=b*E;G(c,2*d+2*e);c[2*d+2*e+1]+=g*E;G(c,2*d+2*e+1);c[2*d+2*e+1]+=b*r;G(c,2*d+2*e+1);c[2*d+2*e+2]+=g*r;G(c,2*d+2*e+2)}for(d=0;d<\na;d++)c[d]=c[2*d+1]<<16|c[2*d];for(d=a;d<2*a;d++)c[d]=0;return new t(c,0)};function G(f,a){for(;(f[a]&65535)!=f[a];)f[a+1]+=f[a]>>>16,f[a]&=65535,a++}function H(f,a){this.g=f;this.h=a}\nfunction D(f,a){if(C(a))throw Error(\"division by zero\");if(C(f))return new H(w,w);if(B(f))return a=D(x(f),a),new H(x(a.g),x(a.h));if(B(a))return a=D(f,x(a)),new H(x(a.g),a.h);if(30=d.l(f);)c=I(c),d=I(d);var e=J(c,1),g=J(d,1);d=J(d,2);for(c=J(c,2);!C(d);){var b=g.add(d);0>=b.l(f)&&(e=e.add(c),g=b);d=J(d,1);c=J(c,1)}a=F(f,e.j(a));return new H(e,a)}for(e=w;0<=f.l(a);){c=Math.max(1,Math.floor(f.m()/\na.m()));d=Math.ceil(Math.log(c)/Math.LN2);d=48>=d?1:Math.pow(2,d-48);g=v(c);for(b=g.j(a);B(b)||0>>31;return new t(c,f.h)}function J(f,a){var c=a>>5;a%=32;for(var d=f.g.length-c,e=[],g=0;g>>a|f.i(g+c+1)<<32-a:f.i(g+c);return new t(e,f.h)};m.prototype.digest=m.prototype.v;m.prototype.reset=m.prototype.s;m.prototype.update=m.prototype.u;module.exports.Md5=m;t.prototype.add=t.prototype.add;t.prototype.multiply=t.prototype.j;t.prototype.modulo=t.prototype.A;t.prototype.compare=t.prototype.l;t.prototype.toNumber=t.prototype.m;t.prototype.toString=t.prototype.toString;t.prototype.getBits=t.prototype.i;t.fromNumber=v;t.fromString=y;module.exports.Integer=t;}).apply( typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {});\n", "/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n(function() {'use strict';var h,aa=\"function\"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};function ba(a){a=[\"object\"==typeof globalThis&&globalThis,a,\"object\"==typeof window&&window,\"object\"==typeof self&&self,\"object\"==typeof global&&global];for(var b=0;b{throw a;},0)};function xa(){var a=za;let b=null;a.g&&(b=a.g,a.g=a.g.next,a.g||(a.h=null),b.next=null);return b}class Aa{constructor(){this.h=this.g=null}add(a,b){const c=Ba.get();c.set(a,b);this.h?this.h.next=c:this.g=c;this.h=c}}var Ba=new na(()=>new Ca,a=>a.reset());class Ca{constructor(){this.next=this.g=this.h=null}set(a,b){this.h=a;this.g=b;this.next=null}reset(){this.next=this.g=this.h=null}};let x,y=!1,za=new Aa,Ea=()=>{const a=k.Promise.resolve(void 0);x=()=>{a.then(Da)}};var Da=()=>{for(var a;a=xa();){try{a.h.call(a.g)}catch(c){wa(c)}var b=Ba;b.j(a);100>b.h&&(b.h++,a.next=b.g,b.g=a)}y=!1};function z(){this.s=this.s;this.C=this.C}z.prototype.s=!1;z.prototype.ma=function(){this.s||(this.s=!0,this.N())};z.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function A(a,b){this.type=a;this.g=this.target=b;this.defaultPrevented=!1}A.prototype.h=function(){this.defaultPrevented=!0};var Fa=function(){if(!k.addEventListener||!Object.defineProperty)return!1;var a=!1,b=Object.defineProperty({},\"passive\",{get:function(){a=!0}});try{const c=()=>{};k.addEventListener(\"test\",c,b);k.removeEventListener(\"test\",c,b)}catch(c){}return a}();function C(a,b){A.call(this,a?a.type:\"\");this.relatedTarget=this.g=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=0;this.key=\"\";this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.pointerId=0;this.pointerType=\"\";this.i=null;if(a){var c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.g=b;if(b=a.relatedTarget){if(pa){a:{try{oa(b.nodeName);var e=!0;break a}catch(f){}e=\n!1}e||(b=null)}}else\"mouseover\"==c?b=a.fromElement:\"mouseout\"==c&&(b=a.toElement);this.relatedTarget=b;d?(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.clientX=void 0!==a.clientX?a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.key=a.key||\"\";this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=\na.shiftKey;this.metaKey=a.metaKey;this.pointerId=a.pointerId||0;this.pointerType=\"string\"===typeof a.pointerType?a.pointerType:Ga[a.pointerType]||\"\";this.state=a.state;this.i=a;a.defaultPrevented&&C.aa.h.call(this)}}r(C,A);var Ga={2:\"touch\",3:\"pen\",4:\"mouse\"};C.prototype.h=function(){C.aa.h.call(this);var a=this.i;a.preventDefault?a.preventDefault():a.returnValue=!1};var D=\"closure_listenable_\"+(1E6*Math.random()|0);var Ha=0;function Ia(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.ha=e;this.key=++Ha;this.da=this.fa=!1}function Ja(a){a.da=!0;a.listener=null;a.proxy=null;a.src=null;a.ha=null};function Ka(a){this.src=a;this.g={};this.h=0}Ka.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.g[f];a||(a=this.g[f]=[],this.h++);var g=La(a,b,d,e);-1>>0);function Sa(a){if(\"function\"===typeof a)return a;a[$a]||(a[$a]=function(b){return a.handleEvent(b)});return a[$a]};function E(){z.call(this);this.i=new Ka(this);this.M=this;this.F=null}r(E,z);E.prototype[D]=!0;E.prototype.removeEventListener=function(a,b,c,d){Ya(this,a,b,c,d)};\nfunction F(a,b){var c,d=a.F;if(d)for(c=[];d;d=d.F)c.push(d);a=a.M;d=b.type||b;if(\"string\"===typeof b)b=new A(b,a);else if(b instanceof A)b.target=b.target||a;else{var e=b;b=new A(d,a);ua(b,e)}e=!0;if(c)for(var f=c.length-1;0<=f;f--){var g=b.g=c[f];e=ab(g,d,!0,b)&&e}g=b.g=a;e=ab(g,d,!0,b)&&e;e=ab(g,d,!1,b)&&e;if(c)for(f=0;f{a.g=null;a.i&&(a.i=!1,cb(a))},a.l);const b=a.h;a.h=null;a.m.apply(null,b)}class eb extends z{constructor(a,b){super();this.m=a;this.l=b;this.h=null;this.i=!1;this.g=null}j(a){this.h=arguments;this.g?this.i=!0:cb(this)}N(){super.N();this.g&&(k.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}};function G(a){z.call(this);this.h=a;this.g={}}r(G,z);var fb=[];function gb(a){qa(a.g,function(b,c){this.g.hasOwnProperty(c)&&Za(b)},a);a.g={}}G.prototype.N=function(){G.aa.N.call(this);gb(this)};G.prototype.handleEvent=function(){throw Error(\"EventHandler.handleEvent not implemented\");};var hb=k.JSON.stringify;var ib=k.JSON.parse;var jb=class{stringify(a){return k.JSON.stringify(a,void 0)}parse(a){return k.JSON.parse(a,void 0)}};function kb(){}kb.prototype.h=null;function lb(a){return a.h||(a.h=a.i())};function mb(){}var H={OPEN:\"a\",kb:\"b\",Ja:\"c\",wb:\"d\"};function nb(){A.call(this,\"d\")}r(nb,A);function ob(){A.call(this,\"c\")}r(ob,A);var I={},pb=null;function qb(){return pb=pb||new E}I.La=\"serverreachability\";function rb(a){A.call(this,I.La,a)}r(rb,A);function J(a){const b=qb();F(b,new rb(b,a))}I.STAT_EVENT=\"statevent\";function sb(a,b){A.call(this,I.STAT_EVENT,a);this.stat=b}r(sb,A);function K(a){const b=qb();F(b,new sb(b,a))}I.Ma=\"timingevent\";function tb(a,b){A.call(this,I.Ma,a);this.size=b}r(tb,A);\nfunction ub(a,b){if(\"function\"!==typeof a)throw Error(\"Fn must not be null and must be a function\");return k.setTimeout(function(){a()},b)};function vb(){this.g=!0}vb.prototype.xa=function(){this.g=!1};function wb(a,b,c,d,e,f){a.info(function(){if(a.g)if(f){var g=\"\";for(var m=f.split(\"&\"),q=0;qd.length)){var e=d[1];if(Array.isArray(e)&&!(1>e.length)){var f=e[0];if(\"noop\"!=f&&\"stop\"!=f&&\"close\"!=f)for(var g=1;gw)&&(3!=w||this.g&&(this.h.h||this.g.oa()||Nb(this.g)))){this.J||4!=w||7==b||(8==b||0>=O?J(3):J(2));Ob(this);var c=this.g.Z();this.X=c;b:if(Pb(this)){var d=Nb(this.g);a=\"\";var e=d.length,f=4==P(this.g);if(!this.h.i){if(\"undefined\"===typeof TextDecoder){Q(this);Qb(this);var g=\"\";break b}this.h.i=new k.TextDecoder}for(b=0;bb.length)return Gb;b=b.slice(d,d+c);a.C=d+c;return b}M.prototype.cancel=function(){this.J=!0;Q(this)};function Kb(a){a.S=Date.now()+a.I;Wb(a,a.I)}function Wb(a,b){if(null!=a.B)throw Error(\"WatchDog timer not null\");a.B=ub(p(a.ba,a),b)}function Ob(a){a.B&&(k.clearTimeout(a.B),a.B=null)}\nM.prototype.ba=function(){this.B=null;const a=Date.now();0<=a-this.S?(zb(this.i,this.A),2!=this.L&&(J(3),K(17)),Q(this),this.s=2,Qb(this)):Wb(this,this.S-a)};function Qb(a){0==a.j.G||a.J||Ub(a.j,a)}function Q(a){Ob(a);var b=a.M;b&&\"function\"==typeof b.ma&&b.ma();a.M=null;gb(a.U);a.g&&(b=a.g,a.g=null,b.abort(),b.ma())}\nfunction Rb(a,b){try{var c=a.j;if(0!=c.G&&(c.g==a||Xb(c.h,a)))if(!a.K&&Xb(c.h,a)&&3==c.G){try{var d=c.Da.g.parse(b)}catch(l){d=null}if(Array.isArray(d)&&3==d.length){var e=d;if(0==e[0])a:{if(!c.u){if(c.g)if(c.g.F+3E3e[2]&&c.F&&0==c.v&&!c.C&&(c.C=ub(p(c.Za,c),6E3));if(1>=ac(c.h)&&c.ca){try{c.ca()}catch(l){}c.ca=void 0}}else R(c,11)}else if((a.K||c.g==a)&&Yb(c),!t(b))for(e=c.Da.g.parse(b),b=0;b=a.j:!1}function ac(a){return a.h?1:a.g?a.g.size:0}function Xb(a,b){return a.h?a.h==b:a.g?a.g.has(b):!1}\nfunction bc(a,b){a.g?a.g.add(b):a.h=b}function dc(a,b){a.h&&a.h==b?a.h=null:a.g&&a.g.has(b)&&a.g.delete(b)}ic.prototype.cancel=function(){this.i=kc(this);if(this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const a of this.g.values())a.cancel();this.g.clear()}};function kc(a){if(null!=a.h)return a.i.concat(a.h.D);if(null!=a.g&&0!==a.g.size){let b=a.i;for(const c of a.g.values())b=b.concat(c.D);return b}return la(a.i)};function lc(a){if(a.V&&\"function\"==typeof a.V)return a.V();if(\"undefined\"!==typeof Map&&a instanceof Map||\"undefined\"!==typeof Set&&a instanceof Set)return Array.from(a.values());if(\"string\"===typeof a)return a.split(\"\");if(ha(a)){for(var b=[],c=a.length,d=0;db)throw Error(\"Bad port number \"+b);a.s=b}else a.s=null}function tc(a,b,c){b instanceof sc?(a.i=b,Ac(a.i,a.h)):(c||(b=vc(b,Bc)),a.i=new sc(b,a.h))}function S(a,b,c){a.i.set(b,c)}function Ib(a){S(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36));return a}\nfunction uc(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}function vc(a,b,c){return\"string\"===typeof a?(a=encodeURI(a).replace(b,Cc),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Cc(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var wc=/[#\\/\\?@]/g,yc=/[#\\?:]/g,xc=/[#\\?]/g,Bc=/[#\\?@]/g,zc=/#/g;function sc(a,b){this.h=this.g=null;this.i=a||null;this.j=!!b}\nfunction U(a){a.g||(a.g=new Map,a.h=0,a.i&&pc(a.i,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}h=sc.prototype;h.add=function(a,b){U(this);this.i=null;a=V(this,a);var c=this.g.get(a);c||this.g.set(a,c=[]);c.push(b);this.h+=1;return this};function Dc(a,b){U(a);b=V(a,b);a.g.has(b)&&(a.i=null,a.h-=a.g.get(b).length,a.g.delete(b))}function Ec(a,b){U(a);b=V(a,b);return a.g.has(b)}\nh.forEach=function(a,b){U(this);this.g.forEach(function(c,d){c.forEach(function(e){a.call(b,e,d,this)},this)},this)};h.na=function(){U(this);const a=Array.from(this.g.values()),b=Array.from(this.g.keys()),c=[];for(let d=0;d{d.abort();W(c,\"TestPingServer: timeout\",!1,b)},1E4);fetch(a,{signal:d.signal}).then(f=>{clearTimeout(e);f.ok?W(c,\"TestPingServer: ok\",!0,b):W(c,\"TestPingServer: server error\",!1,b)}).catch(()=>{clearTimeout(e);W(c,\"TestPingServer: error\",!1,b)})}function W(a,b,c,d,e){try{e&&(e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null),d(c)}catch(f){}};function Hc(){this.g=new jb}function Ic(a,b,c){const d=c||\"\";try{nc(a,function(e,f){let g=e;n(e)&&(g=hb(e));b.push(d+f+\"=\"+encodeURIComponent(g))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function Jc(a){this.l=a.Ub||null;this.j=a.eb||!1}r(Jc,kb);Jc.prototype.g=function(){return new Kc(this.l,this.j)};Jc.prototype.i=function(a){return function(){return a}}({});function Kc(a,b){E.call(this);this.D=a;this.o=b;this.m=void 0;this.status=this.readyState=0;this.responseType=this.responseText=this.response=this.statusText=\"\";this.onreadystatechange=null;this.u=new Headers;this.h=null;this.B=\"GET\";this.A=\"\";this.g=!1;this.v=this.j=this.l=null}r(Kc,E);h=Kc.prototype;\nh.open=function(a,b){if(0!=this.readyState)throw this.abort(),Error(\"Error reopening a connection\");this.B=a;this.A=b;this.readyState=1;Lc(this)};h.send=function(a){if(1!=this.readyState)throw this.abort(),Error(\"need to call open() first. \");this.g=!0;const b={headers:this.u,method:this.B,credentials:this.m,cache:void 0};a&&(b.body=a);(this.D||k).fetch(new Request(this.A,b)).then(this.Sa.bind(this),this.ga.bind(this))};\nh.abort=function(){this.response=this.responseText=\"\";this.u=new Headers;this.status=0;this.j&&this.j.cancel(\"Request was aborted.\").catch(()=>{});1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Mc(this));this.readyState=0};\nh.Sa=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,Lc(this)),this.g&&(this.readyState=3,Lc(this),this.g)))if(\"arraybuffer\"===this.responseType)a.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(\"undefined\"!==typeof k.ReadableStream&&\"body\"in a){this.j=a.body.getReader();if(this.o){if(this.responseType)throw Error('responseType must be empty for \"streamBinaryChunks\" mode responses.');this.response=\n[]}else this.response=this.responseText=\"\",this.v=new TextDecoder;Nc(this)}else a.text().then(this.Ra.bind(this),this.ga.bind(this))};function Nc(a){a.j.read().then(a.Pa.bind(a)).catch(a.ga.bind(a))}h.Pa=function(a){if(this.g){if(this.o&&a.value)this.response.push(a.value);else if(!this.o){var b=a.value?a.value:new Uint8Array(0);if(b=this.v.decode(b,{stream:!a.done}))this.response=this.responseText+=b}a.done?Mc(this):Lc(this);3==this.readyState&&Nc(this)}};\nh.Ra=function(a){this.g&&(this.response=this.responseText=a,Mc(this))};h.Qa=function(a){this.g&&(this.response=a,Mc(this))};h.ga=function(){this.g&&Mc(this)};function Mc(a){a.readyState=4;a.l=null;a.j=null;a.v=null;Lc(a)}h.setRequestHeader=function(a,b){this.u.append(a,b)};h.getResponseHeader=function(a){return this.h?this.h.get(a.toLowerCase())||\"\":\"\"};\nh.getAllResponseHeaders=function(){if(!this.h)return\"\";const a=[],b=this.h.entries();for(var c=b.next();!c.done;)c=c.value,a.push(c[0]+\": \"+c[1]),c=b.next();return a.join(\"\\r\\n\")};function Lc(a){a.onreadystatechange&&a.onreadystatechange.call(a)}Object.defineProperty(Kc.prototype,\"withCredentials\",{get:function(){return\"include\"===this.m},set:function(a){this.m=a?\"include\":\"same-origin\"}});function Oc(a){let b=\"\";qa(a,function(c,d){b+=d;b+=\":\";b+=c;b+=\"\\r\\n\"});return b}function Pc(a,b,c){a:{for(d in c){var d=!1;break a}d=!0}d||(c=Oc(c),\"string\"===typeof a?(encodeURIComponent(String(b)),null!=c&&encodeURIComponent(String(c))):S(a,b,c))};function X(a){E.call(this);this.headers=new Map;this.o=a||null;this.h=!1;this.v=this.g=null;this.D=\"\";this.m=0;this.l=\"\";this.j=this.B=this.u=this.A=!1;this.I=null;this.H=\"\";this.J=!1}r(X,E);var Qc=/^https?$/i,Rc=[\"POST\",\"PUT\"];h=X.prototype;h.Ha=function(a){this.J=a};\nh.ea=function(a,b,c,d){if(this.g)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.D+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.D=a;this.l=\"\";this.m=0;this.A=!1;this.h=!0;this.g=this.o?this.o.g():Cb.g();this.v=this.o?lb(this.o):lb(Cb);this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(b,String(a),!0),this.B=!1}catch(f){Sc(this,f);return}a=c||\"\";c=new Map(this.headers);if(d)if(Object.getPrototypeOf(d)===Object.prototype)for(var e in d)c.set(e,d[e]);else if(\"function\"===\ntypeof d.keys&&\"function\"===typeof d.get)for(const f of d.keys())c.set(f,d.get(f));else throw Error(\"Unknown input type for opt_headers: \"+String(d));d=Array.from(c.keys()).find(f=>\"content-type\"==f.toLowerCase());e=k.FormData&&a instanceof k.FormData;!(0<=Array.prototype.indexOf.call(Rc,b,void 0))||d||e||c.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");for(const [f,g]of c)this.g.setRequestHeader(f,g);this.H&&(this.g.responseType=this.H);\"withCredentials\"in this.g&&this.g.withCredentials!==\nthis.J&&(this.g.withCredentials=this.J);try{Tc(this),this.u=!0,this.g.send(a),this.u=!1}catch(f){Sc(this,f)}};function Sc(a,b){a.h=!1;a.g&&(a.j=!0,a.g.abort(),a.j=!1);a.l=b;a.m=5;Uc(a);Vc(a)}function Uc(a){a.A||(a.A=!0,F(a,\"complete\"),F(a,\"error\"))}h.abort=function(a){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=a||7,F(this,\"complete\"),F(this,\"abort\"),Vc(this))};h.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Vc(this,!0));X.aa.N.call(this)};\nh.Ea=function(){this.s||(this.B||this.u||this.j?Wc(this):this.bb())};h.bb=function(){Wc(this)};\nfunction Wc(a){if(a.h&&\"undefined\"!=typeof fa&&(!a.v[1]||4!=P(a)||2!=a.Z()))if(a.u&&4==P(a))bb(a.Ea,0,a);else if(F(a,\"readystatechange\"),4==P(a)){a.h=!1;try{const g=a.Z();a:switch(g){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var b=!0;break a;default:b=!1}var c;if(!(c=b)){var d;if(d=0===g){var e=String(a.D).match(oc)[1]||null;!e&&k.self&&k.self.location&&(e=k.self.location.protocol.slice(0,-1));d=!Qc.test(e?e.toLowerCase():\"\")}c=d}if(c)F(a,\"complete\"),F(a,\"success\");else{a.m=\n6;try{var f=2{}:null;a.g=null;a.v=null;b||F(a,\"ready\");try{c.onreadystatechange=d}catch(e){}}}function Tc(a){a.I&&(k.clearTimeout(a.I),a.I=null)}h.isActive=function(){return!!this.g};function P(a){return a.g?a.g.readyState:0}h.Z=function(){try{return 2=a.h.j-(a.s?1:0))return!1;if(a.s)return a.i=b.D.concat(a.i),!0;if(1==a.G||2==a.G||a.B>=(a.Va?0:a.Wa))return!1;a.s=ub(p(a.Ga,a,b),cd(a,a.B));a.B++;return!0}\nh.Ga=function(a){if(this.s)if(this.s=null,1==this.G){if(!a){this.U=Math.floor(1E5*Math.random());a=this.U++;const e=new M(this,this.j,a);let f=this.o;this.S&&(f?(f=sa(f),ua(f,this.S)):f=this.S);null!==this.m||this.O||(e.H=f,f=null);if(this.P)a:{var b=0;for(var c=0;cl)f=Math.max(0,e[q].g-100),m=!1;else try{Ic(v,g,\"req\"+l+\"_\")}catch(w){d&&d(v)}}if(m){d=g.join(\"&\");break a}}}a=a.i.splice(0,c);b.D=a;return d}function ec(a){if(!a.g&&!a.u){a.Y=1;var b=a.Fa;x||Ea();y||(x(),y=!0);za.add(b,a);a.v=0}}\nfunction $b(a){if(a.g||a.u||3<=a.v)return!1;a.Y++;a.u=ub(p(a.Fa,a),cd(a,a.v));a.v++;return!0}h.Fa=function(){this.u=null;fd(this);if(this.ba&&!(this.M||null==this.g||0>=this.R)){var a=2*this.R;this.j.info(\"BP detection timer enabled: \"+a);this.A=ub(p(this.ab,this),a)}};h.ab=function(){this.A&&(this.A=null,this.j.info(\"BP detection timeout reached.\"),this.j.info(\"Buffering proxy detected and switch to long-polling!\"),this.F=!1,this.M=!0,K(10),Zb(this),fd(this))};\nfunction Tb(a){null!=a.A&&(k.clearTimeout(a.A),a.A=null)}function fd(a){a.g=new M(a,a.j,\"rpc\",a.Y);null===a.m&&(a.g.H=a.o);a.g.O=0;var b=N(a.qa);S(b,\"RID\",\"rpc\");S(b,\"SID\",a.K);S(b,\"AID\",a.T);S(b,\"CI\",a.F?\"0\":\"1\");!a.F&&a.ja&&S(b,\"TO\",a.ja);S(b,\"TYPE\",\"xmlhttp\");$c(a,b);a.m&&a.o&&Pc(b,a.m,a.o);a.L&&(a.g.I=a.L);var c=a.g;a=a.ia;c.L=1;c.v=Ib(N(b));c.m=null;c.P=!0;Jb(c,a)}h.Za=function(){null!=this.C&&(this.C=null,Zb(this),$b(this),K(19))};function Yb(a){null!=a.C&&(k.clearTimeout(a.C),a.C=null)}\nfunction Ub(a,b){var c=null;if(a.g==b){Yb(a);Tb(a);a.g=null;var d=2}else if(Xb(a.h,b))c=b.D,dc(a.h,b),d=1;else return;if(0!=a.G)if(b.o)if(1==d){c=b.m?b.m.length:0;b=Date.now()-b.F;var e=a.B;d=qb();F(d,new tb(d,c,b,e));fc(a)}else ec(a);else if(e=b.s,3==e||0==e&&0\n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n * \n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\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/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure: string = 'Unexpected state'): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message =\n `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */\nexport function hardAssert(\n assertion: boolean,\n message?: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj 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 { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.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\nexport interface Resolver {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener!: () => void;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth) {\n this.auth.removeAuthTokenListener(this.tokenListener!);\n }\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener!: AppCheckTokenListener;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n\n constructor(\n private appCheckProvider: Provider\n ) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n this.appCheck.addTokenListener(this.tokenListener);\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck) {\n this.appCheck.removeTokenListener(this.tokenListener!);\n }\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n\n constructor(\n private appCheckProvider: Provider\n ) {\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\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 { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable {\n isEqual(other: T): boolean;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\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 */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n /** Returns a JSON-serializable representation of this `Timestamp`. */\n toJSON(): { seconds: number; nanoseconds: number } {\n return { seconds: this.seconds, nanoseconds: this.nanoseconds };\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n static comparator>(\n p1: BasePath,\n p2: BasePath\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const left = p1.get(i);\n const right = p2.get(i);\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n }\n if (p1.length < p2.length) {\n return -1;\n }\n if (p1.length > p2.length) {\n return 1;\n }\n return 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and traling slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { primitiveComparator } from '../util/misc';\n\nimport { Document } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldPath } from './path';\n\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_LARGEST_BATCH_ID = -1;\n\n/**\n * The initial sequence number for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_SEQUENCE_NUMBER = 0;\n\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nexport class FieldIndex {\n /** An ID for an index that has not yet been added to persistence. */\n static UNKNOWN_ID = -1;\n\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n readonly indexId: number,\n /** The collection ID this index applies to. */\n readonly collectionGroup: string,\n /** The field segments for this index. */\n readonly fields: IndexSegment[],\n /** Shows how up-to-date the index is for the current user. */\n readonly indexState: IndexState\n ) {}\n}\n\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nexport function fieldIndexGetArraySegment(\n fieldIndex: FieldIndex\n): IndexSegment | undefined {\n return fieldIndex.fields.find(s => s.kind === IndexKind.CONTAINS);\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */\nexport function fieldIndexGetDirectionalSegments(\n fieldIndex: FieldIndex\n): IndexSegment[] {\n return fieldIndex.fields.filter(s => s.kind !== IndexKind.CONTAINS);\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\nexport function fieldIndexGetKeyOrder(fieldIndex: FieldIndex): IndexKind {\n const directionalSegments = fieldIndexGetDirectionalSegments(fieldIndex);\n return directionalSegments.length === 0\n ? IndexKind.ASCENDING\n : directionalSegments[directionalSegments.length - 1].kind;\n}\n\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nexport function fieldIndexSemanticComparator(\n left: FieldIndex,\n right: FieldIndex\n): number {\n let cmp = primitiveComparator(left.collectionGroup, right.collectionGroup);\n if (cmp !== 0) {\n return cmp;\n }\n\n for (let i = 0; i < Math.min(left.fields.length, right.fields.length); ++i) {\n cmp = indexSegmentComparator(left.fields[i], right.fields[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return primitiveComparator(left.fields.length, right.fields.length);\n}\n\n/** Returns a debug representation of the field index */\nexport function fieldIndexToString(fieldIndex: FieldIndex): string {\n return `id=${fieldIndex.indexId}|cg=${\n fieldIndex.collectionGroup\n }|f=${fieldIndex.fields.map(f => `${f.fieldPath}:${f.kind}`).join(',')}`;\n}\n\n/** The type of the index, e.g. for which type of query it can be used. */\nexport const enum IndexKind {\n // Note: The order of these values cannot be changed as the enum values are\n // stored in IndexedDb.\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n ASCENDING,\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n DESCENDING,\n /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */\n CONTAINS\n}\n\n/** An index component consisting of field path and index type. */\nexport class IndexSegment {\n constructor(\n /** The field path of the component. */\n readonly fieldPath: FieldPath,\n /** The fields sorting order. */\n readonly kind: IndexKind\n ) {}\n}\n\nfunction indexSegmentComparator(\n left: IndexSegment,\n right: IndexSegment\n): number {\n const cmp = FieldPath.comparator(left.fieldPath, right.fieldPath);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.kind, right.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */\nexport class IndexState {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n readonly sequenceNumber: number,\n /** The the latest indexed read time, document and batch id. */\n readonly offset: IndexOffset\n ) {}\n\n /** The state of an index that has not yet been backfilled. */\n static empty(): IndexState {\n return new IndexState(INITIAL_SEQUENCE_NUMBER, IndexOffset.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */\nexport function newIndexOffsetSuccessorFromReadTime(\n readTime: SnapshotVersion,\n largestBatchId: number\n): IndexOffset {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const successorSeconds = readTime.toTimestamp().seconds;\n const successorNanos = readTime.toTimestamp().nanoseconds + 1;\n const successor = SnapshotVersion.fromTimestamp(\n successorNanos === 1e9\n ? new Timestamp(successorSeconds + 1, 0)\n : new Timestamp(successorSeconds, successorNanos)\n );\n return new IndexOffset(successor, DocumentKey.empty(), largestBatchId);\n}\n\n/** Creates a new offset based on the provided document. */\nexport function newIndexOffsetFromDocument(document: Document): IndexOffset {\n return new IndexOffset(\n document.readTime,\n document.key,\n INITIAL_LARGEST_BATCH_ID\n );\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */\nexport class IndexOffset {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n readonly readTime: SnapshotVersion,\n\n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n readonly documentKey: DocumentKey,\n\n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n readonly largestBatchId: number\n ) {}\n\n /** Returns an offset that sorts before all regular offsets. */\n static min(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.min(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n\n /** Returns an offset that sorts after all regular offsets. */\n static max(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.max(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n}\n\nexport function indexOffsetComparator(\n left: IndexOffset,\n right: IndexOffset\n): number {\n let cmp = left.readTime.compareTo(right.readTime);\n if (cmp !== 0) {\n return cmp;\n }\n cmp = DocumentKey.comparator(left.documentKey, right.documentKey);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.largestBatchId, right.largestBatchId);\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 { ListenSequenceNumber } from '../core/types';\nexport const PRIMARY_LEASE_LOST_ERROR_MSG =\n 'The current tab is not in the required state to perform this operation. ' +\n 'It might be necessary to refresh the browser tab.';\n\n/** The different modes supported by `Persistence.runTransaction()`. */\nexport type PersistenceTransactionMode =\n | 'readonly'\n | 'readwrite'\n | 'readwrite-primary';\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */\nexport abstract class PersistenceTransaction {\n private readonly onCommittedListeners: Array<() => void> = [];\n\n abstract readonly currentSequenceNumber: ListenSequenceNumber;\n\n addOnCommittedListener(listener: () => void): void {\n this.onCommittedListeners.push(listener);\n }\n\n raiseOnCommittedEvent(): void {\n this.onCommittedListeners.forEach(listener => listener());\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { IndexManager } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { PRIMARY_LEASE_LOST_ERROR_MSG } from './persistence_transaction';\n\nexport interface LocalStore {\n collectGarbage(garbageCollector: LruGarbageCollector): Promise;\n\n /** Manages the list of active field and collection indices. */\n indexManager: IndexManager;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments: LocalDocumentsView;\n}\n\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */\nexport async function ignoreIfPrimaryLeaseLoss(\n err: FirestoreError\n): Promise {\n if (\n err.code === Code.FAILED_PRECONDITION &&\n err.message === PRIMARY_LEASE_LOST_ERROR_MSG\n ) {\n logDebug('LocalStore', 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\n\nexport type FulfilledHandler =\n | ((result: T) => R | PersistencePromise)\n | null;\nexport type RejectedHandler =\n | ((reason: Error) => R | PersistencePromise)\n | null;\nexport type Resolver = (value?: T) => void;\nexport type Rejector = (error: Error) => void;\n\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */\nexport class PersistencePromise {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n private nextCallback: FulfilledHandler = null;\n private catchCallback: RejectedHandler = null;\n\n // When the operation resolves, we'll set result or error and mark isDone.\n private result: T | undefined = undefined;\n private error: Error | undefined = undefined;\n private isDone = false;\n\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n private callbackAttached = false;\n\n constructor(callback: (resolve: Resolver, reject: Rejector) => void) {\n callback(\n value => {\n this.isDone = true;\n this.result = value;\n if (this.nextCallback) {\n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(value!);\n }\n },\n error => {\n this.isDone = true;\n this.error = error;\n if (this.catchCallback) {\n this.catchCallback(error);\n }\n }\n );\n }\n\n catch(\n fn: (error: Error) => R | PersistencePromise\n ): PersistencePromise {\n return this.next(undefined, fn);\n }\n\n next(\n nextFn?: FulfilledHandler,\n catchFn?: RejectedHandler\n ): PersistencePromise {\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result!);\n } else {\n return this.wrapFailure(catchFn, this.error);\n }\n } else {\n return new PersistencePromise((resolve, reject) => {\n this.nextCallback = (value: T) => {\n this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n this.catchCallback = (error: Error) => {\n this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n }\n\n toPromise(): Promise {\n return new Promise((resolve, reject) => {\n this.next(resolve, reject);\n });\n }\n\n private wrapUserFunction(\n fn: () => R | PersistencePromise\n ): PersistencePromise {\n try {\n const result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n } else {\n return PersistencePromise.resolve(result);\n }\n } catch (e) {\n return PersistencePromise.reject(e as Error);\n }\n }\n\n private wrapSuccess(\n nextFn: FulfilledHandler | undefined,\n value: T\n ): PersistencePromise {\n if (nextFn) {\n return this.wrapUserFunction(() => nextFn(value));\n } else {\n // If there's no nextFn, then R must be the same as T\n return PersistencePromise.resolve(value as unknown as R);\n }\n }\n\n private wrapFailure(\n catchFn: RejectedHandler | undefined,\n error: Error\n ): PersistencePromise {\n if (catchFn) {\n return this.wrapUserFunction(() => catchFn(error));\n } else {\n return PersistencePromise.reject(error);\n }\n }\n\n static resolve(): PersistencePromise;\n static resolve(result: R): PersistencePromise;\n static resolve(result?: R): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n resolve(result);\n });\n }\n\n static reject(error: Error): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n reject(error);\n });\n }\n\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n all: { forEach: (cb: (el: PersistencePromise) => void) => void }\n ): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n let expectedCount = 0;\n let resolvedCount = 0;\n let done = false;\n\n all.forEach(element => {\n ++expectedCount;\n element.next(\n () => {\n ++resolvedCount;\n if (done && resolvedCount === expectedCount) {\n resolve();\n }\n },\n err => reject(err)\n );\n });\n\n done = true;\n if (resolvedCount === expectedCount) {\n resolve();\n }\n });\n }\n\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */\n static or(\n predicates: Array<() => PersistencePromise>\n ): PersistencePromise {\n let p: PersistencePromise =\n PersistencePromise.resolve(false);\n for (const predicate of predicates) {\n p = p.next(isTrue => {\n if (isTrue) {\n return PersistencePromise.resolve(isTrue);\n } else {\n return predicate();\n }\n });\n }\n return p;\n }\n\n /**\n * Given an iterable, call the given function on each element in the\n * collection and wait for all of the resulting concurrent PersistencePromises\n * to resolve.\n */\n static forEach(\n collection: { forEach: (cb: (r: R, s: S) => void) => void },\n f:\n | ((r: R, s: S) => PersistencePromise)\n | ((r: R) => PersistencePromise)\n ): PersistencePromise;\n static forEach(\n collection: { forEach: (cb: (r: R) => void) => void },\n f: (r: R) => PersistencePromise\n ): PersistencePromise;\n static forEach(\n collection: { forEach: (cb: (r: R, s?: S) => void) => void },\n f: (r: R, s?: S) => PersistencePromise\n ): PersistencePromise {\n const promises: Array> = [];\n collection.forEach((r, s) => {\n promises.push(f.call(this, r, s));\n });\n return this.waitFor(promises);\n }\n\n /**\n * Concurrently map all array elements through asynchronous function.\n */\n static mapArray(\n array: T[],\n f: (t: T) => PersistencePromise\n ): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n const expectedCount = array.length;\n const results: U[] = new Array(expectedCount);\n let resolvedCount = 0;\n for (let i = 0; i < expectedCount; i++) {\n const current = i;\n f(array[current]).next(\n result => {\n results[current] = result;\n ++resolvedCount;\n if (resolvedCount === expectedCount) {\n resolve(results);\n }\n },\n err => reject(err)\n );\n }\n });\n }\n\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */\n static doWhile(\n condition: () => boolean,\n action: () => PersistencePromise\n ): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n const process = (): void => {\n if (condition() === true) {\n action().next(() => {\n process();\n }, reject);\n } else {\n resolve();\n }\n };\n process();\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 { getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise {\n logDebug(LOG_TAG, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for userse running version < 4.5.\n const androidVersion = getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndxedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise\n ): PersistencePromise {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback\n ): PersistencePromise {\n const results: Array> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\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 */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n private task: DelayedOperation | null;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly backfiller: IndexBackfiller\n ) {\n this.task = null;\n }\n\n start(): void {\n debugAssert(\n this.task === null,\n 'Cannot start an already started IndexBackfillerScheduler'\n );\n this.schedule(INITIAL_BACKFILL_DELAY_MS);\n }\n\n stop(): void {\n if (this.task) {\n this.task.cancel();\n this.task = null;\n }\n }\n\n get started(): boolean {\n return this.task !== null;\n }\n\n private schedule(delay: number): void {\n debugAssert(\n this.task === null,\n 'Cannot schedule IndexBackfiller while a task is pending'\n );\n logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n this.task = this.asyncQueue.enqueueAfterDelay(\n TimerId.IndexBackfill,\n delay,\n async () => {\n this.task = null;\n try {\n const documentsProcessed = await this.backfiller.backfill();\n logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during index backfill: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n }\n );\n }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n private readonly localStore: LocalStore,\n private readonly persistence: Persistence\n ) {}\n\n async backfill(\n maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n ): Promise {\n return this.persistence.runTransaction(\n 'Backfill Indexes',\n 'readwrite-primary',\n txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n );\n }\n\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n private writeIndexEntries(\n transation: PersistenceTransaction,\n maxDocumentsToProcess: number\n ): PersistencePromise {\n const processedCollectionGroups = new Set();\n let documentsRemaining = maxDocumentsToProcess;\n let continueLoop = true;\n return PersistencePromise.doWhile(\n () => continueLoop === true && documentsRemaining > 0,\n () => {\n return this.localStore.indexManager\n .getNextCollectionGroupToUpdate(transation)\n .next((collectionGroup: string | null) => {\n if (\n collectionGroup === null ||\n processedCollectionGroups.has(collectionGroup)\n ) {\n continueLoop = false;\n } else {\n logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`);\n return this.writeEntriesForCollectionGroup(\n transation,\n collectionGroup,\n documentsRemaining\n ).next(documentsProcessed => {\n documentsRemaining -= documentsProcessed;\n processedCollectionGroups.add(collectionGroup);\n });\n }\n });\n }\n ).next(() => maxDocumentsToProcess - documentsRemaining);\n }\n\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */\n private writeEntriesForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n documentsRemainingUnderCap: number\n ): PersistencePromise {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager\n .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n .next(existingOffset =>\n this.localStore.localDocuments\n .getNextDocuments(\n transaction,\n collectionGroup,\n existingOffset,\n documentsRemainingUnderCap\n )\n .next(nextBatch => {\n const docs: DocumentMap = nextBatch.changes;\n return this.localStore.indexManager\n .updateIndexEntries(transaction, docs)\n .next(() => this.getNewOffset(existingOffset, nextBatch))\n .next(newOffset => {\n logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n return this.localStore.indexManager.updateCollectionGroup(\n transaction,\n collectionGroup,\n newOffset\n );\n })\n .next(() => docs.size);\n })\n );\n }\n\n /** Returns the next offset based on the provided documents. */\n private getNewOffset(\n existingOffset: IndexOffset,\n lookupResult: LocalWriteResult\n ): IndexOffset {\n let maxOffset: IndexOffset = existingOffset;\n lookupResult.changes.forEach((key, document) => {\n const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n maxOffset = newOffset;\n }\n });\n return new IndexOffset(\n maxOffset.readTime,\n maxOffset.documentKey,\n Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n );\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): 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 { ResourcePath } from '../model/path';\nimport { fail, hardAssert } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encodeResourcePath(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decodeResourcePath(path: EncodedResourcePath): ResourcePath {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const length = path.length;\n hardAssert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n hardAssert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 'Non-empty path ' + path + ' had length 2'\n );\n return ResourcePath.emptyPath();\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\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 { BatchId, TargetId } from '../core/types';\nimport { ResourcePath } from '../model/path';\nimport { fail } from '../util/assert';\n\nimport {\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { DbDocumentMutation } from './indexeddb_schema';\nimport { DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy } from './indexeddb_schema_legacy';\n\n// This file contains static constants and helper functions for IndexedDB.\n// It is split from indexeddb_schema to allow for minification.\n\n/** A timestamp type that can be used in IndexedDb keys. */\nexport type DbTimestampKey = [/* seconds */ number, /* nanos */ number];\n\n// The key for the singleton object in the DbPrimaryClient is a single string.\nexport type DbPrimaryClientKey = typeof DbPrimaryClientKey;\n\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\nexport const DbPrimaryClientStore = 'owner';\n\n/**\n * The key string used for the single object that exists in the\n * DbPrimaryClient store.\n */\n\nexport const DbPrimaryClientKey = 'owner';\n\n/** Object keys in the 'mutationQueues' store are userId strings. */\nexport type DbMutationQueueKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationQueueStore = 'mutationQueues';\n\n/** Keys are automatically assigned via the userId property. */\nexport const DbMutationQueueKeyPath = 'userId';\n\n/** The 'mutations' store is keyed by batch ID. */\nexport type DbMutationBatchKey = BatchId;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationBatchStore = 'mutations';\n\n/** Keys are automatically assigned via the userId, batchId properties. */\nexport const DbMutationBatchKeyPath = 'batchId';\n\n/** The index name for lookup of mutations by user. */\n\nexport const DbMutationBatchUserMutationsIndex = 'userMutationsIndex';\n\n/** The user mutations index is keyed by [userId, batchId] pairs. */\nexport const DbMutationBatchUserMutationsKeyPath = ['userId', 'batchId'];\n\n/**\n * The key for a db document mutation, which is made up of a userID, path, and\n * batchId. Note that the path must be serialized into a form that indexedDB can\n * sort.\n */\nexport type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId];\n\n/**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\nexport function newDbDocumentMutationPrefixForUser(userId: string): [string] {\n return [userId];\n}\n\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nexport function newDbDocumentMutationPrefixForPath(\n userId: string,\n path: ResourcePath\n): [string, EncodedResourcePath] {\n return [userId, encodeResourcePath(path)];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\nexport function newDbDocumentMutationKey(\n userId: string,\n path: ResourcePath,\n batchId: BatchId\n): DbDocumentMutationKey {\n return [userId, encodeResourcePath(path), batchId];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */\nexport const DbDocumentMutationPlaceholder: DbDocumentMutation = {};\n\nexport const DbDocumentMutationStore = 'documentMutations';\n\nexport const DbRemoteDocumentStore = 'remoteDocumentsV14';\n\n/**\n * A key in the 'remoteDocumentsV14' object store is an array containing the\n * collection path, the collection group, the read time and the document id.\n */\nexport type DbRemoteDocumentKey = [\n /** path to collection */ string[],\n /** collection group */ string,\n /** read time */ DbTimestampKey,\n /** document ID */ string\n];\n\n/**\n * The primary key of the remote documents store, which allows for efficient\n * access by collection path and read time.\n */\nexport const DbRemoteDocumentKeyPath = [\n 'prefixPath',\n 'collectionGroup',\n 'readTime',\n 'documentId'\n];\n\n/** An index that provides access to documents by key. */\nexport const DbRemoteDocumentDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbRemoteDocumentDocumentKeyIndexPath = [\n 'prefixPath',\n 'collectionGroup',\n 'documentId'\n];\n\n/**\n * An index that provides access to documents by collection group and read\n * time.\n *\n * This index is used by the index backfiller.\n */\nexport const DbRemoteDocumentCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbRemoteDocumentCollectionGroupIndexPath = [\n 'collectionGroup',\n 'readTime',\n 'prefixPath',\n 'documentId'\n];\n\nexport const DbRemoteDocumentGlobalStore = 'remoteDocumentGlobal';\n\nexport const DbRemoteDocumentGlobalKey = 'remoteDocumentGlobalKey';\n\nexport type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobalKey;\n\n/**\n * A key in the 'targets' object store is a targetId of the query.\n */\nexport type DbTargetKey = TargetId;\n\nexport const DbTargetStore = 'targets';\n\n/** Keys are automatically assigned via the targetId property. */\nexport const DbTargetKeyPath = 'targetId';\n\n/** The name of the queryTargets index. */\nexport const DbTargetQueryTargetsIndexName = 'queryTargetsIndex';\n\n/**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\nexport const DbTargetQueryTargetsKeyPath = ['canonicalId', 'targetId'];\n\n/**\n * The key for a DbTargetDocument, containing a targetId and an encoded resource\n * path.\n */\nexport type DbTargetDocumentKey = [TargetId, EncodedResourcePath];\n\n/** Name of the IndexedDb object store. */\nexport const DbTargetDocumentStore = 'targetDocuments';\n\n/** Keys are automatically assigned via the targetId, path properties. */\nexport const DbTargetDocumentKeyPath = ['targetId', 'path'];\n\n/** The index name for the reverse index. */\nexport const DbTargetDocumentDocumentTargetsIndex = 'documentTargetsIndex';\n\n/** We also need to create the reverse index for these properties. */\nexport const DbTargetDocumentDocumentTargetsKeyPath = ['path', 'targetId'];\n\n/**\n * The type to represent the single allowed key for the DbTargetGlobal store.\n */\nexport type DbTargetGlobalKey = typeof DbTargetGlobalKey;\n/**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\nexport const DbTargetGlobalKey = 'targetGlobalKey';\n\nexport const DbTargetGlobalStore = 'targetGlobal';\n\n/**\n * The key for a DbCollectionParent entry, containing the collection ID\n * and the parent path that contains it. Note that the parent path will be an\n * empty path in the case of root-level collections.\n */\nexport type DbCollectionParentKey = [string, EncodedResourcePath];\n\n/** Name of the IndexedDb object store. */\nexport const DbCollectionParentStore = 'collectionParents';\n\n/** Keys are automatically assigned via the collectionId, parent properties. */\nexport const DbCollectionParentKeyPath = ['collectionId', 'parent'];\n\n/** Name of the IndexedDb object store. */\nexport const DbClientMetadataStore = 'clientMetadata';\n\n/** Keys are automatically assigned via the clientId properties. */\nexport const DbClientMetadataKeyPath = 'clientId';\n\n/** Object keys in the 'clientMetadata' store are clientId strings. */\nexport type DbClientMetadataKey = string;\n\nexport type DbBundlesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbBundleStore = 'bundles';\n\nexport const DbBundleKeyPath = 'bundleId';\n\nexport type DbNamedQueriesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbNamedQueryStore = 'namedQueries';\n\nexport const DbNamedQueryKeyPath = 'name';\n\n/** The key for each index consisting of just the index id. */\nexport type DbIndexConfigurationKey = number;\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexConfigurationStore = 'indexConfiguration';\n\nexport const DbIndexConfigurationKeyPath = 'indexId';\n\n/**\n * An index that provides access to the index configurations by collection\n * group.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexConfigurationCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbIndexConfigurationCollectionGroupIndexPath = 'collectionGroup';\n\n/** The key for each index state consisting of the index id and its user id. */\nexport type DbIndexStateKey = [number, string];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexStateStore = 'indexState';\n\nexport const DbIndexStateKeyPath = ['indexId', 'uid'];\n\n/**\n * An index that provides access to documents in a collection sorted by last\n * update time. Used by the backfiller.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexStateSequenceNumberIndex = 'sequenceNumberIndex';\n\nexport const DbIndexStateSequenceNumberIndexPath = ['uid', 'sequenceNumber'];\n\n/**\n * The key for each index entry consists of the index id and its user id,\n * the encoded array and directional value for the indexed fields as well as\n * an ordered and an encoded document path for the indexed document.\n */\nexport type DbIndexEntryKey = [\n number,\n string,\n Uint8Array,\n Uint8Array,\n Uint8Array,\n string[]\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexEntryStore = 'indexEntries';\n\nexport const DbIndexEntryKeyPath = [\n 'indexId',\n 'uid',\n 'arrayValue',\n 'directionalValue',\n 'orderedDocumentKey',\n 'documentKey'\n];\n\nexport const DbIndexEntryDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbIndexEntryDocumentKeyIndexPath = [\n 'indexId',\n 'uid',\n 'orderedDocumentKey'\n];\n\nexport type DbDocumentOverlayKey = [\n /* userId */ string,\n /* collectionPath */ string,\n /* documentId */ string\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbDocumentOverlayStore = 'documentOverlays';\n\nexport const DbDocumentOverlayKeyPath = [\n 'userId',\n 'collectionPath',\n 'documentId'\n];\n\nexport const DbDocumentOverlayCollectionPathOverlayIndex =\n 'collectionPathOverlayIndex';\n\nexport const DbDocumentOverlayCollectionPathOverlayIndexPath = [\n 'userId',\n 'collectionPath',\n 'largestBatchId'\n];\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndex =\n 'collectionGroupOverlayIndex';\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndexPath = [\n 'userId',\n 'collectionGroup',\n 'largestBatchId'\n];\n\n// Visible for testing\nexport const V1_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStoreLegacy,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore\n];\n\n// Visible for testing\nexport const V3_STORES = V1_STORES;\n// Note: DbRemoteDocumentChanges is no longer used and dropped with v9.\nexport const V4_STORES = [...V3_STORES, DbClientMetadataStore];\nexport const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobalStore];\nexport const V8_STORES = [...V6_STORES, DbCollectionParentStore];\nexport const V11_STORES = [...V8_STORES, DbBundleStore, DbNamedQueryStore];\nexport const V12_STORES = [...V11_STORES, DbDocumentOverlayStore];\nexport const V13_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStore,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore,\n DbClientMetadataStore,\n DbRemoteDocumentGlobalStore,\n DbCollectionParentStore,\n DbBundleStore,\n DbNamedQueryStore,\n DbDocumentOverlayStore\n];\nexport const V14_STORES = V13_STORES;\nexport const V15_STORES = [\n ...V14_STORES,\n DbIndexConfigurationStore,\n DbIndexStateStore,\n DbIndexEntryStore\n];\nexport const V16_STORES = V15_STORES;\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 16) {\n return V16_STORES;\n } else if (schemaVersion === 15) {\n return V15_STORES;\n } else if (schemaVersion === 14) {\n return V14_STORES;\n } else if (schemaVersion === 13) {\n return V13_STORES;\n } else if (schemaVersion === 12) {\n return V12_STORES;\n } else if (schemaVersion === 11) {\n return V11_STORES;\n } else {\n fail('Only schema version 11 and 12 and 13 are supported');\n }\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 { Document as ProtoDocument } from '../protos/firestore_proto_api';\n\nimport { DbNoDocument, DbUnknownDocument } from './indexeddb_schema';\nimport { DbTimestampKey } from './indexeddb_sentinels';\n\n// This file contains older schema definitions for object stores that were\n// migrated to newer schema versions. These object stores should only be used\n// during schema migrations.\n\nexport interface DbRemoteDocument {\n unknownDocument?: DbUnknownDocument;\n noDocument?: DbNoDocument;\n document?: ProtoDocument;\n hasCommittedMutations?: boolean;\n readTime?: DbTimestampKey;\n parentPath?: string[];\n}\n\nexport type DbRemoteDocumentKey = string[];\nexport const DbRemoteDocumentStore = 'remoteDocuments';\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 { ListenSequenceNumber } from '../core/types';\nimport { debugCast } from '../util/assert';\n\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\nexport function getStore(\n txn: PersistenceTransaction,\n store: string\n): SimpleDbStore {\n const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n return SimpleDb.getStore(\n indexedDbTransaction.simpleDbTransaction,\n store\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach(\n obj: Dict | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty(obj: Dict): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\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\nimport { debugAssert, fail } from './assert';\n\n/*\n * 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\nexport type Comparator = (key1: K, key2: K) => number;\n\nexport interface Entry {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\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 // Returns a copy of the map, with the specified key removed.\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 // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const 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 // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\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. 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 inorderTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && 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,\n // 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\n // 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(): Entry {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const 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 } 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(): Entry | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\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 isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. 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 inorderTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. 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 reverseTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\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 // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\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 private removeMin(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\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 // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = 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 LLRBNode.EMPTY;\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 isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\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 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 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 private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\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 // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode {\n get key(): never {\n throw fail('LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail('LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail('LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail('LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail('LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\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 // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet): SortedSet {\n let result: SortedSet = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets(\n before: SortedSet,\n after: SortedSet,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator(it: SortedSetIterator): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\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 { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\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/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\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 { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\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 { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\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 { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 'invalid timestamp: ' + date);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\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 { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n", "import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\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 { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { arrayEquals, primitiveComparator } from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail('Unexpected value type: ' + JSON.stringify(left));\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return primitiveComparator(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail('Invalid value type: ' + leftType);\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n return { mapValue: {} };\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return { mapValue: {} };\n } else if ('mapValue' in value) {\n return MAX_VALUE;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 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 */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be sycned or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\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 { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown FieldFilter operator: ' + this.op);\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail('Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return other !== null && !arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\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\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== 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 { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet {\n let result = new SortedSet(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + orderBy.dir);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { forEach, isEmpty } from './obj';\n\ntype Entry = [K, V];\n\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nexport class ObjectMap {\n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n private inner: {\n [canonicalId: string]: Array>;\n } = {};\n\n /** The number of entries stored in the map */\n private innerSize = 0;\n\n constructor(\n private mapKeyFn: (key: KeyType) => string,\n private equalsFn: (l: KeyType, r: KeyType) => boolean\n ) {}\n\n /** Get a value for this key, or undefined if it does not exist. */\n get(key: KeyType): ValueType | undefined {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (const [otherKey, value] of matches) {\n if (this.equalsFn(otherKey, key)) {\n return value;\n }\n }\n return undefined;\n }\n\n has(key: KeyType): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Put this key and value in the map. */\n set(key: KeyType, value: ValueType): void {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n this.innerSize++;\n return;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n // This is updating an existing entry and does not increase `innerSize`.\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n this.innerSize++;\n }\n\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n delete(key: KeyType): boolean {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n } else {\n matches.splice(i, 1);\n }\n this.innerSize--;\n return true;\n }\n }\n return false;\n }\n\n forEach(fn: (key: KeyType, val: ValueType) => void): void {\n forEach(this.inner, (_, entries) => {\n for (const [k, v] of entries) {\n fn(k, v);\n }\n });\n }\n\n isEmpty(): boolean {\n return isEmpty(this.inner);\n }\n\n size(): number {\n return this.innerSize;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { OverlayedDocument } from '../local/overlayed_document';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\nimport { Overlay } from './overlay';\n\n/** Miscellaneous collection types / constants. */\n\nexport type MutableDocumentMap = SortedMap;\nconst EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap(\n DocumentKey.comparator\n);\nexport function mutableDocumentMap(): MutableDocumentMap {\n return EMPTY_MUTABLE_DOCUMENT_MAP;\n}\n\nexport interface DocumentSizeEntries {\n documents: MutableDocumentMap;\n sizeMap: SortedMap;\n}\n\nexport type DocumentMap = SortedMap;\nconst EMPTY_DOCUMENT_MAP = new SortedMap(\n DocumentKey.comparator\n);\nexport function documentMap(...docs: Document[]): DocumentMap {\n let map = EMPTY_DOCUMENT_MAP;\n for (const doc of docs) {\n map = map.insert(doc.key, doc);\n }\n return map;\n}\n\nexport type OverlayedDocumentMap = DocumentKeyMap;\nexport function newOverlayedDocumentMap(): OverlayedDocumentMap {\n return newDocumentKeyMap();\n}\n\nexport function convertOverlayedDocumentMapToDocumentMap(\n collection: OverlayedDocumentMap\n): DocumentMap {\n let documents = EMPTY_DOCUMENT_MAP;\n collection.forEach(\n (k, v) => (documents = documents.insert(k, v.overlayedDocument))\n );\n return documents;\n}\n\nexport type OverlayMap = DocumentKeyMap;\nexport function newOverlayMap(): OverlayMap {\n return newDocumentKeyMap();\n}\n\nexport type MutationMap = DocumentKeyMap;\nexport function newMutationMap(): MutationMap {\n return newDocumentKeyMap();\n}\n\nexport type DocumentKeyMap = ObjectMap;\nexport function newDocumentKeyMap(): DocumentKeyMap {\n return new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n}\n\nexport type DocumentVersionMap = SortedMap;\nconst EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(\n DocumentKey.comparator\n);\nexport function documentVersionMap(): DocumentVersionMap {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nexport type DocumentKeySet = SortedSet;\nconst EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet(...keys: DocumentKey[]): DocumentKeySet {\n let set = EMPTY_DOCUMENT_KEY_SET;\n for (const key of keys) {\n set = set.add(key);\n }\n return set;\n}\n\nexport type TargetIdSet = SortedSet;\nconst EMPTY_TARGET_ID_SET = new SortedSet(primitiveComparator);\nexport function targetIdSet(): SortedSet {\n return EMPTY_TARGET_ID_SET;\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 { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map {\n const result = new Map();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array\n): Map {\n const transformResults = new Map();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map {\n const transformResults = new Map();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\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 */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n DocumentVersionMap,\n documentVersionMap,\n newMutationMap,\n OverlayedDocumentMap\n} from './collections';\nimport { MutableDocument } from './document';\nimport { FieldMask } from './field_mask';\nimport {\n calculateOverlayMutation,\n Mutation,\n mutationApplyToLocalView,\n mutationApplyToRemoteDocument,\n mutationEquals,\n MutationResult\n} from './mutation';\n\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nexport class MutationBatch {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(\n public batchId: BatchId,\n public localWriteTime: Timestamp,\n public baseMutations: Mutation[],\n public mutations: Mutation[]\n ) {\n debugAssert(mutations.length > 0, 'Cannot create an empty mutation batch');\n }\n\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */\n applyToRemoteDocument(\n document: MutableDocument,\n batchResult: MutationBatchResult\n ): void {\n const mutationResults = batchResult.mutationResults;\n debugAssert(\n mutationResults.length === this.mutations.length,\n `Mismatch between mutations length\n (${this.mutations.length}) and mutation results length\n (${mutationResults.length}).`\n );\n\n for (let i = 0; i < this.mutations.length; i++) {\n const mutation = this.mutations[i];\n if (mutation.key.isEqual(document.key)) {\n const mutationResult = mutationResults[i];\n mutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n }\n }\n\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */\n applyToLocalView(\n document: MutableDocument,\n mutatedFields: FieldMask | null\n ): FieldMask | null {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const mutation of this.baseMutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n\n // Second, apply all user-provided mutations.\n for (const mutation of this.mutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n return mutatedFields;\n }\n\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */\n applyToLocalDocumentSet(\n documentMap: OverlayedDocumentMap,\n documentsWithoutRemoteVersion: DocumentKeySet\n ): MutationMap {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const overlays = newMutationMap();\n this.mutations.forEach(m => {\n const overlayedDocument = documentMap.get(m.key)!;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n const mutableDocument =\n overlayedDocument.overlayedDocument as MutableDocument;\n let mutatedFields = this.applyToLocalView(\n mutableDocument,\n overlayedDocument.mutatedFields\n );\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n mutatedFields = documentsWithoutRemoteVersion.has(m.key)\n ? null\n : mutatedFields;\n const overlay = calculateOverlayMutation(mutableDocument, mutatedFields);\n if (overlay !== null) {\n overlays.set(m.key, overlay);\n }\n\n if (!mutableDocument.isValidDocument()) {\n mutableDocument.convertToNoDocument(SnapshotVersion.min());\n }\n });\n return overlays;\n }\n\n keys(): DocumentKeySet {\n return this.mutations.reduce(\n (keys, m) => keys.add(m.key),\n documentKeySet()\n );\n }\n\n isEqual(other: MutationBatch): boolean {\n return (\n this.batchId === other.batchId &&\n arrayEquals(this.mutations, other.mutations, (l, r) =>\n mutationEquals(l, r)\n ) &&\n arrayEquals(this.baseMutations, other.baseMutations, (l, r) =>\n mutationEquals(l, r)\n )\n );\n }\n}\n\n/** The result of applying a mutation batch to the backend. */\nexport class MutationBatchResult {\n private constructor(\n readonly batch: MutationBatch,\n readonly commitVersion: SnapshotVersion,\n readonly mutationResults: MutationResult[],\n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n readonly docVersions: DocumentVersionMap\n ) {}\n\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */\n static from(\n batch: MutationBatch,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ): MutationBatchResult {\n hardAssert(\n batch.mutations.length === results.length,\n 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length\n );\n\n let versionMap = documentVersionMap();\n const mutations = batch.mutations;\n for (let i = 0; i < mutations.length; i++) {\n versionMap = versionMap.insert(mutations[i].key, results[i].version);\n }\n\n return new MutationBatchResult(batch, commitVersion, results, versionMap);\n }\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 { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\n\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */\nexport class Overlay {\n constructor(readonly largestBatchId: number, readonly mutation: Mutation) {}\n\n getKey(): DocumentKey {\n return this.mutation.key;\n }\n\n isEqual(other: Overlay | null): boolean {\n return other !== null && this.mutation === other.mutation;\n }\n\n toString(): string {\n return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\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\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BloomFilter as ProtoBloomFilter } from '../protos/firestore_proto_api';\n\nexport class ExistenceFilter {\n constructor(public count: number, public unchangedNames?: ProtoBloomFilter) {}\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\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/**\n * The global, singleton instance of TestingHooksSpi.\n *\n * This variable will be `null` in all cases _except_ when running from\n * integration tests that have registered callbacks to be notified of events\n * that happen during the test execution.\n */\nexport let testingHooksSpi: TestingHooksSpi | null = null;\n\n/**\n * Sets the value of the `testingHooksSpi` object.\n * @param instance the instance to set.\n */\nexport function setTestingHooksSpi(instance: TestingHooksSpi): void {\n if (testingHooksSpi) {\n throw new Error('a TestingHooksSpi instance is already set');\n }\n testingHooksSpi = instance;\n}\n\n/**\n * The \"service provider interface\" for the testing hooks.\n *\n * The implementation of this object will handle the callbacks made by the SDK\n * to be handled by the integration tests.\n *\n * This \"SPI\" is separated from the implementation to avoid import cycles and\n * to enable production builds to fully tree-shake away the testing hooks logic.\n */\nexport interface TestingHooksSpi {\n /**\n * Invokes all callbacks registered with\n * `TestingHooks.onExistenceFilterMismatch()` with the given info.\n */\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void;\n}\n\n/**\n * Information about an existence filter mismatch.\n * @internal\n */\nexport interface ExistenceFilterMismatchInfo {\n /** The number of documents that matched the query in the local cache. */\n localCacheCount: number;\n\n /**\n * The number of documents that matched the query on the server, as specified\n * in the ExistenceFilter message's `count` field.\n */\n existenceFilterCount: number;\n\n /**\n * The projectId used when checking documents for membership in the bloom\n * filter.\n */\n projectId: string;\n\n /**\n * The databaseId used when checking documents for membership in the bloom\n * filter.\n */\n databaseId: string;\n\n /**\n * Information about the bloom filter provided by Watch in the ExistenceFilter\n * message's `unchangedNames` field. If this property is omitted or undefined\n * then that means that Watch did _not_ provide a bloom filter.\n */\n bloomFilter?: {\n /**\n * Whether a full requery was averted by using the bloom filter. If false,\n * then something happened, such as a false positive, to prevent using the\n * bloom filter to avoid a full requery.\n */\n applied: boolean;\n\n /** The number of hash functions used in the bloom filter. */\n hashCount: number;\n\n /** The number of bytes in the bloom filter's bitmask. */\n bitmapLength: number;\n\n /** The number of bits of padding in the last byte of the bloom filter. */\n padding: number;\n\n /**\n * Tests the given string for membership in the bloom filter created from\n * the existence filter; will be undefined if creating the bloom filter\n * failed.\n */\n mightContain?: (value: string) => boolean;\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/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\nexport function newTextEncoder(): TextEncoder {\n return new TextEncoder();\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\nexport function newTextDecoder(): TextDecoder {\n return new TextDecoder('utf-8');\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 { Md5, Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { newTextEncoder } from '../platform/text_serializer';\n\nconst MAX_64_BIT_UNSIGNED_INTEGER = new Integer([0xffffffff, 0xffffffff], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction getMd5HashValue(value: string): Uint8Array {\n const encodedValue = newTextEncoder().encode(value);\n const md5 = new Md5();\n md5.update(encodedValue);\n return new Uint8Array(md5.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2’s complement using little endian.\nfunction get64BitUints(Bytes: Uint8Array): [Integer, Integer] {\n const dataView = new DataView(Bytes.buffer);\n const chunk1 = dataView.getUint32(0, /* littleEndian= */ true);\n const chunk2 = dataView.getUint32(4, /* littleEndian= */ true);\n const chunk3 = dataView.getUint32(8, /* littleEndian= */ true);\n const chunk4 = dataView.getUint32(12, /* littleEndian= */ true);\n const integer1 = new Integer([chunk1, chunk2], 0);\n const integer2 = new Integer([chunk3, chunk4], 0);\n return [integer1, integer2];\n}\n\nexport class BloomFilter {\n readonly bitCount: number;\n private readonly bitCountInInteger: Integer;\n\n constructor(\n readonly bitmap: Uint8Array,\n readonly padding: number,\n readonly hashCount: number\n ) {\n if (padding < 0 || padding >= 8) {\n throw new BloomFilterError(`Invalid padding: ${padding}`);\n }\n\n if (hashCount < 0) {\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length > 0 && this.hashCount === 0) {\n // Only empty bloom filter can have 0 hash count.\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length === 0 && padding !== 0) {\n // Empty bloom filter should have 0 padding.\n throw new BloomFilterError(\n `Invalid padding when bitmap length is 0: ${padding}`\n );\n }\n\n this.bitCount = bitmap.length * 8 - padding;\n // Set the bit count in Integer to avoid repetition in mightContain().\n this.bitCountInInteger = Integer.fromNumber(this.bitCount);\n }\n\n // Calculate the ith hash value based on the hashed 64bit integers,\n // and calculate its corresponding bit index in the bitmap to be checked.\n private getBitIndex(num1: Integer, num2: Integer, hashIndex: number): number {\n // Calculate hashed value h(i) = h1 + (i * h2).\n let hashValue = num1.add(num2.multiply(Integer.fromNumber(hashIndex)));\n // Wrap if hash value overflow 64bit.\n if (hashValue.compare(MAX_64_BIT_UNSIGNED_INTEGER) === 1) {\n hashValue = new Integer([hashValue.getBits(0), hashValue.getBits(1)], 0);\n }\n return hashValue.modulo(this.bitCountInInteger).toNumber();\n }\n\n // Return whether the bit on the given index in the bitmap is set to 1.\n private isBitSet(index: number): boolean {\n // To retrieve bit n, calculate: (bitmap[n / 8] & (0x01 << (n % 8))).\n const byte = this.bitmap[Math.floor(index / 8)];\n const offset = index % 8;\n return (byte & (0x01 << offset)) !== 0;\n }\n\n mightContain(value: string): boolean {\n // Empty bitmap should always return false on membership check.\n if (this.bitCount === 0) {\n return false;\n }\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n if (!this.isBitSet(index)) {\n return false;\n }\n }\n return true;\n }\n\n /** Create bloom filter for testing purposes only. */\n static create(\n bitCount: number,\n hashCount: number,\n contains: string[]\n ): BloomFilter {\n const padding = bitCount % 8 === 0 ? 0 : 8 - (bitCount % 8);\n const bitmap = new Uint8Array(Math.ceil(bitCount / 8));\n const bloomFilter = new BloomFilter(bitmap, padding, hashCount);\n contains.forEach(item => bloomFilter.insert(item));\n return bloomFilter;\n }\n\n private insert(value: string): void {\n if (this.bitCount === 0) {\n return;\n }\n\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n this.setBit(index);\n }\n }\n\n private setBit(index: number): void {\n const indexOfByte = Math.floor(index / 8);\n const offset = index % 8;\n this.bitmap[indexOfByte] |= 0x01 << offset;\n }\n}\n\nexport class BloomFilterError extends Error {\n readonly name = 'BloomFilterError';\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap,\n MutableDocumentMap\n} from '../model/collections';\nimport { ByteString } from '../util/byte_string';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\n\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */\nexport class RemoteEvent {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n readonly snapshotVersion: SnapshotVersion,\n /**\n * A map from target to changes to the target. See TargetChange.\n */\n readonly targetChanges: Map,\n /**\n * A map of targets that is known to be inconsistent, and the purpose for\n * re-listening. Listens for these targets should be re-established without\n * resume tokens.\n */\n readonly targetMismatches: SortedMap,\n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n readonly documentUpdates: MutableDocumentMap,\n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n readonly resolvedLimboDocuments: DocumentKeySet\n ) {}\n\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): RemoteEvent {\n const targetChanges = new Map();\n targetChanges.set(\n targetId,\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current,\n resumeToken\n )\n );\n return new RemoteEvent(\n SnapshotVersion.min(),\n targetChanges,\n new SortedMap(primitiveComparator),\n mutableDocumentMap(),\n documentKeySet()\n );\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */\nexport class TargetChange {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n readonly resumeToken: ByteString,\n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n readonly current: boolean,\n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n readonly addedDocuments: DocumentKeySet,\n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n readonly modifiedDocuments: DocumentKeySet,\n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n readonly removedDocuments: DocumentKeySet\n ) {}\n\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */\n static createSynthesizedTargetChangeForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): TargetChange {\n return new TargetChange(\n resumeToken,\n current,\n documentKeySet(),\n documentKeySet(),\n documentKeySet()\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 { DatabaseId } from '../core/database_info';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { ChangeType } from '../core/view_snapshot';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { normalizeByteString } from '../model/normalize';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { Base64DecodeError } from '../util/base64_decode_error';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport {\n testingHooksSpi,\n ExistenceFilterMismatchInfo as TestingHooksExistenceFilterMismatchInfo\n} from '../util/testing_hooks_spi';\n\nimport { BloomFilter, BloomFilterError } from './bloom_filter';\nimport { ExistenceFilter } from './existence_filter';\nimport { RemoteEvent, TargetChange } from './remote_event';\n\n/**\n * Internal representation of the watcher API protocol buffers.\n */\nexport type WatchChange =\n | DocumentWatchChange\n | WatchTargetChange\n | ExistenceFilterChange;\n\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */\nexport class DocumentWatchChange {\n constructor(\n /** The new document applies to all of these targets. */\n public updatedTargetIds: TargetId[],\n /** The new document is removed from all of these targets. */\n public removedTargetIds: TargetId[],\n /** The key of the document for this change. */\n public key: DocumentKey,\n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n public newDoc: MutableDocument | null\n ) {}\n}\n\nexport class ExistenceFilterChange {\n constructor(\n public targetId: TargetId,\n public existenceFilter: ExistenceFilter\n ) {}\n}\n\nexport const enum WatchTargetChangeState {\n NoChange,\n Added,\n Removed,\n Current,\n Reset\n}\n\nconst enum BloomFilterApplicationStatus {\n Success,\n Skipped,\n FalsePositive\n}\nexport class WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n public state: WatchTargetChangeState,\n /** The target IDs that were added/removed/set. */\n public targetIds: TargetId[],\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n public resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /** An RPC error indicating why the watch failed. */\n public cause: FirestoreError | null = null\n ) {}\n}\n\n/** Tracks the internal state of a Watch target. */\nclass TargetState {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n private pendingResponses = 0;\n\n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n private documentChanges: SortedMap =\n snapshotChangesMap();\n\n /** See public getters for explanations of these fields. */\n private _resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n private _current = false;\n\n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n private _hasPendingChanges = true;\n\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */\n get current(): boolean {\n return this._current;\n }\n\n /** The last resume token sent to us for this target. */\n get resumeToken(): ByteString {\n return this._resumeToken;\n }\n\n /** Whether this target has pending target adds or target removes. */\n get isPending(): boolean {\n return this.pendingResponses !== 0;\n }\n\n /** Whether we have modified any state that should trigger a snapshot. */\n get hasPendingChanges(): boolean {\n return this._hasPendingChanges;\n }\n\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */\n updateResumeToken(resumeToken: ByteString): void {\n if (resumeToken.approximateByteSize() > 0) {\n this._hasPendingChanges = true;\n this._resumeToken = resumeToken;\n }\n }\n\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */\n toTargetChange(): TargetChange {\n let addedDocuments = documentKeySet();\n let modifiedDocuments = documentKeySet();\n let removedDocuments = documentKeySet();\n\n this.documentChanges.forEach((key, changeType) => {\n switch (changeType) {\n case ChangeType.Added:\n addedDocuments = addedDocuments.add(key);\n break;\n case ChangeType.Modified:\n modifiedDocuments = modifiedDocuments.add(key);\n break;\n case ChangeType.Removed:\n removedDocuments = removedDocuments.add(key);\n break;\n default:\n fail('Encountered invalid change type: ' + changeType);\n }\n });\n\n return new TargetChange(\n this._resumeToken,\n this._current,\n addedDocuments,\n modifiedDocuments,\n removedDocuments\n );\n }\n\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */\n clearPendingChanges(): void {\n this._hasPendingChanges = false;\n this.documentChanges = snapshotChangesMap();\n }\n\n addDocumentChange(key: DocumentKey, changeType: ChangeType): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.insert(key, changeType);\n }\n\n removeDocumentChange(key: DocumentKey): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.remove(key);\n }\n\n recordPendingTargetRequest(): void {\n this.pendingResponses += 1;\n }\n\n recordTargetResponse(): void {\n this.pendingResponses -= 1;\n hardAssert(\n this.pendingResponses >= 0,\n '`pendingResponses` is less than 0. Actual value: ' +\n this.pendingResponses +\n '. This indicates that the SDK received more target acks from the ' +\n 'server than expected. The SDK should not continue to operate.'\n );\n }\n\n markCurrent(): void {\n this._hasPendingChanges = true;\n this._current = true;\n }\n}\n\n/**\n * Interface implemented by RemoteStore to expose target metadata to the\n * WatchChangeAggregator.\n */\nexport interface TargetMetadataProvider {\n /**\n * Returns the set of remote document keys for the given target ID as of the\n * last raised snapshot.\n */\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet;\n\n /**\n * Returns the TargetData for an active target ID or 'null' if this target\n * has become inactive\n */\n getTargetDataForTarget(targetId: TargetId): TargetData | null;\n\n /**\n * Returns the database ID of the Firestore instance.\n */\n getDatabaseId(): DatabaseId;\n}\n\nconst LOG_TAG = 'WatchChangeAggregator';\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nexport class WatchChangeAggregator {\n constructor(private metadataProvider: TargetMetadataProvider) {}\n\n /** The internal state of all tracked targets. */\n private targetStates = new Map();\n\n /** Keeps track of the documents to update since the last raised snapshot. */\n private pendingDocumentUpdates = mutableDocumentMap();\n\n /** A mapping of document keys to their set of target IDs. */\n private pendingDocumentTargetMapping = documentTargetMap();\n\n /**\n * A map of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n private pendingTargetResets = new SortedMap(\n primitiveComparator\n );\n\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */\n handleDocumentChange(docChange: DocumentWatchChange): void {\n for (const targetId of docChange.updatedTargetIds) {\n if (docChange.newDoc && docChange.newDoc.isFoundDocument()) {\n this.addDocumentToTarget(targetId, docChange.newDoc);\n } else {\n this.removeDocumentFromTarget(\n targetId,\n docChange.key,\n docChange.newDoc\n );\n }\n }\n\n for (const targetId of docChange.removedTargetIds) {\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n }\n }\n\n /** Processes and adds the WatchTargetChange to the current set of changes. */\n handleTargetChange(targetChange: WatchTargetChange): void {\n this.forEachTarget(targetChange, targetId => {\n const targetState = this.ensureTargetState(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (this.isActiveTarget(targetId)) {\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n targetState.clearPendingChanges();\n }\n targetState.updateResumeToken(targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n this.removeTarget(targetId);\n }\n debugAssert(\n !targetChange.cause,\n 'WatchChangeAggregator does not handle errored targets'\n );\n break;\n case WatchTargetChangeState.Current:\n if (this.isActiveTarget(targetId)) {\n targetState.markCurrent();\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (this.isActiveTarget(targetId)) {\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.resetTarget(targetId);\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n }\n\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */\n forEachTarget(\n targetChange: WatchTargetChange,\n fn: (targetId: TargetId) => void\n ): void {\n if (targetChange.targetIds.length > 0) {\n targetChange.targetIds.forEach(fn);\n } else {\n this.targetStates.forEach((_, targetId) => {\n if (this.isActiveTarget(targetId)) {\n fn(targetId);\n }\n });\n }\n }\n\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */\n handleExistenceFilter(watchChange: ExistenceFilterChange): void {\n const targetId = watchChange.targetId;\n const expectedCount = watchChange.existenceFilter.count;\n\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n const target = targetData.target;\n if (targetIsDocumentTarget(target)) {\n if (expectedCount === 0) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const key = new DocumentKey(target.path);\n this.removeDocumentFromTarget(\n targetId,\n key,\n MutableDocument.newNoDocument(key, SnapshotVersion.min())\n );\n } else {\n hardAssert(\n expectedCount === 1,\n 'Single document existence filter with count: ' + expectedCount\n );\n }\n } else {\n const currentSize = this.getCurrentDocumentCountForTarget(targetId);\n // Existence filter mismatch. Mark the documents as being in limbo, and\n // raise a snapshot with `isFromCache:true`.\n if (currentSize !== expectedCount) {\n // Apply bloom filter to identify and mark removed documents.\n const bloomFilter = this.parseBloomFilter(watchChange);\n const status = bloomFilter\n ? this.applyBloomFilter(bloomFilter, watchChange, currentSize)\n : BloomFilterApplicationStatus.Skipped;\n\n if (status !== BloomFilterApplicationStatus.Success) {\n // If bloom filter application fails, we reset the mapping and\n // trigger re-run of the query.\n this.resetTarget(targetId);\n\n const purpose: TargetPurpose =\n status === BloomFilterApplicationStatus.FalsePositive\n ? TargetPurpose.ExistenceFilterMismatchBloom\n : TargetPurpose.ExistenceFilterMismatch;\n this.pendingTargetResets = this.pendingTargetResets.insert(\n targetId,\n purpose\n );\n }\n testingHooksSpi?.notifyOnExistenceFilterMismatch(\n createExistenceFilterMismatchInfoForTestingHooks(\n currentSize,\n watchChange.existenceFilter,\n this.metadataProvider.getDatabaseId(),\n bloomFilter,\n status\n )\n );\n }\n }\n }\n }\n\n /**\n * Parse the bloom filter from the \"unchanged_names\" field of an existence\n * filter.\n */\n private parseBloomFilter(\n watchChange: ExistenceFilterChange\n ): BloomFilter | null {\n const unchangedNames = watchChange.existenceFilter.unchangedNames;\n if (!unchangedNames || !unchangedNames.bits) {\n return null;\n }\n\n const {\n bits: { bitmap = '', padding = 0 },\n hashCount = 0\n } = unchangedNames;\n\n let normalizedBitmap: Uint8Array;\n try {\n normalizedBitmap = normalizeByteString(bitmap).toUint8Array();\n } catch (err) {\n if (err instanceof Base64DecodeError) {\n logWarn(\n 'Decoding the base64 bloom filter in existence filter failed (' +\n err.message +\n '); ignoring the bloom filter and falling back to full re-query.'\n );\n return null;\n } else {\n throw err;\n }\n }\n\n let bloomFilter: BloomFilter;\n try {\n // BloomFilter throws error if the inputs are invalid.\n bloomFilter = new BloomFilter(normalizedBitmap, padding, hashCount);\n } catch (err) {\n if (err instanceof BloomFilterError) {\n logWarn('BloomFilter error: ', err);\n } else {\n logWarn('Applying bloom filter failed: ', err);\n }\n return null;\n }\n\n if (bloomFilter.bitCount === 0) {\n return null;\n }\n\n return bloomFilter;\n }\n\n /**\n * Apply bloom filter to remove the deleted documents, and return the\n * application status.\n */\n private applyBloomFilter(\n bloomFilter: BloomFilter,\n watchChange: ExistenceFilterChange,\n currentCount: number\n ): BloomFilterApplicationStatus {\n const expectedCount = watchChange.existenceFilter.count;\n\n const removedDocumentCount = this.filterRemovedDocuments(\n bloomFilter,\n watchChange.targetId\n );\n\n return expectedCount === currentCount - removedDocumentCount\n ? BloomFilterApplicationStatus.Success\n : BloomFilterApplicationStatus.FalsePositive;\n }\n\n /**\n * Filter out removed documents based on bloom filter membership result and\n * return number of documents removed.\n */\n private filterRemovedDocuments(\n bloomFilter: BloomFilter,\n targetId: number\n ): number {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n let removalCount = 0;\n\n existingKeys.forEach(key => {\n const databaseId = this.metadataProvider.getDatabaseId();\n const documentPath =\n `projects/${databaseId.projectId}` +\n `/databases/${databaseId.database}` +\n `/documents/${key.path.canonicalString()}`;\n\n if (!bloomFilter.mightContain(documentPath)) {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n removalCount++;\n }\n });\n\n return removalCount;\n }\n\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */\n createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent {\n const targetChanges = new Map();\n\n this.targetStates.forEach((targetState, targetId) => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n if (targetState.current && targetIsDocumentTarget(targetData.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n //\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const key = new DocumentKey(targetData.target.path);\n if (\n this.pendingDocumentUpdates.get(key) === null &&\n !this.targetContainsDocument(targetId, key)\n ) {\n this.removeDocumentFromTarget(\n targetId,\n key,\n MutableDocument.newNoDocument(key, snapshotVersion)\n );\n }\n }\n\n if (targetState.hasPendingChanges) {\n targetChanges.set(targetId, targetState.toTargetChange());\n targetState.clearPendingChanges();\n }\n }\n });\n\n let resolvedLimboDocuments = documentKeySet();\n\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n //\n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.pendingDocumentTargetMapping.forEach((key, targets) => {\n let isOnlyLimboTarget = true;\n\n targets.forEachWhile(targetId => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (\n targetData &&\n targetData.purpose !== TargetPurpose.LimboResolution\n ) {\n isOnlyLimboTarget = false;\n return false;\n }\n\n return true;\n });\n\n if (isOnlyLimboTarget) {\n resolvedLimboDocuments = resolvedLimboDocuments.add(key);\n }\n });\n\n this.pendingDocumentUpdates.forEach((_, doc) =>\n doc.setReadTime(snapshotVersion)\n );\n\n const remoteEvent = new RemoteEvent(\n snapshotVersion,\n targetChanges,\n this.pendingTargetResets,\n this.pendingDocumentUpdates,\n resolvedLimboDocuments\n );\n\n this.pendingDocumentUpdates = mutableDocumentMap();\n this.pendingDocumentTargetMapping = documentTargetMap();\n this.pendingTargetResets = new SortedMap(\n primitiveComparator\n );\n\n return remoteEvent;\n }\n\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n addDocumentToTarget(targetId: TargetId, document: MutableDocument): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const changeType = this.targetContainsDocument(targetId, document.key)\n ? ChangeType.Modified\n : ChangeType.Added;\n\n const targetState = this.ensureTargetState(targetId);\n targetState.addDocumentChange(document.key, changeType);\n\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n document.key,\n document\n );\n\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n document.key,\n this.ensureDocumentTargetMapping(document.key).add(targetId)\n );\n }\n\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n removeDocumentFromTarget(\n targetId: TargetId,\n key: DocumentKey,\n updatedDocument: MutableDocument | null\n ): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const targetState = this.ensureTargetState(targetId);\n if (this.targetContainsDocument(targetId, key)) {\n targetState.addDocumentChange(key, ChangeType.Removed);\n } else {\n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n targetState.removeDocumentChange(key);\n }\n\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).delete(targetId)\n );\n\n if (updatedDocument) {\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n key,\n updatedDocument\n );\n }\n }\n\n removeTarget(targetId: TargetId): void {\n this.targetStates.delete(targetId);\n }\n\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */\n private getCurrentDocumentCountForTarget(targetId: TargetId): number {\n const targetState = this.ensureTargetState(targetId);\n const targetChange = targetState.toTargetChange();\n return (\n this.metadataProvider.getRemoteKeysForTarget(targetId).size +\n targetChange.addedDocuments.size -\n targetChange.removedDocuments.size\n );\n }\n\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */\n recordPendingTargetRequest(targetId: TargetId): void {\n // For each request we get we need to record we need a response for it.\n const targetState = this.ensureTargetState(targetId);\n targetState.recordPendingTargetRequest();\n }\n\n private ensureTargetState(targetId: TargetId): TargetState {\n let result = this.targetStates.get(targetId);\n if (!result) {\n result = new TargetState();\n this.targetStates.set(targetId, result);\n }\n return result;\n }\n\n private ensureDocumentTargetMapping(key: DocumentKey): SortedSet {\n let targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(primitiveComparator);\n this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(key, targetMapping);\n }\n\n return targetMapping;\n }\n\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */\n protected isActiveTarget(targetId: TargetId): boolean {\n const targetActive = this.targetDataForActiveTarget(targetId) !== null;\n if (!targetActive) {\n logDebug(LOG_TAG, 'Detected inactive target', targetId);\n }\n return targetActive;\n }\n\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */\n protected targetDataForActiveTarget(targetId: TargetId): TargetData | null {\n const targetState = this.targetStates.get(targetId);\n return targetState && targetState.isPending\n ? null\n : this.metadataProvider.getTargetDataForTarget(targetId);\n }\n\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */\n private resetTarget(targetId: TargetId): void {\n debugAssert(\n !this.targetStates.get(targetId)!.isPending,\n 'Should only reset active targets'\n );\n this.targetStates.set(targetId, new TargetState());\n\n // Trigger removal for any documents currently mapped to this target.\n // These removals will be part of the initial snapshot if Watch does not\n // resend these documents.\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n existingKeys.forEach(key => {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n });\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */\n private targetContainsDocument(\n targetId: TargetId,\n key: DocumentKey\n ): boolean {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n return existingKeys.has(key);\n }\n}\n\nfunction documentTargetMap(): SortedMap> {\n return new SortedMap>(\n DocumentKey.comparator\n );\n}\n\nfunction snapshotChangesMap(): SortedMap {\n return new SortedMap(DocumentKey.comparator);\n}\n\nfunction createExistenceFilterMismatchInfoForTestingHooks(\n localCacheCount: number,\n existenceFilter: ExistenceFilter,\n databaseId: DatabaseId,\n bloomFilter: BloomFilter | null,\n bloomFilterStatus: BloomFilterApplicationStatus\n): TestingHooksExistenceFilterMismatchInfo {\n const result: TestingHooksExistenceFilterMismatchInfo = {\n localCacheCount,\n existenceFilterCount: existenceFilter.count,\n databaseId: databaseId.database,\n projectId: databaseId.projectId\n };\n\n const unchangedNames = existenceFilter.unchangedNames;\n if (unchangedNames) {\n result.bloomFilter = {\n applied: bloomFilterStatus === BloomFilterApplicationStatus.Success,\n hashCount: unchangedNames?.hashCount ?? 0,\n bitmapLength: unchangedNames?.bits?.bitmap?.length ?? 0,\n padding: unchangedNames?.bits?.padding ?? 0,\n mightContain: (value: string): boolean =>\n bloomFilter?.mightContain(value) ?? false\n };\n }\n\n return result;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\nfunction fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined ||\n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n value instanceof Buffer ||\n value instanceof Uint8Array,\n 'value must be undefined, Buffer, or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 'tried to deserialize invalid key ' + resourceName.toString()\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[],\n skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = skipAliasing\n ? aggregate.alias\n : `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified operator');\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail('Unrecognized filter type ' + JSON.stringify(filter));\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { ByteString } from '../util/byte_string';\n\n/** An enumeration of the different purposes we have for targets. */\nexport const enum TargetPurpose {\n /** A regular, normal query target. */\n Listen = 'TargetPurposeListen',\n\n /**\n * The query target was used to refill a query after an existence filter\n * mismatch.\n */\n ExistenceFilterMismatch = 'TargetPurposeExistenceFilterMismatch',\n\n /**\n * The query target was used if the query is the result of a false positive in\n * the bloom filter.\n */\n ExistenceFilterMismatchBloom = 'TargetPurposeExistenceFilterMismatchBloom',\n\n /** The query target was used to resolve a limbo document. */\n LimboResolution = 'TargetPurposeLimboResolution'\n}\n\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */\nexport class TargetData {\n constructor(\n /** The target being listened to. */\n readonly target: Target,\n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n readonly targetId: TargetId,\n /** The purpose of the target. */\n readonly purpose: TargetPurpose,\n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n readonly sequenceNumber: ListenSequenceNumber,\n /** The latest snapshot version seen for this target. */\n readonly snapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */\n readonly lastLimboFreeSnapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n readonly resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /**\n * The number of documents that last matched the query at the resume token or\n * read time. Documents are counted only when making a listen request with\n * resume token or read time, otherwise, keep it null.\n */\n readonly expectedCount: number | null = null\n ) {}\n\n /** Creates a new target data instance with an updated sequence number. */\n withSequenceNumber(sequenceNumber: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n this.expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */\n withResumeToken(\n resumeToken: ByteString,\n snapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n resumeToken,\n /* expectedCount= */ null\n );\n }\n\n /**\n * Creates a new target data instance with an updated expected count.\n */\n withExpectedCount(expectedCount: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */\n withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n lastLimboFreeSnapshotVersion,\n this.resumeToken,\n this.expectedCount\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 { Timestamp } from '../api/timestamp';\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport { LimitType, Query, queryWithLimit } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetIsDocumentTarget } from '../core/target';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n IndexOffset,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { Overlay } from '../model/overlay';\nimport { FieldPath } from '../model/path';\nimport {\n BundledQuery as ProtoBundledQuery,\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { DocumentsTarget as PublicDocumentsTarget } from '../protos/firestore_proto_api';\nimport {\n convertQueryTargetToQuery,\n fromDocument,\n fromDocumentsTarget,\n fromMutation,\n fromQueryTarget,\n fromVersion,\n JsonProtoSerializer,\n toDocument,\n toDocumentsTarget,\n toMutation,\n toQueryTarget\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport {\n DbBundle,\n DbDocumentOverlay,\n DbIndexConfiguration,\n DbIndexState,\n DbMutationBatch,\n DbNamedQuery,\n DbQuery,\n DbRemoteDocument,\n DbTarget,\n DbTimestamp\n} from './indexeddb_schema';\nimport { DbDocumentOverlayKey, DbTimestampKey } from './indexeddb_sentinels';\nimport { TargetData, TargetPurpose } from './target_data';\n\n/** Serializer for values stored in the LocalStore. */\nexport class LocalSerializer {\n constructor(readonly remoteSerializer: JsonProtoSerializer) {}\n}\n\n/** Decodes a remote document from storage locally to a Document. */\nexport function fromDbRemoteDocument(\n localSerializer: LocalSerializer,\n remoteDoc: DbRemoteDocument\n): MutableDocument {\n let doc: MutableDocument;\n if (remoteDoc.document) {\n doc = fromDocument(\n localSerializer.remoteSerializer,\n remoteDoc.document,\n !!remoteDoc.hasCommittedMutations\n );\n } else if (remoteDoc.noDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n const version = fromDbTimestamp(remoteDoc.noDocument.readTime);\n doc = MutableDocument.newNoDocument(key, version);\n if (remoteDoc.hasCommittedMutations) {\n doc.setHasCommittedMutations();\n }\n } else if (remoteDoc.unknownDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n const version = fromDbTimestamp(remoteDoc.unknownDocument.version);\n doc = MutableDocument.newUnknownDocument(key, version);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n\n if (remoteDoc.readTime) {\n doc.setReadTime(fromDbTimestampKey(remoteDoc.readTime));\n }\n\n return doc;\n}\n\n/** Encodes a document for storage locally. */\nexport function toDbRemoteDocument(\n localSerializer: LocalSerializer,\n document: MutableDocument\n): DbRemoteDocument {\n const key = document.key;\n const remoteDoc: DbRemoteDocument = {\n prefixPath: key.getCollectionPath().popLast().toArray(),\n collectionGroup: key.collectionGroup,\n documentId: key.path.lastSegment(),\n readTime: toDbTimestampKey(document.readTime),\n hasCommittedMutations: document.hasCommittedMutations\n };\n\n if (document.isFoundDocument()) {\n remoteDoc.document = toDocument(localSerializer.remoteSerializer, document);\n } else if (document.isNoDocument()) {\n remoteDoc.noDocument = {\n path: key.path.toArray(),\n readTime: toDbTimestamp(document.version)\n };\n } else if (document.isUnknownDocument()) {\n remoteDoc.unknownDocument = {\n path: key.path.toArray(),\n version: toDbTimestamp(document.version)\n };\n } else {\n return fail('Unexpected Document ' + document);\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n ).queryTarget;\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n uid: string,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid,\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\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 { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n DbBundlesKey,\n DbBundleStore,\n DbNamedQueriesKey,\n DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbBundle,\n fromDbNamedQuery,\n toDbBundle,\n toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return bundlesStore(transaction)\n .get(bundleId)\n .next(bundle => {\n if (bundle) {\n return fromDbBundle(bundle);\n }\n return undefined;\n });\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return namedQueriesStore(transaction)\n .get(queryName)\n .next(query => {\n if (query) {\n return fromDbNamedQuery(query);\n }\n return undefined;\n });\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbNamedQueryStore);\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 { User } from '../auth/user';\nimport {\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayKey,\n DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbDocumentOverlay,\n LocalSerializer,\n toDbDocumentOverlay,\n toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(\n private readonly serializer: LocalSerializer,\n private readonly userId: string\n ) {}\n\n static forUser(\n serializer: LocalSerializer,\n user: User\n ): IndexedDbDocumentOverlayCache {\n const userId = user.uid || '';\n return new IndexedDbDocumentOverlayCache(serializer, userId);\n }\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return documentOverlayStore(transaction)\n .get(toDbDocumentOverlayKey(this.userId, key))\n .next(dbOverlay => {\n if (dbOverlay) {\n return fromDbDocumentOverlay(this.serializer, dbOverlay);\n }\n return null;\n });\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\n const result = newOverlayMap();\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n return this.getOverlay(transaction, key).next(overlay => {\n if (overlay !== null) {\n result.set(key, overlay);\n }\n });\n }).next(() => result);\n }\n\n saveOverlays(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n overlays: MutationMap\n ): PersistencePromise {\n const promises: Array> = [];\n overlays.forEach((_, mutation) => {\n const overlay = new Overlay(largestBatchId, mutation);\n promises.push(this.saveOverlay(transaction, overlay));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const collectionPaths = new Set();\n\n // Get the set of unique collection paths.\n documentKeys.forEach(key =>\n collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n );\n\n const promises: Array> = [];\n collectionPaths.forEach(collectionPath => {\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, batchId],\n [this.userId, collectionPath, batchId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n promises.push(\n documentOverlayStore(transaction).deleteAll(\n DbDocumentOverlayCollectionPathOverlayIndex,\n range\n )\n );\n });\n return PersistencePromise.waitFor(promises);\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n const collectionPath = encodeResourcePath(collection);\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, sinceBatchId],\n [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n .next(dbOverlays => {\n for (const dbOverlay of dbOverlays) {\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n result.set(overlay.getKey(), overlay);\n }\n return result;\n });\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n const result = newOverlayMap();\n let currentBatchId: number | undefined = undefined;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionGroup, sinceBatchId],\n [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .iterate(\n {\n index: DbDocumentOverlayCollectionGroupOverlayIndex,\n range\n },\n (_, dbOverlay, control) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n if (\n result.size() < count ||\n overlay.largestBatchId === currentBatchId\n ) {\n result.set(overlay.getKey(), overlay);\n currentBatchId = overlay.largestBatchId;\n } else {\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n overlay: Overlay\n ): PersistencePromise {\n return documentOverlayStore(transaction).put(\n toDbDocumentOverlay(this.serializer, this.userId, overlay)\n );\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentOverlayStore\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 { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { isMaxValue } from '../model/values';\nimport { ArrayValue, MapValue, Value } from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { isNegativeZero } from '../util/types';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\n\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n\nconst INDEX_TYPE_NULL = 5;\nconst INDEX_TYPE_BOOLEAN = 10;\nconst INDEX_TYPE_NAN = 13;\nconst INDEX_TYPE_NUMBER = 15;\nconst INDEX_TYPE_TIMESTAMP = 20;\nconst INDEX_TYPE_STRING = 25;\nconst INDEX_TYPE_BLOB = 30;\nconst INDEX_TYPE_REFERENCE = 37;\nconst INDEX_TYPE_GEOPOINT = 45;\nconst INDEX_TYPE_ARRAY = 50;\nconst INDEX_TYPE_MAP = 55;\nconst INDEX_TYPE_REFERENCE_SEGMENT = 60;\n\n// A terminator that indicates that a truncatable value was not truncated.\n// This must be smaller than all other type labels.\nconst NOT_TRUNCATED = 2;\n\n/** Firestore index value writer. */\nexport class FirestoreIndexValueWriter {\n static INSTANCE = new FirestoreIndexValueWriter();\n\n private constructor() {}\n\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n //\n // As an example, consider the resulting encoding for:\n //\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n\n /** Writes an index value. */\n writeIndexValue(value: Value, encoder: DirectionalIndexByteEncoder): void {\n this.writeIndexValueAux(value, encoder);\n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n encoder.writeInfinity();\n }\n\n private writeIndexValueAux(\n indexValue: Value,\n encoder: DirectionalIndexByteEncoder\n ): void {\n if ('nullValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NULL);\n } else if ('booleanValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BOOLEAN);\n encoder.writeNumber(indexValue.booleanValue ? 1 : 0);\n } else if ('integerValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n encoder.writeNumber(normalizeNumber(indexValue.integerValue));\n } else if ('doubleValue' in indexValue) {\n const n = normalizeNumber(indexValue.doubleValue);\n if (isNaN(n)) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NAN);\n } else {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n if (isNegativeZero(n)) {\n // -0.0, 0 and 0.0 are all considered the same\n encoder.writeNumber(0.0);\n } else {\n encoder.writeNumber(n);\n }\n }\n } else if ('timestampValue' in indexValue) {\n let timestamp = indexValue.timestampValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_TIMESTAMP);\n if (typeof timestamp === 'string') {\n timestamp = normalizeTimestamp(timestamp);\n }\n encoder.writeString(`${timestamp.seconds || ''}`);\n encoder.writeNumber(timestamp.nanos || 0);\n } else if ('stringValue' in indexValue) {\n this.writeIndexString(indexValue.stringValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else if ('bytesValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BLOB);\n encoder.writeBytes(normalizeByteString(indexValue.bytesValue!));\n this.writeTruncationMarker(encoder);\n } else if ('referenceValue' in indexValue) {\n this.writeIndexEntityRef(indexValue.referenceValue!, encoder);\n } else if ('geoPointValue' in indexValue) {\n const geoPoint = indexValue.geoPointValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_GEOPOINT);\n encoder.writeNumber(geoPoint.latitude || 0);\n encoder.writeNumber(geoPoint.longitude || 0);\n } else if ('mapValue' in indexValue) {\n if (isMaxValue(indexValue)) {\n this.writeValueTypeLabel(encoder, Number.MAX_SAFE_INTEGER);\n } else {\n this.writeIndexMap(indexValue.mapValue!, encoder);\n this.writeTruncationMarker(encoder);\n }\n } else if ('arrayValue' in indexValue) {\n this.writeIndexArray(indexValue.arrayValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else {\n fail('unknown index value type ' + indexValue);\n }\n }\n\n private writeIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_STRING);\n this.writeUnlabeledIndexString(stringIndexValue, encoder);\n }\n\n private writeUnlabeledIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n encoder.writeString(stringIndexValue);\n }\n\n private writeIndexMap(\n mapIndexValue: MapValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const map = mapIndexValue.fields || {};\n this.writeValueTypeLabel(encoder, INDEX_TYPE_MAP);\n for (const key of Object.keys(map)) {\n this.writeIndexString(key, encoder);\n this.writeIndexValueAux(map[key], encoder);\n }\n }\n\n private writeIndexArray(\n arrayIndexValue: ArrayValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const values = arrayIndexValue.values || [];\n this.writeValueTypeLabel(encoder, INDEX_TYPE_ARRAY);\n for (const element of values) {\n this.writeIndexValueAux(element, encoder);\n }\n }\n\n private writeIndexEntityRef(\n referenceValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE);\n const path = DocumentKey.fromName(referenceValue).path;\n path.forEach(segment => {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE_SEGMENT);\n this.writeUnlabeledIndexString(segment, encoder);\n });\n }\n\n private writeValueTypeLabel(\n encoder: DirectionalIndexByteEncoder,\n typeOrder: number\n ): void {\n encoder.writeNumber(typeOrder);\n }\n\n private writeTruncationMarker(encoder: DirectionalIndexByteEncoder): void {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n encoder.writeNumber(NOT_TRUNCATED);\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 | agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n/** These constants are taken from the backend. */\nconst MIN_SURROGATE = '\\uD800';\nconst MAX_SURROGATE = '\\uDBFF';\n\nconst ESCAPE1 = 0x00;\nconst NULL_BYTE = 0xff; // Combined with ESCAPE1\nconst SEPARATOR = 0x01; // Combined with ESCAPE1\n\nconst ESCAPE2 = 0xff;\nconst INFINITY = 0xff; // Combined with ESCAPE2\nconst FF_BYTE = 0x00; // Combined with ESCAPE2\n\nconst LONG_SIZE = 64;\nconst BYTE_SIZE = 8;\n\n/**\n * The default size of the buffer. This is arbitrary, but likely larger than\n * most index values so that less copies of the underlying buffer will be made.\n * For large values, a single copy will made to double the buffer length.\n */\nconst DEFAULT_BUFFER_SIZE = 1024;\n\n/** Converts a JavaScript number to a byte array (using big endian encoding). */\nfunction doubleToLongBits(value: number): Uint8Array {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value, /* littleEndian= */ false);\n return new Uint8Array(dv.buffer);\n}\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nexport function numberOfLeadingZerosInByte(x: number): number {\n debugAssert(x < 256, 'Provided value is not a byte: ' + x);\n if (x === 0) {\n return 8;\n }\n\n let zeros = 0;\n if (x >> 4 === 0) {\n // Test if the first four bits are zero.\n zeros += 4;\n x = x << 4;\n }\n if (x >> 6 === 0) {\n // Test if the first two (or next two) bits are zero.\n zeros += 2;\n x = x << 2;\n }\n if (x >> 7 === 0) {\n // Test if the remaining bit is zero.\n zeros += 1;\n }\n return zeros;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\nfunction numberOfLeadingZeros(bytes: Uint8Array): number {\n debugAssert(\n bytes.length === 8,\n 'Can only count leading zeros in 64-bit numbers'\n );\n let leadingZeros = 0;\n for (let i = 0; i < 8; ++i) {\n const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff);\n leadingZeros += zeros;\n if (zeros !== 8) {\n break;\n }\n }\n return leadingZeros;\n}\n\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction unsignedNumLength(value: Uint8Array): number {\n // This is just the number of bytes for the unsigned representation of the number.\n const numBits = LONG_SIZE - numberOfLeadingZeros(value);\n return Math.ceil(numBits / BYTE_SIZE);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */\nexport class OrderedCodeWriter {\n buffer = new Uint8Array(DEFAULT_BUFFER_SIZE);\n position = 0;\n\n writeBytesAscending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteAscending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorAscending();\n }\n\n writeBytesDescending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteDescending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorDescending();\n }\n\n /** Writes utf8 bytes into this byte sequence, ascending. */\n writeUtf8Ascending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteAscending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteAscending((0x0f << 6) | (charCode >>> 6));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteAscending((0x0f << 5) | (charCode >>> 12));\n this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteAscending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorAscending();\n }\n\n /** Writes utf8 bytes into this byte sequence, descending */\n writeUtf8Descending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteDescending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteDescending((0x0f << 6) | (charCode >>> 6));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteDescending((0x0f << 5) | (charCode >>> 12));\n this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteDescending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorDescending();\n }\n\n writeNumberAscending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = len & 0xff; // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = value[i] & 0xff;\n }\n }\n\n writeNumberDescending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = ~(len & 0xff); // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = ~(value[i] & 0xff);\n }\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */\n writeInfinityAscending(): void {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(INFINITY);\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */\n writeInfinityDescending(): void {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(INFINITY);\n }\n\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */\n reset(): void {\n this.position = 0;\n }\n\n seed(encodedBytes: Uint8Array): void {\n this.ensureAvailable(encodedBytes.length);\n this.buffer.set(encodedBytes, this.position);\n this.position += encodedBytes.length;\n }\n\n /** Makes a copy of the encoded bytes in this buffer. */\n encodedBytes(): Uint8Array {\n return this.buffer.slice(0, this.position);\n }\n\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */\n private toOrderedBits(val: number): Uint8Array {\n const value = doubleToLongBits(val);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n const isNegative = (value[0] & 0x80) !== 0;\n\n // Revert the two complement to get natural ordering\n value[0] ^= isNegative ? 0xff : 0x80;\n for (let i = 1; i < value.length; ++i) {\n value[i] ^= isNegative ? 0xff : 0x00;\n }\n return value;\n }\n\n /** Writes a single byte ascending to the buffer. */\n private writeByteAscending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(FF_BYTE);\n } else {\n this.writeEscapedByteAscending(masked);\n }\n }\n\n /** Writes a single byte descending to the buffer. */\n private writeByteDescending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(FF_BYTE);\n } else {\n this.writeEscapedByteDescending(b);\n }\n }\n\n private writeSeparatorAscending(): void {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(SEPARATOR);\n }\n\n private writeSeparatorDescending(): void {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(SEPARATOR);\n }\n\n private writeEscapedByteAscending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = b;\n }\n\n private writeEscapedByteDescending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = ~b;\n }\n\n private ensureAvailable(bytes: number): void {\n const minCapacity = bytes + this.position;\n if (minCapacity <= this.buffer.length) {\n return;\n }\n // Try doubling.\n let newLength = this.buffer.length * 2;\n // Still not big enough? Just allocate the right size.\n if (newLength < minCapacity) {\n newLength = minCapacity;\n }\n // Create the new buffer.\n const newBuffer = new Uint8Array(newLength);\n newBuffer.set(this.buffer); // copy old data\n this.buffer = newBuffer;\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 */\nimport { IndexKind } from '../model/field_index';\nimport { ByteString } from '../util/byte_string';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\nimport { OrderedCodeWriter } from './ordered_code_writer';\n\nclass AscendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesAscending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Ascending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberAscending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityAscending();\n }\n}\n\nclass DescendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesDescending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Descending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberDescending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityDescending();\n }\n}\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */\nexport class IndexByteEncoder {\n private orderedCode = new OrderedCodeWriter();\n private ascending = new AscendingIndexByteEncoder(this.orderedCode);\n private descending = new DescendingIndexByteEncoder(this.orderedCode);\n\n seed(encodedBytes: Uint8Array): void {\n this.orderedCode.seed(encodedBytes);\n }\n\n forKind(kind: IndexKind): DirectionalIndexByteEncoder {\n return kind === IndexKind.ASCENDING ? this.ascending : this.descending;\n }\n\n encodedBytes(): Uint8Array {\n return this.orderedCode.encodedBytes();\n }\n\n reset(): void {\n this.orderedCode.reset();\n }\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 { DocumentKey } from '../model/document_key';\n\n/** Represents an index entry saved by the SDK in persisted storage. */\nexport class IndexEntry {\n constructor(\n readonly indexId: number,\n readonly documentKey: DocumentKey,\n readonly arrayValue: Uint8Array,\n readonly directionalValue: Uint8Array\n ) {}\n\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */\n successor(): IndexEntry {\n const currentLength = this.directionalValue.length;\n const newLength =\n currentLength === 0 || this.directionalValue[currentLength - 1] === 255\n ? currentLength + 1\n : currentLength;\n\n const successor = new Uint8Array(newLength);\n successor.set(this.directionalValue, 0);\n if (newLength !== currentLength) {\n successor.set([0], this.directionalValue.length);\n } else {\n ++successor[successor.length - 1];\n }\n\n return new IndexEntry(\n this.indexId,\n this.documentKey,\n this.arrayValue,\n successor\n );\n }\n}\n\nexport function indexEntryComparator(\n left: IndexEntry,\n right: IndexEntry\n): number {\n let cmp = left.indexId - right.indexId;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left.arrayValue, right.arrayValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left.directionalValue, right.directionalValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n return DocumentKey.comparator(left.documentKey, right.documentKey);\n}\n\nexport function compareByteArrays(left: Uint8Array, right: Uint8Array): number {\n for (let i = 0; i < left.length && i < right.length; ++i) {\n const compare = left[i] - right[i];\n if (compare !== 0) {\n return compare;\n }\n }\n return left.length - right.length;\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 { FieldFilter, Operator } from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { Target } from '../core/target';\nimport { hardAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind,\n IndexSegment,\n IndexState\n} from './field_index';\nimport { FieldPath } from './path';\n\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */\nexport class TargetIndexMatcher {\n // The collection ID (or collection group) of the query target.\n private readonly collectionId: string;\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n private inequalityFilters = new SortedSet((lhs, rhs) =>\n FieldPath.comparator(lhs.field, rhs.field)\n );\n\n // The list of equality filters of the target.\n private readonly equalityFilters: FieldFilter[];\n // The list of orderBys of the target.\n private readonly orderBys: OrderBy[];\n\n constructor(target: Target) {\n this.collectionId =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n this.orderBys = target.orderBy;\n this.equalityFilters = [];\n for (const filter of target.filters) {\n const fieldFilter = filter as FieldFilter;\n if (fieldFilter.isInequality()) {\n this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n } else {\n this.equalityFilters.push(fieldFilter);\n }\n }\n }\n\n get hasMultipleInequality(): boolean {\n return this.inequalityFilters.size > 1;\n }\n\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */\n servedByIndex(index: FieldIndex): boolean {\n hardAssert(\n index.collectionGroup === this.collectionId,\n 'Collection IDs do not match'\n );\n\n if (this.hasMultipleInequality) {\n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return false;\n }\n\n // If there is an array element, find a matching filter.\n const arraySegment = fieldIndexGetArraySegment(index);\n if (\n arraySegment !== undefined &&\n !this.hasMatchingEqualityFilter(arraySegment)\n ) {\n return false;\n }\n\n const segments = fieldIndexGetDirectionalSegments(index);\n let equalitySegments = new Set();\n let segmentIndex = 0;\n let orderBysIndex = 0;\n\n // Process all equalities first. Equalities can appear out of order.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n // We attempt to greedily match all segments to equality filters. If a\n // filter matches an index segment, we can mark the segment as used.\n if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n equalitySegments = equalitySegments.add(\n segments[segmentIndex].fieldPath.canonicalString()\n );\n } else {\n // If we cannot find a matching filter, we need to verify whether the\n // remaining segments map to the target's inequality and its orderBy\n // clauses.\n break;\n }\n }\n\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (segmentIndex === segments.length) {\n return true;\n }\n\n if (this.inequalityFilters.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n const segment = segments[segmentIndex];\n\n if (\n !this.matchesFilter(inequalityFilter, segment) ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n ++segmentIndex;\n }\n\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n const segment = segments[segmentIndex];\n if (\n orderBysIndex >= this.orderBys.length ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */\n buildTargetIndex(): FieldIndex | null {\n if (this.hasMultipleInequality) {\n return null;\n }\n\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let uniqueFields = new SortedSet(FieldPath.comparator);\n const segments: IndexSegment[] = [];\n\n for (const filter of this.equalityFilters) {\n if (filter.field.isKeyField()) {\n continue;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n if (isArrayOperator) {\n segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n } else {\n if (uniqueFields.has(filter.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(filter.field);\n segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n }\n }\n\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const orderBy of this.orderBys) {\n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n if (orderBy.field.isKeyField()) {\n continue;\n }\n\n if (uniqueFields.has(orderBy.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(orderBy.field);\n\n segments.push(\n new IndexSegment(\n orderBy.field,\n orderBy.dir === Direction.ASCENDING\n ? IndexKind.ASCENDING\n : IndexKind.DESCENDING\n )\n );\n }\n\n return new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n this.collectionId,\n segments,\n IndexState.empty()\n );\n }\n\n private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n for (const filter of this.equalityFilters) {\n if (this.matchesFilter(filter, segment)) {\n return true;\n }\n }\n return false;\n }\n\n private matchesFilter(\n filter: FieldFilter | undefined,\n segment: IndexSegment\n ): boolean {\n if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n return false;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n }\n\n private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n if (!orderBy.field.isEqual(segment.fieldPath)) {\n return false;\n }\n return (\n (segment.kind === IndexKind.ASCENDING &&\n orderBy.dir === Direction.ASCENDING) ||\n (segment.kind === IndexKind.DESCENDING &&\n orderBy.dir === Direction.DESCENDING)\n );\n }\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 {\n CompositeFilter,\n compositeFilterIsConjunction,\n compositeFilterIsDisjunction,\n compositeFilterIsFlat,\n compositeFilterIsFlatConjunction,\n compositeFilterWithAddedFilters,\n CompositeOperator,\n FieldFilter,\n Filter,\n InFilter,\n Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n if (filter instanceof InFilter) {\n const expandedFilters =\n filter.value.arrayValue?.values?.map(value =>\n FieldFilter.create(filter.field, Operator.EQUAL, value)\n ) || [];\n\n return CompositeFilter.create(expandedFilters, CompositeOperator.OR);\n } else {\n // We have reached other kinds of field filters.\n return filter;\n }\n }\n\n // We have a composite filter.\n const expandedFilters = filter.filters.map(subfilter =>\n computeInExpansion(subfilter)\n );\n return CompositeFilter.create(expandedFilters, filter.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

    Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */\nexport function getDnfTerms(filter: CompositeFilter): Filter[] {\n if (filter.getFilters().length === 0) {\n return [];\n }\n\n const result: Filter = computeDistributedNormalForm(\n computeInExpansion(filter)\n );\n\n hardAssert(\n isDisjunctiveNormalForm(result),\n 'computeDistributedNormalForm did not result in disjunctive normal form'\n );\n\n if (isSingleFieldFilter(result) || isFlatConjunction(result)) {\n return [result];\n }\n\n return result.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */\nfunction isSingleFieldFilter(filter: Filter): boolean {\n return filter instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */\nfunction isFlatConjunction(filter: Filter): boolean {\n return (\n filter instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(filter)\n );\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

    In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

    For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n return (\n isSingleFieldFilter(filter) ||\n isFlatConjunction(filter) ||\n isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n filter: Filter\n): boolean {\n if (filter instanceof CompositeFilter) {\n if (compositeFilterIsDisjunction(filter)) {\n for (const subFilter of filter.getFilters()) {\n if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n if (filter.filters.length === 1) {\n return computeDistributedNormalForm(filter.filters[0]);\n }\n\n // Compute DNF for each of the subfilters first\n const result = filter.filters.map(subfilter =>\n computeDistributedNormalForm(subfilter)\n );\n\n let newFilter: Filter = CompositeFilter.create(result, filter.op);\n newFilter = applyAssociation(newFilter);\n\n if (isDisjunctiveNormalForm(newFilter)) {\n return newFilter;\n }\n\n hardAssert(\n newFilter instanceof CompositeFilter,\n 'field filters are already in DNF form'\n );\n hardAssert(\n compositeFilterIsConjunction(newFilter),\n 'Disjunction of filters all of which are already in DNF form is itself in DNF form.'\n );\n hardAssert(\n newFilter.filters.length > 1,\n 'Single-filter composite filters are already in DNF form.'\n );\n\n return newFilter.filters.reduce((runningResult, filter) =>\n applyDistribution(runningResult, filter)\n );\n}\n\nexport function applyDistribution(lhs: Filter, rhs: Filter): Filter {\n hardAssert(\n lhs instanceof FieldFilter || lhs instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n hardAssert(\n rhs instanceof FieldFilter || rhs instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n let result: Filter;\n\n if (lhs instanceof FieldFilter) {\n if (rhs instanceof FieldFilter) {\n // FieldFilter FieldFilter\n result = applyDistributionFieldFilters(lhs, rhs);\n } else {\n // FieldFilter CompositeFilter\n result = applyDistributionFieldAndCompositeFilters(lhs, rhs);\n }\n } else {\n if (rhs instanceof FieldFilter) {\n // CompositeFilter FieldFilter\n result = applyDistributionFieldAndCompositeFilters(rhs, lhs);\n } else {\n // CompositeFilter CompositeFilter\n result = applyDistributionCompositeFilters(lhs, rhs);\n }\n }\n\n return applyAssociation(result);\n}\n\nfunction applyDistributionFieldFilters(\n lhs: FieldFilter,\n rhs: FieldFilter\n): Filter {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([lhs, rhs], CompositeOperator.AND);\n}\n\nfunction applyDistributionCompositeFilters(\n lhs: CompositeFilter,\n rhs: CompositeFilter\n): Filter {\n hardAssert(\n lhs.filters.length > 0 && rhs.filters.length > 0,\n 'Found an empty composite filter'\n );\n\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n\n // Case 1 is a merge.\n if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {\n return compositeFilterWithAddedFilters(lhs, rhs.getFilters());\n }\n\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;\n const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;\n const results = disjunctionSide.filters.map(subfilter =>\n applyDistribution(subfilter, otherSide)\n );\n return CompositeFilter.create(results, CompositeOperator.OR);\n}\n\nfunction applyDistributionFieldAndCompositeFilters(\n fieldFilter: FieldFilter,\n compositeFilter: CompositeFilter\n): Filter {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (compositeFilterIsConjunction(compositeFilter)) {\n // Case 1\n return compositeFilterWithAddedFilters(\n compositeFilter,\n fieldFilter.getFilters()\n );\n } else {\n // Case 2\n const newFilters = compositeFilter.filters.map(subfilter =>\n applyDistribution(fieldFilter, subfilter)\n );\n\n return CompositeFilter.create(newFilters, CompositeOperator.OR);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

      \n *
    • A | (B | C) == (A | B) | C == (A | B | C)\n *
    • A & (B & C) == (A & B) & C == (A & B & C)\n *
    \n *\n *

    For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n const filters = filter.getFilters();\n\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (filters.length === 1) {\n return applyAssociation(filters[0]);\n }\n\n // Associativity applied to a flat composite filter results is itself.\n if (compositeFilterIsFlat(filter)) {\n return filter;\n }\n\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));\n\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n const newSubfilters: Filter[] = [];\n updatedFilters.forEach(subfilter => {\n if (subfilter instanceof FieldFilter) {\n newSubfilters.push(subfilter);\n } else if (subfilter instanceof CompositeFilter) {\n if (subfilter.op === filter.op) {\n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n newSubfilters.push(...subfilter.filters);\n } else {\n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n newSubfilters.push(subfilter);\n }\n }\n });\n\n if (newSubfilters.length === 1) {\n return newSubfilters[0];\n }\n\n return CompositeFilter.create(newSubfilters, filter.op);\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 { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\n this.collectionParentIndex.add(collectionPath);\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise {\n return PersistencePromise.resolve(\n this.collectionParentIndex.getEntries(collectionId)\n );\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(IndexType.NONE);\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve([]);\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */\nexport class MemoryCollectionParentIndex {\n private index = {} as {\n [collectionId: string]: SortedSet;\n };\n\n // Returns false if the entry already existed.\n add(collectionPath: ResourcePath): boolean {\n debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents =\n this.index[collectionId] ||\n new SortedSet(ResourcePath.comparator);\n const added = !existingParents.has(parentPath);\n this.index[collectionId] = existingParents.add(parentPath);\n return added;\n }\n\n has(collectionPath: ResourcePath): boolean {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents = this.index[collectionId];\n return existingParents && existingParents.has(parentPath);\n }\n\n getEntries(collectionId: string): ResourcePath[] {\n const parentPaths =\n this.index[collectionId] ||\n new SortedSet(ResourcePath.comparator);\n return parentPaths.toArray();\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\nimport { User } from '../auth/user';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport {\n canonifyTarget,\n newTarget,\n Target,\n targetEquals,\n targetGetArrayValues,\n targetGetLowerBound,\n targetGetNotInValues,\n targetGetSegmentCount,\n targetGetUpperBound,\n targetHasLimit\n} from '../core/target';\nimport { FirestoreIndexValueWriter } from '../index/firestore_index_value_writer';\nimport { IndexByteEncoder } from '../index/index_byte_encoder';\nimport { IndexEntry, indexEntryComparator } from '../index/index_entry';\nimport { documentKeySet, DocumentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n fieldIndexGetKeyOrder,\n fieldIndexToString,\n IndexKind,\n IndexOffset,\n indexOffsetComparator,\n IndexSegment\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { TargetIndexMatcher } from '../model/target_index_matcher';\nimport { isArray, refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { getDnfTerms } from '../util/logic_utils';\nimport { immediateSuccessor, primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { diffSortedSets, SortedSet } from '../util/sorted_set';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexManager, IndexType } from './index_manager';\nimport {\n DbCollectionParent,\n DbIndexConfiguration,\n DbIndexEntry,\n DbIndexState\n} from './indexeddb_schema';\nimport {\n DbCollectionParentKey,\n DbCollectionParentStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationKey,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryKey,\n DbIndexEntryStore,\n DbIndexStateKey,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbIndexConfiguration,\n toDbIndexConfiguration,\n toDbIndexState\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nconst LOG_TAG = 'IndexedDbIndexManager';\n\nconst EMPTY_VALUE = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nexport class IndexedDbIndexManager implements IndexManager {\n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n private collectionParentsCache = new MemoryCollectionParentIndex();\n\n private readonly uid: string;\n\n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n private targetToDnfSubTargets = new ObjectMap(\n t => canonifyTarget(t),\n (l, r) => targetEquals(l, r)\n );\n\n constructor(user: User, private readonly databaseId: DatabaseId) {\n this.uid = user.uid || '';\n }\n\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\n debugAssert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n if (!this.collectionParentsCache.has(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n\n transaction.addOnCommittedListener(() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.collectionParentsCache.add(collectionPath);\n });\n\n const collectionParent: DbCollectionParent = {\n collectionId,\n parent: encodeResourcePath(parentPath)\n };\n return collectionParentsStore(transaction).put(collectionParent);\n }\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise {\n const parentPaths = [] as ResourcePath[];\n const range = IDBKeyRange.bound(\n [collectionId, ''],\n [immediateSuccessor(collectionId), ''],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return collectionParentsStore(transaction)\n .loadAll(range)\n .next(entries => {\n for (const entry of entries) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (entry.collectionId !== collectionId) {\n break;\n }\n parentPaths.push(decodeResourcePath(entry.parent));\n }\n return parentPaths;\n });\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const indexes = indexConfigurationStore(transaction);\n const dbIndex = toDbIndexConfiguration(index);\n delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb\n const result = indexes.add(dbIndex);\n if (index.indexState) {\n const states = indexStateStore(transaction);\n return result.next(indexId => {\n states.put(\n toDbIndexState(\n indexId,\n this.uid,\n index.indexState.sequenceNumber,\n index.indexState.offset\n )\n );\n });\n } else {\n return result.next();\n }\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n const entries = indexEntriesStore(transaction);\n return indexes\n .delete(index.indexId)\n .next(() =>\n states.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n )\n .next(() =>\n entries.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n );\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const indexes = indexConfigurationStore(transaction);\n const entries = indexEntriesStore(transaction);\n const states = indexStateStore(transaction);\n\n return indexes\n .deleteAll()\n .next(() => entries.deleteAll())\n .next(() => states.deleteAll());\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getIndexType(transaction, subTarget).next(type => {\n if (type === IndexType.NONE || type === IndexType.PARTIAL) {\n const targetIndexMatcher = new TargetIndexMatcher(subTarget);\n const fieldIndex = targetIndexMatcher.buildTargetIndex();\n if (fieldIndex != null) {\n return this.addFieldIndex(transaction, fieldIndex);\n }\n }\n });\n }\n );\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n const indexEntries = indexEntriesStore(transaction);\n\n let canServeTarget = true;\n const indexes = new Map();\n\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getFieldIndex(transaction, subTarget).next(index => {\n canServeTarget &&= !!index;\n indexes.set(subTarget, index);\n });\n }\n ).next(() => {\n if (!canServeTarget) {\n return PersistencePromise.resolve(null as DocumentKey[] | null);\n } else {\n let existingKeys = documentKeySet();\n const result: DocumentKey[] = [];\n return PersistencePromise.forEach(indexes, (index, subTarget) => {\n logDebug(\n LOG_TAG,\n `Using index ${fieldIndexToString(\n index!\n )} to execute ${canonifyTarget(target)}`\n );\n\n const arrayValues = targetGetArrayValues(subTarget, index!);\n const notInValues = targetGetNotInValues(subTarget, index!);\n const lowerBound = targetGetLowerBound(subTarget, index!);\n const upperBound = targetGetUpperBound(subTarget, index!);\n\n const lowerBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n lowerBound\n );\n const upperBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n upperBound\n );\n const notInEncoded = this.encodeValues(\n index!,\n subTarget,\n notInValues\n );\n\n const indexRanges = this.generateIndexRanges(\n index!.indexId,\n arrayValues,\n lowerBoundEncoded,\n lowerBound.inclusive,\n upperBoundEncoded,\n upperBound.inclusive,\n notInEncoded\n );\n return PersistencePromise.forEach(\n indexRanges,\n (indexRange: IDBKeyRange) => {\n return indexEntries\n .loadFirst(indexRange, target.limit)\n .next(entries => {\n entries.forEach(entry => {\n const documentKey = DocumentKey.fromSegments(\n entry.documentKey\n );\n if (!existingKeys.has(documentKey)) {\n existingKeys = existingKeys.add(documentKey);\n result.push(documentKey);\n }\n });\n });\n }\n );\n }).next(() => result as DocumentKey[] | null);\n }\n });\n }\n\n private getSubTargets(target: Target): Target[] {\n let subTargets = this.targetToDnfSubTargets.get(target);\n if (subTargets) {\n return subTargets;\n }\n\n if (target.filters.length === 0) {\n subTargets = [target];\n } else {\n // There is an implicit AND operation between all the filters stored in the target\n const dnf: Filter[] = getDnfTerms(\n CompositeFilter.create(target.filters, CompositeOperator.AND)\n );\n\n subTargets = dnf.map(term =>\n newTarget(\n target.path,\n target.collectionGroup,\n target.orderBy,\n term.getFilters(),\n target.limit,\n target.startAt,\n target.endAt\n )\n );\n }\n\n this.targetToDnfSubTargets.set(target, subTargets);\n return subTargets;\n }\n\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */\n private generateIndexRanges(\n indexId: number,\n arrayValues: ProtoValue[] | null,\n lowerBounds: Uint8Array[],\n lowerBoundInclusive: boolean,\n upperBounds: Uint8Array[],\n upperBoundInclusive: boolean,\n notInValues: Uint8Array[]\n ): IDBKeyRange[] {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const totalScans =\n (arrayValues != null ? arrayValues.length : 1) *\n Math.max(lowerBounds.length, upperBounds.length);\n const scansPerArrayElement =\n totalScans / (arrayValues != null ? arrayValues.length : 1);\n\n const indexRanges: IDBKeyRange[] = [];\n for (let i = 0; i < totalScans; ++i) {\n const arrayValue = arrayValues\n ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement])\n : EMPTY_VALUE;\n\n const lowerBound = this.generateLowerBound(\n indexId,\n arrayValue,\n lowerBounds[i % scansPerArrayElement],\n lowerBoundInclusive\n );\n const upperBound = this.generateUpperBound(\n indexId,\n arrayValue,\n upperBounds[i % scansPerArrayElement],\n upperBoundInclusive\n );\n\n const notInBound = notInValues.map(notIn =>\n this.generateLowerBound(\n indexId,\n arrayValue,\n notIn,\n /* inclusive= */ true\n )\n );\n\n indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound));\n }\n\n return indexRanges;\n }\n\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */\n private generateLowerBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry : entry.successor();\n }\n\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */\n private generateUpperBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry.successor() : entry;\n }\n\n private getFieldIndex(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n const targetIndexMatcher = new TargetIndexMatcher(target);\n const collectionGroup =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n\n return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {\n // Return the index with the most number of segments.\n let index: FieldIndex | null = null;\n for (const candidate of indexes) {\n const matches = targetIndexMatcher.servedByIndex(candidate);\n if (\n matches &&\n (!index || candidate.fields.length > index.fields.length)\n ) {\n index = candidate;\n }\n }\n return index;\n });\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n let indexType = IndexType.FULL;\n const subTargets = this.getSubTargets(target);\n return PersistencePromise.forEach(subTargets, (target: Target) => {\n return this.getFieldIndex(transaction, target).next(index => {\n if (!index) {\n indexType = IndexType.NONE;\n } else if (\n indexType !== IndexType.NONE &&\n index.fields.length < targetGetSegmentCount(target)\n ) {\n indexType = IndexType.PARTIAL;\n }\n });\n }).next(() => {\n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n if (\n targetHasLimit(target) &&\n subTargets.length > 1 &&\n indexType === IndexType.FULL\n ) {\n return IndexType.PARTIAL;\n }\n\n return indexType;\n });\n }\n\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */\n private encodeDirectionalElements(\n fieldIndex: FieldIndex,\n document: Document\n ): Uint8Array | null {\n const encoder = new IndexByteEncoder();\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const field = document.data.field(segment.fieldPath);\n if (field == null) {\n return null;\n }\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n field,\n directionalEncoder\n );\n }\n return encoder.encodedBytes();\n }\n\n /** Encodes a single value to the ascending index format. */\n private encodeSingleElement(value: ProtoValue): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n encoder.forKind(IndexKind.ASCENDING)\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */\n private encodeDirectionalKey(\n fieldIndex: FieldIndex,\n documentKey: DocumentKey\n ): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n refValue(this.databaseId, documentKey),\n encoder.forKind(fieldIndexGetKeyOrder(fieldIndex))\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */\n private encodeValues(\n fieldIndex: FieldIndex,\n target: Target,\n values: ProtoValue[] | null\n ): Uint8Array[] {\n if (values === null) {\n return [];\n }\n\n let encoders: IndexByteEncoder[] = [];\n encoders.push(new IndexByteEncoder());\n\n let valueIdx = 0;\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const value = values[valueIdx++];\n for (const encoder of encoders) {\n if (this.isInFilter(target, segment.fieldPath) && isArray(value)) {\n encoders = this.expandIndexValues(encoders, segment, value);\n } else {\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n directionalEncoder\n );\n }\n }\n }\n return this.getEncodedBytes(encoders);\n }\n\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */\n private encodeBound(\n fieldIndex: FieldIndex,\n target: Target,\n bound: Bound\n ): Uint8Array[] {\n return this.encodeValues(fieldIndex, target, bound.position);\n }\n\n /** Returns the byte representation for the provided encoders. */\n private getEncodedBytes(encoders: IndexByteEncoder[]): Uint8Array[] {\n const result: Uint8Array[] = [];\n for (let i = 0; i < encoders.length; ++i) {\n result[i] = encoders[i].encodedBytes();\n }\n return result;\n }\n\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */\n private expandIndexValues(\n encoders: IndexByteEncoder[],\n segment: IndexSegment,\n value: ProtoValue\n ): IndexByteEncoder[] {\n const prefixes = [...encoders];\n const results: IndexByteEncoder[] = [];\n for (const arrayElement of value.arrayValue!.values || []) {\n for (const prefix of prefixes) {\n const clonedEncoder = new IndexByteEncoder();\n clonedEncoder.seed(prefix.encodedBytes());\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n arrayElement,\n clonedEncoder.forKind(segment.kind)\n );\n results.push(clonedEncoder);\n }\n }\n return results;\n }\n\n private isInFilter(target: Target, fieldPath: FieldPath): boolean {\n return !!target.filters.find(\n f =>\n f instanceof FieldFilter &&\n f.field.isEqual(fieldPath) &&\n (f.op === Operator.IN || f.op === Operator.NOT_IN)\n );\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n\n return (\n collectionGroup\n ? indexes.loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n : indexes.loadAll()\n ).next(indexConfigs => {\n const result: FieldIndex[] = [];\n return PersistencePromise.forEach(\n indexConfigs,\n (indexConfig: DbIndexConfiguration) => {\n return states\n .get([indexConfig.indexId!, this.uid])\n .next(indexState => {\n result.push(fromDbIndexConfiguration(indexConfig, indexState));\n });\n }\n ).next(() => result);\n });\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.getFieldIndexes(transaction).next(indexes => {\n if (indexes.length === 0) {\n return null;\n }\n indexes.sort((l, r) => {\n const cmp = l.indexState.sequenceNumber - r.indexState.sequenceNumber;\n return cmp !== 0\n ? cmp\n : primitiveComparator(l.collectionGroup, r.collectionGroup);\n });\n return indexes[0].collectionGroup;\n });\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n return this.getNextSequenceNumber(transaction).next(nextSequenceNumber =>\n indexes\n .loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n .next(configs =>\n PersistencePromise.forEach(configs, (config: DbIndexConfiguration) =>\n states.put(\n toDbIndexState(\n config.indexId!,\n this.uid,\n nextSequenceNumber,\n offset\n )\n )\n )\n )\n );\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const memoizedIndexes = new Map();\n return PersistencePromise.forEach(documents, (key, doc) => {\n const memoizedCollectionIndexes = memoizedIndexes.get(\n key.collectionGroup\n );\n const fieldIndexes = memoizedCollectionIndexes\n ? PersistencePromise.resolve(memoizedCollectionIndexes)\n : this.getFieldIndexes(transaction, key.collectionGroup);\n\n return fieldIndexes.next(fieldIndexes => {\n memoizedIndexes.set(key.collectionGroup, fieldIndexes);\n return PersistencePromise.forEach(\n fieldIndexes,\n (fieldIndex: FieldIndex) => {\n return this.getExistingIndexEntries(\n transaction,\n key,\n fieldIndex\n ).next(existingEntries => {\n const newEntries = this.computeIndexEntries(doc, fieldIndex);\n if (!existingEntries.isEqual(newEntries)) {\n return this.updateEntries(\n transaction,\n doc,\n fieldIndex,\n existingEntries,\n newEntries\n );\n }\n return PersistencePromise.resolve();\n });\n }\n );\n });\n });\n }\n\n private addIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.put({\n indexId: indexEntry.indexId,\n uid: this.uid,\n arrayValue: indexEntry.arrayValue,\n directionalValue: indexEntry.directionalValue,\n orderedDocumentKey: this.encodeDirectionalKey(fieldIndex, document.key),\n documentKey: document.key.path.toArray()\n });\n }\n\n private deleteIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.delete([\n indexEntry.indexId,\n this.uid,\n indexEntry.arrayValue,\n indexEntry.directionalValue,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key.path.toArray()\n ]);\n }\n\n private getExistingIndexEntries(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n fieldIndex: FieldIndex\n ): PersistencePromise> {\n const indexEntries = indexEntriesStore(transaction);\n let results = new SortedSet(indexEntryComparator);\n return indexEntries\n .iterate(\n {\n index: DbIndexEntryDocumentKeyIndex,\n range: IDBKeyRange.only([\n fieldIndex.indexId,\n this.uid,\n this.encodeDirectionalKey(fieldIndex, documentKey)\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n entry.arrayValue,\n entry.directionalValue\n )\n );\n }\n )\n .next(() => results);\n }\n\n /** Creates the index entries for the given document. */\n private computeIndexEntries(\n document: Document,\n fieldIndex: FieldIndex\n ): SortedSet {\n let results = new SortedSet(indexEntryComparator);\n\n const directionalValue = this.encodeDirectionalElements(\n fieldIndex,\n document\n );\n if (directionalValue == null) {\n return results;\n }\n\n const arraySegment = fieldIndexGetArraySegment(fieldIndex);\n if (arraySegment != null) {\n const value = document.data.field(arraySegment.fieldPath);\n if (isArray(value)) {\n for (const arrayValue of value.arrayValue!.values || []) {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n this.encodeSingleElement(arrayValue),\n directionalValue\n )\n );\n }\n }\n } else {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n EMPTY_VALUE,\n directionalValue\n )\n );\n }\n\n return results;\n }\n\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */\n private updateEntries(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n existingEntries: SortedSet,\n newEntries: SortedSet\n ): PersistencePromise {\n logDebug(LOG_TAG, \"Updating index entries for document '%s'\", document.key);\n\n const promises: Array> = [];\n diffSortedSets(\n existingEntries,\n newEntries,\n indexEntryComparator,\n /* onAdd= */ entry => {\n promises.push(\n this.addIndexEntry(transaction, document, fieldIndex, entry)\n );\n },\n /* onRemove= */ entry => {\n promises.push(\n this.deleteIndexEntry(transaction, document, fieldIndex, entry)\n );\n }\n );\n\n return PersistencePromise.waitFor(promises);\n }\n\n private getNextSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n let nextSequenceNumber = 1;\n const states = indexStateStore(transaction);\n return states\n .iterate(\n {\n index: DbIndexStateSequenceNumberIndex,\n reverse: true,\n range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])\n },\n (_, state, controller) => {\n controller.done();\n nextSequenceNumber = state.sequenceNumber + 1;\n }\n )\n .next(() => nextSequenceNumber);\n }\n\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */\n private createRange(\n lower: IndexEntry,\n upper: IndexEntry,\n notInValues: IndexEntry[]\n ): IDBKeyRange[] {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n notInValues = notInValues\n .sort((l, r) => indexEntryComparator(l, r))\n .filter(\n (el, i, values) => !i || indexEntryComparator(el, values[i - 1]) !== 0\n );\n\n const bounds: IndexEntry[] = [];\n bounds.push(lower);\n for (const notInValue of notInValues) {\n const cmpToLower = indexEntryComparator(notInValue, lower);\n const cmpToUpper = indexEntryComparator(notInValue, upper);\n\n if (cmpToLower === 0) {\n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n bounds[0] = lower.successor();\n } else if (cmpToLower > 0 && cmpToUpper < 0) {\n // `notInValue` is in the middle of the range\n bounds.push(notInValue);\n bounds.push(notInValue.successor());\n } else if (cmpToUpper > 0) {\n // `notInValue` (and all following values) are out of the range\n break;\n }\n }\n bounds.push(upper);\n\n const ranges: IDBKeyRange[] = [];\n for (let i = 0; i < bounds.length; i += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.isRangeMatchable(bounds[i], bounds[i + 1])) {\n return [];\n }\n\n const lowerBound = [\n bounds[i].indexId,\n this.uid,\n bounds[i].arrayValue,\n bounds[i].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n const upperBound = [\n bounds[i + 1].indexId,\n this.uid,\n bounds[i + 1].arrayValue,\n bounds[i + 1].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n ranges.push(IDBKeyRange.bound(lowerBound, upperBound));\n }\n return ranges;\n }\n\n isRangeMatchable(lowerBound: IndexEntry, upperBound: IndexEntry): boolean {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return indexEntryComparator(lowerBound, upperBound) > 0;\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise {\n return this.getFieldIndexes(transaction, collectionGroup).next(\n getMinOffsetFromFieldIndexes\n );\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n return PersistencePromise.mapArray(\n this.getSubTargets(target),\n (subTarget: Target) =>\n this.getFieldIndex(transaction, subTarget).next(index =>\n index ? index : fail('Target cannot be served from index')\n )\n ).next(getMinOffsetFromFieldIndexes);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */\nfunction collectionParentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbCollectionParentStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */\nfunction indexEntriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbIndexEntryStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */\nfunction indexConfigurationStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbIndexConfigurationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */\nfunction indexStateStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbIndexStateStore);\n}\n\nfunction getMinOffsetFromFieldIndexes(fieldIndexes: FieldIndex[]): IndexOffset {\n hardAssert(\n fieldIndexes.length !== 0,\n 'Found empty index group when looking for least recent index offset.'\n );\n\n let minOffset: IndexOffset = fieldIndexes[0].indexState.offset;\n let maxBatchId: number = minOffset.largestBatchId;\n for (let i = 1; i < fieldIndexes.length; i++) {\n const newOffset: IndexOffset = fieldIndexes[i].indexState.offset;\n if (indexOffsetComparator(newOffset, minOffset) < 0) {\n minOffset = newOffset;\n }\n if (maxBatchId < newOffset.largestBatchId) {\n maxBatchId = newOffset.largestBatchId;\n }\n }\n return new IndexOffset(minOffset.readTime, minOffset.documentKey, maxBatchId);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\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 { DocumentKey } from '../model/document_key';\nimport { fail, hardAssert } from '../util/assert';\n\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbRemoteDocument\n} from './indexeddb_schema';\nimport { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n newDbDocumentMutationKey\n} from './indexeddb_sentinels';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: { batchId: number; mutations: Array<{ key: DocumentKey }> }\n): PersistencePromise {\n const mutationStore = txn.store(\n DbMutationBatchStore\n );\n const indexTxn = txn.store(\n DbDocumentMutationStore\n );\n const promises: Array> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n hardAssert(\n numDeleted === 1,\n 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = newDbDocumentMutationKey(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Returns an approximate size for the given document.\n */\nexport function dbDocumentSize(\n doc: DbRemoteDocument | DbRemoteDocumentLegacy | null\n): number {\n if (!doc) {\n return 0;\n }\n\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail('Unknown remote document type');\n }\n return JSON.stringify(value).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 { User } from '../auth/user';\nimport { isCollectionGroupQuery, isDocumentQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { decodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { removeMutationBatch } from './indexeddb_mutation_batch_impl';\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue\n} from './indexeddb_schema';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationPlaceholder,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationQueueKey,\n DbMutationQueueStore,\n newDbDocumentMutationKey,\n newDbDocumentMutationPrefixForPath,\n newDbDocumentMutationPrefixForUser\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction, getStore } from './indexeddb_transaction';\nimport {\n fromDbMutationBatch,\n LocalSerializer,\n toDbMutationBatch\n} from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n hardAssert(user.uid !== '', 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n hardAssert(\n typeof batchId === 'number',\n 'Auto-generated key is not a number'\n );\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch);\n\n const promises: Array> = [];\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = newDbDocumentMutationKey(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutationPlaceholder)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n hardAssert(\n dbBatch.userId === this.userId,\n `Unexpected user '${dbBatch.userId}' for mutation batch ${batchId}`\n );\n return fromDbMutationBatch(this.serializer, dbBatch);\n }\n return null;\n });\n }\n\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n hardAssert(\n dbBatch.batchId >= nextBatchId,\n 'Should have found mutation after ' + nextBatchId\n );\n foundBatch = fromDbMutationBatch(this.serializer, dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 'Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n batchId\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n const promises: Array> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isDocumentQuery(query),\n \"Document queries shouldn't go down this path\"\n );\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet\n ): PersistencePromise {\n const results: MutationBatch[] = [];\n const promises: Array> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 'Dangling document-mutation reference found, ' +\n 'which points to ' +\n batchId\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n key\n );\n }\n );\n });\n }\n\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n newDbDocumentMutationPrefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = decodeResourcePath(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n hardAssert(\n danglingMutationReferences.length === 0,\n 'Document leak -- detected dangling mutation references when queue is empty. ' +\n 'Dangling keys: ' +\n danglingMutationReferences.map(p => p.canonicalString())\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\n\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata || {\n userId: this.userId,\n lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n lastStreamToken: ''\n }\n );\n });\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise {\n const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationBatchStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentMutationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationQueueStore\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentKey,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetQueryTargetsIndexName,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\n\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n metadata.highestTargetId = targetIdGenerator.next();\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion =\n lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n hardAssert(\n metadata.targetCount > 0,\n 'Removing from an empty target cache'\n );\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const promises: Array> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return globalTargetStore(transaction)\n .get(DbTargetGlobalKey)\n .next(metadata => {\n hardAssert(metadata !== null, 'Missing metadata row.');\n return metadata;\n });\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise {\n return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return targetsStore(transaction).put(\n toDbTarget(this.serializer, targetData)\n );\n }\n\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const canonicalId = canonifyTarget(target);\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTargetQueryTargetsIndexName },\n (key, value, control) => {\n const found = fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (targetEquals(target, found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = encodeResourcePath(key.path);\n promises.push(store.put({ targetId, path }));\n promises.push(this.referenceDelegate.addReference(txn, targetId, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = encodeResourcePath(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, targetId, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = decodeResourcePath(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const path = encodeResourcePath(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetGlobalStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbTargetDocumentStore\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 { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = new SortedSet(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\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 { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n decodeResourcePath,\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n documentTargetStore,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n ActiveTargets,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: Persistence, params: LruParams) {\n this.garbageCollector = newLruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return (this.db.getTargetCache() as IndexedDbTargetCache).removeTargets(\n txn,\n upperBound,\n activeTargetIds\n );\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise {\n return mutationQueuesContainKey(txn, docKey);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey, SnapshotVersion.min());\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }\n )\n .next(() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber };\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n private changesApplied = false;\n\n protected abstract getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise;\n\n protected abstract getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise;\n\n protected abstract applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n addEntry(document: MutableDocument): void {\n this.assertNotApplied();\n this.changes.set(document.key, document);\n }\n\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n removeEntry(key: DocumentKey, readTime: SnapshotVersion): void {\n this.assertNotApplied();\n this.changes.set(\n key,\n MutableDocument.newInvalidDocument(key).setReadTime(readTime)\n );\n }\n\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n this.assertNotApplied();\n const bufferedEntry = this.changes.get(documentKey);\n if (bufferedEntry !== undefined) {\n return PersistencePromise.resolve(bufferedEntry);\n } else {\n return this.getFromCache(transaction, documentKey);\n }\n }\n\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n return this.getAllFromCache(transaction, documentKeys);\n }\n\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n apply(transaction: PersistenceTransaction): PersistencePromise {\n this.assertNotApplied();\n this.changesApplied = true;\n return this.applyChanges(transaction);\n }\n\n /** Helper to assert this.changes is not null */\n protected assertNotApplied(): void {\n debugAssert(!this.changesApplied, 'Changes have already been applied.');\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentSizeEntries,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentStore,\n DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbRemoteDocument,\n LocalSerializer,\n toDbRemoteDocument,\n toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n document: MutableDocument;\n size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n indexManager!: IndexManager;\n\n constructor(readonly serializer: LocalSerializer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(doc);\n }\n\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n ): PersistencePromise {\n const store = remoteDocumentsStore(transaction);\n return store.delete(dbReadTimeKey(documentKey, readTime));\n }\n\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */\n updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let doc = MutableDocument.newInvalidDocument(documentKey);\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n }\n )\n .next(() => doc);\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let result = {\n size: 0,\n document: MutableDocument.newInvalidDocument(documentKey)\n };\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n result = {\n document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n };\n }\n )\n .next(() => result);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n let sizeMap = new SortedMap(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n }\n ).next(() => {\n return { documents: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n let sortedKeys = new SortedSet(dbKeyComparator);\n documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n const range = IDBKeyRange.bound(\n dbKey(sortedKeys.first()!),\n dbKey(sortedKeys.last()!)\n );\n const keyIter = sortedKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate(\n { index: DbRemoteDocumentDocumentKeyIndex, range },\n (_, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments([\n ...dbRemoteDoc.prefixPath,\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n ]);\n\n // Go through keys not found in cache.\n while (nextKey && dbKeyComparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(dbKey(nextKey));\n } else {\n control.done();\n }\n }\n )\n .next(() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap,\n context?: QueryContext\n ): PersistencePromise {\n const collection = query.path;\n const startKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n toDbTimestampKey(offset.readTime),\n offset.documentKey.path.isEmpty()\n ? ''\n : offset.documentKey.path.lastSegment()\n ];\n const endKey: DbRemoteDocumentKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n ''\n ];\n\n return remoteDocumentsStore(transaction)\n .loadAll(IDBKeyRange.bound(startKey, endKey, true))\n .next(dbRemoteDocs => {\n context?.incrementDocumentReadCount(dbRemoteDocs.length);\n let results = mutableDocumentMap();\n for (const dbRemoteDoc of dbRemoteDocs) {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n if (\n document.isFoundDocument() &&\n (queryMatches(query, document) || mutatedDocs.has(document.key))\n ) {\n // Either the document matches the given query, or it is mutated.\n results = results.insert(document.key, document);\n }\n }\n return results;\n });\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limit: number\n ): PersistencePromise {\n debugAssert(limit > 0, 'Limit should be at least 1');\n let results = mutableDocumentMap();\n\n const startKey = dbCollectionGroupKey(collectionGroup, offset);\n const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentCollectionGroupIndex,\n range: IDBKeyRange.bound(startKey, endKey, true)\n },\n (_, dbRemoteDoc, control) => {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n results = results.insert(document.key, document);\n if (results.size === limit) {\n control.done();\n }\n }\n )\n .next(() => results);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobalKey)\n .next(metadata => {\n hardAssert(!!metadata, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata);\n }\n\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n documentKey: DocumentKey,\n dbRemoteDoc: DbRemoteDocument | null\n ): MutableDocument {\n if (dbRemoteDoc) {\n const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n const isSentinelRemoval =\n doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n if (!isSentinelRemoval) {\n return doc;\n }\n }\n return MutableDocument.newInvalidDocument(documentKey);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n return new IndexedDbRemoteDocumentCacheImpl(serializer);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n protected documentStates: ObjectMap<\n DocumentKey,\n { size: number; readTime: SnapshotVersion }\n > = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(\n private readonly documentCache: IndexedDbRemoteDocumentCacheImpl,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, documentChange) => {\n const previousDoc = this.documentStates.get(key);\n debugAssert(\n previousDoc !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n promises.push(\n this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n );\n if (documentChange.isValidDocument()) {\n debugAssert(\n !documentChange.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n const doc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousDoc.size;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousDoc.size;\n if (this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const deletedDoc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange.convertToNoDocument(SnapshotVersion.min())\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n this.documentStates.set(documentKey, {\n size: getResult.size,\n readTime: getResult.document.readTime\n });\n return getResult.document;\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ documents, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentStates.set(documentKey, {\n size,\n readTime: documents.get(documentKey)!.readTime\n });\n });\n return documents;\n });\n }\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentGlobalStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentStore\n );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n toDbTimestampKey(readTime),\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n collectionGroup: string,\n offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n const path = offset.documentKey.path.toArray();\n return [\n /* collection id */ collectionGroup,\n toDbTimestampKey(offset.readTime),\n /* prefix path */ path.slice(0, path.length - 2),\n /* document id */ path.length > 0 ? path[path.length - 1] : ''\n ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n const left = l.path.toArray();\n const right = r.path.toArray();\n\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let cmp = 0;\n for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n cmp = primitiveComparator(left[i], right[i]);\n if (cmp) {\n return cmp;\n }\n }\n\n cmp = primitiveComparator(left.length, right.length);\n if (cmp) {\n return cmp;\n }\n\n cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n if (cmp) {\n return cmp;\n }\n\n return primitiveComparator(left[left.length - 1], right[right.length - 1]);\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 { Document } from '../model/document';\nimport { FieldMask } from '../model/field_mask';\n\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nexport class OverlayedDocument {\n constructor(\n readonly overlayedDocument: Document,\n\n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n readonly mutatedFields: FieldMask | 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 */\n\nimport {\n asCollectionQueryAtPath,\n isCollectionGroupQuery,\n isDocumentQuery,\n Query,\n queryMatches\n} from '../core/query';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n DocumentKeySet,\n OverlayMap,\n DocumentMap,\n MutableDocumentMap,\n newDocumentKeyMap,\n newMutationMap,\n newOverlayMap,\n documentMap,\n mutableDocumentMap,\n documentKeySet,\n DocumentKeyMap,\n convertOverlayedDocumentMapToDocumentMap,\n OverlayedDocumentMap,\n newOverlayedDocumentMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset, INITIAL_LARGEST_BATCH_ID } from '../model/field_index';\nimport { FieldMask } from '../model/field_mask';\nimport {\n calculateOverlayMutation,\n mutationApplyToLocalView,\n PatchMutation\n} from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly documentOverlayCache: DocumentOverlayCache,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n let overlay: Overlay | null = null;\n return this.documentOverlayCache\n .getOverlay(transaction, key)\n .next(value => {\n overlay = value;\n return this.remoteDocumentCache.getEntry(transaction, key);\n })\n .next(document => {\n if (overlay !== null) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n return document as Document;\n });\n }\n\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */\n getDocuments(\n transaction: PersistenceTransaction,\n keys: DocumentKeySet\n ): PersistencePromise {\n return this.remoteDocumentCache\n .getEntries(transaction, keys)\n .next(docs =>\n this.getLocalViewOfDocuments(transaction, docs, documentKeySet()).next(\n () => docs as DocumentMap\n )\n );\n }\n\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */\n getLocalViewOfDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n existenceStateChanged: DocumentKeySet = documentKeySet()\n ): PersistencePromise {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() => {\n return this.computeViews(\n transaction,\n docs,\n overlays,\n existenceStateChanged\n ).next(computeViewsResult => {\n let result = documentMap();\n computeViewsResult.forEach((documentKey, overlayedDocument) => {\n result = result.insert(\n documentKey,\n overlayedDocument.overlayedDocument\n );\n });\n return result;\n });\n });\n }\n\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */\n getOverlayedDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() =>\n this.computeViews(transaction, docs, overlays, documentKeySet())\n );\n }\n\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */\n private populateOverlays(\n transaction: PersistenceTransaction,\n overlays: OverlayMap,\n docs: MutableDocumentMap\n ): PersistencePromise {\n const missingOverlays: DocumentKey[] = [];\n docs.forEach(key => {\n if (!overlays.has(key)) {\n missingOverlays.push(key);\n }\n });\n return this.documentOverlayCache\n .getOverlays(transaction, missingOverlays)\n .next(result => {\n result.forEach((key, val) => {\n overlays.set(key, val);\n });\n });\n }\n\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */\n computeViews(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n overlays: OverlayMap,\n existenceStateChanged: DocumentKeySet\n ): PersistencePromise {\n let recalculateDocuments = mutableDocumentMap();\n const mutatedFields = newDocumentKeyMap();\n const results = newOverlayedDocumentMap();\n docs.forEach((_, doc) => {\n const overlay = overlays.get(doc.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n if (\n existenceStateChanged.has(doc.key) &&\n (overlay === undefined || overlay.mutation instanceof PatchMutation)\n ) {\n recalculateDocuments = recalculateDocuments.insert(doc.key, doc);\n } else if (overlay !== undefined) {\n mutatedFields.set(doc.key, overlay.mutation.getFieldMask());\n mutationApplyToLocalView(\n overlay.mutation,\n doc,\n overlay.mutation.getFieldMask(),\n Timestamp.now()\n );\n } else {\n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n mutatedFields.set(doc.key, FieldMask.empty());\n }\n });\n\n return this.recalculateAndSaveOverlays(\n transaction,\n recalculateDocuments\n ).next(recalculatedFields => {\n recalculatedFields.forEach((documentKey, mask) =>\n mutatedFields.set(documentKey, mask)\n );\n docs.forEach((documentKey, document) =>\n results.set(\n documentKey,\n new OverlayedDocument(\n document,\n mutatedFields.get(documentKey) ?? null\n )\n )\n );\n return results;\n });\n }\n\n private recalculateAndSaveOverlays(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise> {\n const masks = newDocumentKeyMap();\n // A reverse lookup map from batch id to the documents within that batch.\n let documentsByBatchId = new SortedMap(\n (key1: number, key2: number) => key1 - key2\n );\n let processed = documentKeySet();\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKeys(transaction, docs)\n .next(batches => {\n for (const batch of batches) {\n batch.keys().forEach(key => {\n const baseDoc = docs.get(key);\n if (baseDoc === null) {\n return;\n }\n let mask: FieldMask | null = masks.get(key) || FieldMask.empty();\n mask = batch.applyToLocalView(baseDoc, mask);\n masks.set(key, mask);\n const newSet = (\n documentsByBatchId.get(batch.batchId) || documentKeySet()\n ).add(key);\n documentsByBatchId = documentsByBatchId.insert(\n batch.batchId,\n newSet\n );\n });\n }\n })\n .next(() => {\n const promises: Array> = [];\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n const iter = documentsByBatchId.getReverseIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const batchId = entry.key;\n const keys = entry.value;\n const overlays = newMutationMap();\n keys.forEach(key => {\n if (!processed.has(key)) {\n const overlayMutation = calculateOverlayMutation(\n docs.get(key)!,\n masks.get(key)!\n );\n if (overlayMutation !== null) {\n overlays.set(key, overlayMutation);\n }\n processed = processed.add(key);\n }\n });\n promises.push(\n this.documentOverlayCache.saveOverlays(\n transaction,\n batchId,\n overlays\n )\n );\n }\n return PersistencePromise.waitFor(promises);\n })\n .next(() => masks);\n }\n\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */\n recalculateAndSaveOverlaysForDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise> {\n return this.remoteDocumentCache\n .getEntries(transaction, documentKeys)\n .next(docs => this.recalculateAndSaveOverlays(transaction, docs));\n }\n\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n * @param context - A optional tracker to keep a record of important details\n * during database local query execution.\n */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise {\n if (isDocumentQuery(query)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n } else if (isCollectionGroupQuery(query)) {\n return this.getDocumentsMatchingCollectionGroupQuery(\n transaction,\n query,\n offset,\n context\n );\n } else {\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n query,\n offset,\n context\n );\n }\n }\n\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n *

    The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */\n getNextDocuments(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n count: number\n ): PersistencePromise {\n return this.remoteDocumentCache\n .getAllFromCollectionGroup(transaction, collectionGroup, offset, count)\n .next((originalDocs: MutableDocumentMap) => {\n const overlaysPromise: PersistencePromise =\n count - originalDocs.size > 0\n ? this.documentOverlayCache.getOverlaysForCollectionGroup(\n transaction,\n collectionGroup,\n offset.largestBatchId,\n count - originalDocs.size\n )\n : PersistencePromise.resolve(newOverlayMap());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let largestBatchId = INITIAL_LARGEST_BATCH_ID;\n let modifiedDocs = originalDocs;\n return overlaysPromise.next(overlays => {\n return PersistencePromise.forEach(\n overlays,\n (key: DocumentKey, overlay: Overlay) => {\n if (largestBatchId < overlay.largestBatchId) {\n largestBatchId = overlay.largestBatchId;\n }\n if (originalDocs.get(key)) {\n return PersistencePromise.resolve();\n }\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(doc => {\n modifiedDocs = modifiedDocs.insert(key, doc);\n });\n }\n )\n .next(() =>\n this.populateOverlays(transaction, overlays, originalDocs)\n )\n .next(() =>\n this.computeViews(\n transaction,\n modifiedDocs,\n overlays,\n documentKeySet()\n )\n )\n .next(localDocs => ({\n batchId: largestBatchId,\n changes: convertOverlayedDocumentMapToDocumentMap(localDocs)\n }));\n });\n });\n }\n\n private getDocumentsMatchingDocumentQuery(\n transaction: PersistenceTransaction,\n docPath: ResourcePath\n ): PersistencePromise {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(\n document => {\n let result = documentMap();\n if (document.isFoundDocument()) {\n result = result.insert(document.key, document);\n }\n return result;\n }\n );\n }\n\n private getDocumentsMatchingCollectionGroupQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise {\n debugAssert(\n query.path.isEmpty(),\n 'Currently we only support collection group queries at the root.'\n );\n const collectionId = query.collectionGroup!;\n let results = documentMap();\n return this.indexManager\n .getCollectionParents(transaction, collectionId)\n .next(parents => {\n // Perform a collection query against each parent that contains the\n // collectionId and aggregate the results.\n return PersistencePromise.forEach(parents, (parent: ResourcePath) => {\n const collectionQuery = asCollectionQueryAtPath(\n query,\n parent.child(collectionId)\n );\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n collectionQuery,\n offset,\n context\n ).next(r => {\n r.forEach((key, doc) => {\n results = results.insert(key, doc);\n });\n });\n }).next(() => results);\n });\n }\n\n private getDocumentsMatchingCollectionQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise {\n // Query the remote documents and overlay mutations.\n let overlays: OverlayMap;\n return this.documentOverlayCache\n .getOverlaysForCollection(transaction, query.path, offset.largestBatchId)\n .next(result => {\n overlays = result;\n return this.remoteDocumentCache.getDocumentsMatchingQuery(\n transaction,\n query,\n offset,\n overlays,\n context\n );\n })\n .next(remoteDocuments => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n overlays.forEach((_, overlay) => {\n const key = overlay.getKey();\n if (remoteDocuments.get(key) === null) {\n remoteDocuments = remoteDocuments.insert(\n key,\n MutableDocument.newInvalidDocument(key)\n );\n }\n });\n\n // Apply the overlays and match against the query.\n let results = documentMap();\n remoteDocuments.forEach((key, document) => {\n const overlay = overlays.get(key);\n if (overlay !== undefined) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n // Finally, insert the documents that still match the query\n if (queryMatches(query, document)) {\n results = results.insert(key, document);\n }\n });\n return results;\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 { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n NamedQuery as ProtoNamedQuery,\n BundleMetadata as ProtoBundleMetadata\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport {\n fromBundleMetadata,\n fromProtoNamedQuery,\n LocalSerializer\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\nexport class MemoryBundleCache implements BundleCache {\n private bundles = new Map();\n private namedQueries = new Map();\n\n constructor(private serializer: LocalSerializer) {}\n\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return PersistencePromise.resolve(this.bundles.get(bundleId));\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n this.bundles.set(bundleMetadata.id!, fromBundleMetadata(bundleMetadata));\n return PersistencePromise.resolve();\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return PersistencePromise.resolve(this.namedQueries.get(queryName));\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n this.namedQueries.set(query.name!, fromProtoNamedQuery(query));\n return PersistencePromise.resolve();\n }\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 {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */\nexport class MemoryDocumentOverlayCache implements DocumentOverlayCache {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n private overlays = new SortedMap(\n DocumentKey.comparator\n );\n private overlayByBatchId = new Map();\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.resolve(this.overlays.get(key));\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\n const result = newOverlayMap();\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n return this.getOverlay(transaction, key).next(overlay => {\n if (overlay !== null) {\n result.set(key, overlay);\n }\n });\n }).next(() => result);\n }\n\n saveOverlays(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n overlays: MutationMap\n ): PersistencePromise {\n overlays.forEach((_, mutation) => {\n this.saveOverlay(transaction, largestBatchId, mutation);\n });\n return PersistencePromise.resolve();\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const keys = this.overlayByBatchId.get(batchId);\n if (keys !== undefined) {\n keys.forEach(key => (this.overlays = this.overlays.remove(key)));\n this.overlayByBatchId.delete(batchId);\n }\n return PersistencePromise.resolve();\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n\n const immediateChildrenPathLength = collection.length + 1;\n const prefix = new DocumentKey(collection.child(''));\n const iter = this.overlays.getIteratorFrom(prefix);\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (!collection.isPrefixOf(key.path)) {\n break;\n }\n // Documents from sub-collections\n if (key.path.length !== immediateChildrenPathLength) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n result.set(overlay.getKey(), overlay);\n }\n }\n\n return PersistencePromise.resolve(result);\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n let batchIdToOverlays = new SortedMap(\n (key1: number, key2: number) => key1 - key2\n );\n\n const iter = this.overlays.getIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (key.getCollectionGroup() !== collectionGroup) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId);\n if (overlaysForBatchId === null) {\n overlaysForBatchId = newOverlayMap();\n batchIdToOverlays = batchIdToOverlays.insert(\n overlay.largestBatchId,\n overlaysForBatchId\n );\n }\n overlaysForBatchId.set(overlay.getKey(), overlay);\n }\n }\n\n const result = newOverlayMap();\n const batchIter = batchIdToOverlays.getIterator();\n while (batchIter.hasNext()) {\n const entry = batchIter.getNext();\n const overlays = entry.value;\n overlays.forEach((key, overlay) => result.set(key, overlay));\n if (result.size() >= count) {\n break;\n }\n }\n return PersistencePromise.resolve(result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n mutation: Mutation\n ): void {\n // Remove the association of the overlay to its batch id.\n const existing = this.overlays.get(mutation.key);\n if (existing !== null) {\n const newSet = this.overlayByBatchId\n .get(existing.largestBatchId)!\n .delete(mutation.key);\n this.overlayByBatchId.set(existing.largestBatchId, newSet);\n }\n\n this.overlays = this.overlays.insert(\n mutation.key,\n new Overlay(largestBatchId, mutation)\n );\n\n // Create the association of this overlay to the given largestBatchId.\n let batch = this.overlayByBatchId.get(largestBatchId);\n if (batch === undefined) {\n batch = documentKeySet();\n this.overlayByBatchId.set(largestBatchId, batch);\n }\n this.overlayByBatchId.set(largestBatchId, batch.add(mutation.key));\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, TargetId } from '../core/types';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */\nexport class ReferenceSet {\n // A set of outstanding references to a document sorted by key.\n private refsByKey = new SortedSet(DocReference.compareByKey);\n\n // A set of outstanding references to a document sorted by target id.\n private refsByTarget = new SortedSet(DocReference.compareByTargetId);\n\n /** Returns true if the reference set contains no references. */\n isEmpty(): boolean {\n return this.refsByKey.isEmpty();\n }\n\n /** Adds a reference to the given document key for the given ID. */\n addReference(key: DocumentKey, id: TargetId | BatchId): void {\n const ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n }\n\n /** Add references to the given document keys for the given ID. */\n addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.addReference(key, id));\n }\n\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n removeReference(key: DocumentKey, id: TargetId | BatchId): void {\n this.removeRef(new DocReference(key, id));\n }\n\n removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.removeReference(key, id));\n }\n\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n removeReferencesForId(id: TargetId | BatchId): DocumentKey[] {\n const emptyKey = new DocumentKey(new ResourcePath([]));\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n const keys: DocumentKey[] = [];\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n this.removeRef(ref);\n keys.push(ref.key);\n });\n return keys;\n }\n\n removeAllReferences(): void {\n this.refsByKey.forEach(ref => this.removeRef(ref));\n }\n\n private removeRef(ref: DocReference): void {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n }\n\n referencesForId(id: TargetId | BatchId): DocumentKeySet {\n const emptyKey = new DocumentKey(new ResourcePath([]));\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n let keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n keys = keys.add(ref.key);\n });\n return keys;\n }\n\n containsKey(key: DocumentKey): boolean {\n const ref = new DocReference(key, 0);\n const firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return firstRef !== null && key.isEqual(firstRef.key);\n }\n}\n\nexport class DocReference {\n constructor(\n public key: DocumentKey,\n public targetOrBatchId: TargetId | BatchId\n ) {}\n\n /** Compare by key then by ID */\n static compareByKey(left: DocReference, right: DocReference): number {\n return (\n DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId)\n );\n }\n\n /** Compare by ID then by key */\n static compareByTargetId(left: DocReference, right: DocReference): number {\n return (\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.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\nimport { isCollectionGroupQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { DocReference } from './reference_set';\n\nexport class MemoryMutationQueue implements MutationQueue {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n private mutationQueue: MutationBatch[] = [];\n\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n private nextBatchId: BatchId = 1;\n\n /** An ordered mapping between documents and the mutations batch IDs. */\n private batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n\n constructor(\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n debugAssert(mutations.length !== 0, 'Mutation batches should not be empty');\n\n const batchId = this.nextBatchId;\n this.nextBatchId++;\n\n if (this.mutationQueue.length > 0) {\n const prior = this.mutationQueue[this.mutationQueue.length - 1];\n debugAssert(\n prior.batchId < batchId,\n 'Mutation batchIDs must be monotonically increasing order'\n );\n }\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n this.mutationQueue.push(batch);\n\n // Track references by document key and index collection parents.\n for (const mutation of mutations) {\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(\n new DocReference(mutation.key, batchId)\n );\n\n this.indexManager.addToCollectionParentIndex(\n transaction,\n mutation.key.path.popLast()\n );\n }\n\n return PersistencePromise.resolve(batch);\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n const rawIndex = this.indexOfBatchId(nextBatchId);\n const index = rawIndex < 0 ? 0 : rawIndex;\n return PersistencePromise.resolve(\n this.mutationQueue.length > index ? this.mutationQueue[index] : null\n );\n }\n\n getHighestUnacknowledgedBatchId(): PersistencePromise {\n return PersistencePromise.resolve(\n this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1\n );\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n const result: MutationBatch[] = [];\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n debugAssert(\n documentKey.isEqual(ref.key),\n \"Should only iterate over a single key's batches\"\n );\n const batch = this.findMutationBatch(ref.targetOrBatchId);\n debugAssert(\n batch !== null,\n 'Batches in the index must exist in the main table'\n );\n result.push(batch!);\n });\n\n return PersistencePromise.resolve(result);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n documentKeys.forEach(documentKey => {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n debugAssert(\n documentKey.isEqual(ref.key),\n \"For each key, should only iterate over a single key's batches\"\n );\n\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n });\n });\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const prefix = query.path;\n const immediateChildrenPathLength = prefix.length + 1;\n\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n\n const start = new DocReference(new DocumentKey(startPath), 0);\n\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n this.batchesByDocumentKey.forEachWhile(ref => {\n const rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n } else {\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n private findMutationBatches(batchIDs: SortedSet): MutationBatch[] {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const result: MutationBatch[] = [];\n batchIDs.forEach(batchId => {\n const batch = this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return result;\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n // Find the position of the first batch for removal.\n const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n hardAssert(\n batchIndex === 0,\n 'Can only remove the first entry of the mutation queue'\n );\n this.mutationQueue.shift();\n\n let references = this.batchesByDocumentKey;\n return PersistencePromise.forEach(batch.mutations, (mutation: Mutation) => {\n const ref = new DocReference(mutation.key, batch.batchId);\n references = references.delete(ref);\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n mutation.key\n );\n }).next(() => {\n this.batchesByDocumentKey = references;\n });\n }\n\n removeCachedMutationKeys(batchId: BatchId): void {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const ref = new DocReference(key, 0);\n const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.mutationQueue.length === 0) {\n debugAssert(\n this.batchesByDocumentKey.isEmpty(),\n 'Document leak -- detected dangling mutation references when queue is empty.'\n );\n }\n return PersistencePromise.resolve();\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */\n private indexOfExistingBatchId(batchId: BatchId, action: string): number {\n const index = this.indexOfBatchId(batchId);\n debugAssert(\n index >= 0 && index < this.mutationQueue.length,\n 'Batches must exist to be ' + action\n );\n return index;\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */\n private indexOfBatchId(batchId: BatchId): number {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\n\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n const firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n }\n\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */\n private findMutationBatch(batchId: BatchId): MutationBatch | null {\n const index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n\n const batch = this.mutationQueue[index];\n debugAssert(batch.batchId === batchId, 'If found batch must match');\n return batch;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert, fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { IndexManager } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\n\nexport type DocumentSizer = (doc: Document) => number;\n\n/** Miscellaneous collection types / constants. */\ninterface MemoryRemoteDocumentCacheEntry {\n document: Document;\n size: number;\n}\n\ntype DocumentEntryMap = SortedMap;\nfunction documentEntryMap(): DocumentEntryMap {\n return new SortedMap(\n DocumentKey.comparator\n );\n}\n\nexport interface MemoryRemoteDocumentCache extends RemoteDocumentCache {\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise\n ): PersistencePromise;\n}\n\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass MemoryRemoteDocumentCacheImpl implements MemoryRemoteDocumentCache {\n /** Underlying cache of documents and their read times. */\n private docs = documentEntryMap();\n private indexManager!: IndexManager;\n\n /** Size of all cached documents. */\n private size = 0;\n\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(private readonly sizer: DocumentSizer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n addEntry(\n transaction: PersistenceTransaction,\n doc: MutableDocument\n ): PersistencePromise {\n debugAssert(\n !doc.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n\n const key = doc.key;\n const entry = this.docs.get(key);\n const previousSize = entry ? entry.size : 0;\n const currentSize = this.sizer(doc);\n\n this.docs = this.docs.insert(key, {\n document: doc.mutableCopy(),\n size: currentSize\n });\n\n this.size += currentSize - previousSize;\n\n return this.indexManager.addToCollectionParentIndex(\n transaction,\n key.path.popLast()\n );\n }\n\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n removeEntry(documentKey: DocumentKey): void {\n const entry = this.docs.get(documentKey);\n if (entry) {\n this.docs = this.docs.remove(documentKey);\n this.size -= entry.size;\n }\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n const entry = this.docs.get(documentKey);\n return PersistencePromise.resolve(\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n documentKeys.forEach(documentKey => {\n const entry = this.docs.get(documentKey);\n results = results.insert(\n documentKey,\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n });\n return PersistencePromise.resolve(results);\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap\n ): PersistencePromise {\n let results = mutableDocumentMap();\n\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const collectionPath = query.path;\n const prefix = new DocumentKey(collectionPath.child(''));\n const iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n const {\n key,\n value: { document }\n } = iterator.getNext();\n if (!collectionPath.isPrefixOf(key.path)) {\n break;\n }\n if (key.path.length > collectionPath.length + 1) {\n // Exclude entries from subcollections.\n continue;\n }\n if (\n indexOffsetComparator(newIndexOffsetFromDocument(document), offset) <= 0\n ) {\n // The document sorts before the offset.\n continue;\n }\n if (!mutatedDocs.has(document.key) && !queryMatches(query, document)) {\n // The document cannot possibly match the query.\n continue;\n }\n\n results = results.insert(document.key, document.mutableCopy());\n }\n return PersistencePromise.resolve(results);\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limti: number\n ): PersistencePromise {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n fail('getAllFromCollectionGroup() is not supported.');\n }\n\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise\n ): PersistencePromise {\n return PersistencePromise.forEach(this.docs, (key: DocumentKey) => f(key));\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new MemoryRemoteDocumentChangeBuffer(this);\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return PersistencePromise.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\nexport function newMemoryRemoteDocumentCache(\n sizer: DocumentSizer\n): MemoryRemoteDocumentCache {\n return new MemoryRemoteDocumentCacheImpl(sizer);\n}\n\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n constructor(private readonly documentCache: MemoryRemoteDocumentCacheImpl) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n this.changes.forEach((key, doc) => {\n if (doc.isValidDocument()) {\n promises.push(this.documentCache.addEntry(transaction, doc));\n } else {\n this.documentCache.removeEntry(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n return this.documentCache.getEntry(transaction, documentKey);\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n return this.documentCache.getEntries(transaction, documentKeys);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class MemoryTargetCache implements TargetCache {\n /**\n * Maps a target to the data about that target\n */\n private targets = new ObjectMap(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /** The last received snapshot version. */\n private lastRemoteSnapshotVersion = SnapshotVersion.min();\n /** The highest numbered target ID encountered. */\n private highestTargetId: TargetId = 0;\n /** The highest sequence number encountered. */\n private highestSequenceNumber: ListenSequenceNumber = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n private references = new ReferenceSet();\n\n private targetCount = 0;\n\n private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n constructor(private readonly persistence: Persistence) {}\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n this.targets.forEach((_, targetData) => f(targetData));\n return PersistencePromise.resolve();\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.highestSequenceNumber);\n }\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n this.highestTargetId = this.targetIdGenerator.next();\n return PersistencePromise.resolve(this.highestTargetId);\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n if (lastRemoteSnapshotVersion) {\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n if (highestListenSequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = highestListenSequenceNumber;\n }\n return PersistencePromise.resolve();\n }\n\n private saveTargetData(targetData: TargetData): void {\n this.targets.set(targetData.target, targetData);\n const targetId = targetData.targetId;\n if (targetId > this.highestTargetId) {\n this.targetIdGenerator = new TargetIdGenerator(targetId);\n this.highestTargetId = targetId;\n }\n if (targetData.sequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = targetData.sequenceNumber;\n }\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n debugAssert(\n !this.targets.has(targetData.target),\n 'Adding a target that already exists'\n );\n this.saveTargetData(targetData);\n this.targetCount += 1;\n return PersistencePromise.resolve();\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n debugAssert(\n this.targets.has(targetData.target),\n 'Updating a non-existent target'\n );\n this.saveTargetData(targetData);\n return PersistencePromise.resolve();\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n debugAssert(this.targetCount > 0, 'Removing a target from an empty cache');\n debugAssert(\n this.targets.has(targetData.target),\n 'Removing a non-existent target from the cache'\n );\n this.targets.delete(targetData.target);\n this.references.removeReferencesForId(targetData.targetId);\n this.targetCount -= 1;\n return PersistencePromise.resolve();\n }\n\n removeTargets(\n transaction: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const removals: Array> = [];\n this.targets.forEach((key, targetData) => {\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n this.targets.delete(key);\n removals.push(\n this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n );\n count++;\n }\n });\n return PersistencePromise.waitFor(removals).next(() => count);\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.targetCount);\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n const targetData = this.targets.get(target) || null;\n return PersistencePromise.resolve(targetData);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n this.references.addReferences(keys, targetId);\n return PersistencePromise.resolve();\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n this.references.removeReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array> = [];\n if (referenceDelegate) {\n keys.forEach(key => {\n promises.push(referenceDelegate.markPotentiallyOrphaned(txn, key));\n });\n }\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.resolve(this.references.containsKey(key));\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { estimateByteSize } from '../model/values';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { fail } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { LocalSerializer } from './local_serializer';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { MemoryBundleCache } from './memory_bundle_cache';\nimport { MemoryDocumentOverlayCache } from './memory_document_overlay_cache';\nimport { MemoryIndexManager } from './memory_index_manager';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport {\n MemoryRemoteDocumentCache,\n newMemoryRemoteDocumentCache\n} from './memory_remote_document_cache';\nimport { MemoryTargetCache } from './memory_target_cache';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode\n} from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetData } from './target_data';\n\nconst LOG_TAG = 'MemoryPersistence';\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nexport class MemoryPersistence implements Persistence {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n private readonly indexManager: MemoryIndexManager;\n private mutationQueues: { [user: string]: MemoryMutationQueue } = {};\n private overlays: { [user: string]: MemoryDocumentOverlayCache } = {};\n private readonly remoteDocumentCache: MemoryRemoteDocumentCache;\n private readonly targetCache: MemoryTargetCache;\n private readonly bundleCache: MemoryBundleCache;\n private readonly listenSequence = new ListenSequence(0);\n private serializer: LocalSerializer;\n\n private _started = false;\n\n readonly referenceDelegate: MemoryReferenceDelegate;\n\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(\n referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate,\n serializer: JsonProtoSerializer\n ) {\n this._started = true;\n this.referenceDelegate = referenceDelegateFactory(this);\n this.targetCache = new MemoryTargetCache(this);\n const sizer = (doc: Document): number =>\n this.referenceDelegate.documentSize(doc);\n this.indexManager = new MemoryIndexManager();\n this.remoteDocumentCache = newMemoryRemoteDocumentCache(sizer);\n this.serializer = new LocalSerializer(serializer);\n this.bundleCache = new MemoryBundleCache(this.serializer);\n }\n\n start(): Promise {\n return Promise.resolve();\n }\n\n shutdown(): Promise {\n // No durable state to ensure is closed on shutdown.\n this._started = false;\n return Promise.resolve();\n }\n\n get started(): boolean {\n return this._started;\n }\n\n setDatabaseDeletedListener(): void {\n // No op.\n }\n\n setNetworkEnabled(): void {\n // No op.\n }\n\n getIndexManager(user: User): MemoryIndexManager {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n let overlay = this.overlays[user.toKey()];\n if (!overlay) {\n overlay = new MemoryDocumentOverlayCache();\n this.overlays[user.toKey()] = overlay;\n }\n return overlay;\n }\n\n getMutationQueue(user: User, indexManager: IndexManager): MutationQueue {\n let queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue(indexManager, this.referenceDelegate);\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n }\n\n getTargetCache(): MemoryTargetCache {\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): MemoryRemoteDocumentCache {\n return this.remoteDocumentCache;\n }\n\n getBundleCache(): MemoryBundleCache {\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n const txn = new MemoryTransaction(this.listenSequence.next());\n this.referenceDelegate.onTransactionStarted();\n return transactionOperation(txn)\n .next(result => {\n return this.referenceDelegate\n .onTransactionCommitted(txn)\n .next(() => result);\n })\n .toPromise()\n .then(result => {\n txn.raiseOnCommittedEvent();\n return result;\n });\n }\n\n mutationQueuesContainKey(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.or(\n Object.values(this.mutationQueues).map(\n queue => () => queue.containsKey(transaction, key)\n )\n );\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */\nexport class MemoryTransaction extends PersistenceTransaction {\n constructor(readonly currentSequenceNumber: ListenSequenceNumber) {\n super();\n }\n}\n\nexport interface MemoryReferenceDelegate extends ReferenceDelegate {\n documentSize(doc: Document): number;\n onTransactionStarted(): void;\n onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise;\n}\n\nexport class MemoryEagerDelegate implements MemoryReferenceDelegate {\n /** Tracks all documents that are active in Query views. */\n private localViewReferences: ReferenceSet = new ReferenceSet();\n /** The list of documents that are potentially GCed after each transaction. */\n private _orphanedDocuments: Set | null = null;\n\n private constructor(private readonly persistence: MemoryPersistence) {}\n\n static factory(persistence: MemoryPersistence): MemoryEagerDelegate {\n return new MemoryEagerDelegate(persistence);\n }\n\n private get orphanedDocuments(): Set {\n if (!this._orphanedDocuments) {\n throw fail('orphanedDocuments is only valid during a transaction.');\n } else {\n return this._orphanedDocuments;\n }\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n this.localViewReferences.addReference(key, targetId);\n this.orphanedDocuments.delete(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n this.localViewReferences.removeReference(key, targetId);\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const orphaned = this.localViewReferences.removeReferencesForId(\n targetData.targetId\n );\n orphaned.forEach(key => this.orphanedDocuments.add(key.toString()));\n const cache = this.persistence.getTargetCache();\n return cache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(keys => {\n keys.forEach(key => this.orphanedDocuments.add(key.toString()));\n })\n .next(() => cache.removeTargetData(txn, targetData));\n }\n\n onTransactionStarted(): void {\n this._orphanedDocuments = new Set();\n }\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise {\n // Remove newly orphaned documents.\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n return PersistencePromise.forEach(\n this.orphanedDocuments,\n (path: string) => {\n const key = DocumentKey.fromPath(path);\n return this.isReferenced(txn, key).next(isReferenced => {\n if (!isReferenced) {\n changeBuffer.removeEntry(key, SnapshotVersion.min());\n }\n });\n }\n ).next(() => {\n this._orphanedDocuments = null;\n return changeBuffer.apply(txn);\n });\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return this.isReferenced(txn, key).next(isReferenced => {\n if (isReferenced) {\n this.orphanedDocuments.delete(key.toString());\n } else {\n this.orphanedDocuments.add(key.toString());\n }\n });\n }\n\n documentSize(doc: Document): number {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n\n private isReferenced(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.or([\n () =>\n PersistencePromise.resolve(this.localViewReferences.containsKey(key)),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => this.persistence.mutationQueuesContainKey(txn, key)\n ]);\n }\n}\n\nexport class MemoryLruDelegate implements ReferenceDelegate, LruDelegate {\n private orphanedSequenceNumbers: ObjectMap<\n DocumentKey,\n ListenSequenceNumber\n > = new ObjectMap(\n k => encodeResourcePath(k.path),\n (l, r) => l.isEqual(r)\n );\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(\n private readonly persistence: MemoryPersistence,\n lruParams: LruParams\n ) {\n this.garbageCollector = newLruGarbageCollector(this, lruParams);\n }\n\n static factory(\n persistence: MemoryPersistence,\n lruParams: LruParams\n ): MemoryLruDelegate {\n return new MemoryLruDelegate(persistence, lruParams);\n }\n\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n onTransactionStarted(): void {}\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve();\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.persistence.getTargetCache().forEachTarget(txn, f);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.persistence\n .getTargetCache()\n .getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return PersistencePromise.forEach(\n this.orphanedSequenceNumbers,\n (key, sequenceNumber) => {\n // Pass in the exact sequence number as the upper bound so we know it won't be pinned by\n // being too recent.\n return this.isPinned(txn, key, sequenceNumber).next(isPinned => {\n if (!isPinned) {\n return f(sequenceNumber);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n );\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.persistence\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n let count = 0;\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n const p = cache.forEachDocumentKey(txn, key => {\n return this.isPinned(txn, key, upperBound).next(isPinned => {\n if (!isPinned) {\n count++;\n changeBuffer.removeEntry(key, SnapshotVersion.min());\n }\n });\n });\n return p.next(() => changeBuffer.apply(txn)).next(() => count);\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(txn, updated);\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n documentSize(document: Document): number {\n let documentSize = document.key.toString().length;\n if (document.isFoundDocument()) {\n documentSize += estimateByteSize(document.data.value);\n }\n return documentSize;\n }\n\n private isPinned(\n txn: PersistenceTransaction,\n key: DocumentKey,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return PersistencePromise.or([\n () => this.persistence.mutationQueuesContainKey(txn, key),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => {\n const orphanedAt = this.orphanedSequenceNumbers.get(key);\n return PersistencePromise.resolve(\n orphanedAt !== undefined && orphanedAt > upperBound\n );\n }\n ]);\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.persistence.getRemoteDocumentCache().getSize(txn);\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 { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport {\n dbDocumentSize,\n removeMutationBatch\n} from './indexeddb_mutation_batch_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { newIndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n DbCollectionParent,\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue,\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbTarget,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport {\n DbRemoteDocument as DbRemoteDocumentLegacy,\n DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy,\n DbRemoteDocumentKey as DbRemoteDocumentKeyLegacy\n} from './indexeddb_schema_legacy';\nimport {\n DbBundleKeyPath,\n DbBundleStore,\n DbClientMetadataKeyPath,\n DbClientMetadataStore,\n DbCollectionParentKey,\n DbCollectionParentKeyPath,\n DbCollectionParentStore,\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n DbDocumentOverlayKeyPath,\n DbDocumentOverlayStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n DbIndexConfigurationKeyPath,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n DbIndexEntryKeyPath,\n DbIndexEntryStore,\n DbIndexStateKeyPath,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n DbIndexStateStore,\n DbMutationBatchKey,\n DbMutationBatchKeyPath,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n DbMutationQueueKey,\n DbMutationQueueKeyPath,\n DbMutationQueueStore,\n DbNamedQueryKeyPath,\n DbNamedQueryStore,\n DbPrimaryClientStore,\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentKeyPath,\n DbRemoteDocumentStore,\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n DbTargetDocumentKey,\n DbTargetDocumentKeyPath,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetKeyPath,\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalDocumentsView } from './local_documents_view';\nimport {\n fromDbMutationBatch,\n fromDbTarget,\n LocalSerializer,\n toDbTarget\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { MemoryEagerDelegate, MemoryPersistence } from './memory_persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\n\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise {\n debugAssert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createLegacyRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.next(() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n dropRemoteDocumentChangesStore(db);\n\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n });\n }\n\n if (fromVersion < 10 && toVersion >= 10) {\n p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n }\n\n if (fromVersion < 11 && toVersion >= 11) {\n p = p.next(() => {\n createBundlesStore(db);\n createNamedQueriesStore(db);\n });\n }\n\n if (fromVersion < 12 && toVersion >= 12) {\n p = p.next(() => {\n createDocumentOverlayStore(db);\n });\n }\n\n if (fromVersion < 13 && toVersion >= 13) {\n p = p\n .next(() => createRemoteDocumentCache(db))\n .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n }\n\n if (fromVersion < 14 && toVersion >= 14) {\n p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n }\n\n if (fromVersion < 15 && toVersion >= 15) {\n p = p.next(() => createFieldIndex(db));\n }\n\n if (fromVersion < 16 && toVersion >= 16) {\n // Clear the object stores to remove possibly corrupted index entries\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n let byteSize = 0;\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate((_, doc) => {\n byteSize += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata: DbRemoteDocumentGlobal = { byteSize };\n return txn\n .store(\n DbRemoteDocumentGlobalStore\n )\n .put(DbRemoteDocumentGlobalKey, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const queuesStore = txn.store(\n DbMutationQueueStore\n );\n const mutationsStore = txn.store(\n DbMutationBatchStore\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n hardAssert(\n dbBatch.userId === queue.userId,\n `Cannot process batch ${dbBatch.batchId} from unexpected user`\n );\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(\n () => {}\n );\n }\n );\n });\n });\n });\n }\n\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocumentStore);\n const documentsStore = txn.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentKeyLegacy\n >(DbRemoteDocumentStoreLegacy);\n const globalTargetStore = txn.store(\n DbTargetGlobalStore\n );\n\n return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n debugAssert(\n !!metadata,\n 'Metadata should have been written during the version 3 migration'\n );\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise => {\n return documentTargetStore.put({\n targetId: 0,\n path: encodeResourcePath(path),\n sequenceNumber: metadata!.highestListenSequenceNumber!\n });\n };\n\n const promises: Array> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise {\n // Create the index.\n db.createObjectStore(DbCollectionParentStore, {\n keyPath: DbCollectionParentKeyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParentStore);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encodeResourcePath(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store(\n DbDocumentMutationStore\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decodeResourcePath(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n\n private rewriteCanonicalIds(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const targetStore = txn.store(DbTargetStore);\n return targetStore.iterate((key, originalDbTarget) => {\n const originalTargetData = fromDbTarget(originalDbTarget);\n const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n return targetStore.put(updatedDbTarget);\n });\n }\n\n private rewriteRemoteDocumentCache(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const legacyRemoteDocumentStore = transaction.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentLegacy\n >(DbRemoteDocumentStoreLegacy);\n\n const writes: Array> = [];\n return legacyRemoteDocumentStore\n .iterate((_, legacyDocument) => {\n const remoteDocumentStore = transaction.store<\n DbRemoteDocumentKey,\n DbRemoteDocument\n >(DbRemoteDocumentStore);\n\n const path = extractKey(legacyDocument).path.toArray();\n const dbRemoteDocument = {\n prefixPath: path.slice(0, path.length - 2),\n collectionGroup: path[path.length - 2],\n documentId: path[path.length - 1],\n readTime: legacyDocument.readTime || [0, 0],\n unknownDocument: legacyDocument.unknownDocument,\n noDocument: legacyDocument.noDocument,\n document: legacyDocument.document,\n hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n };\n writes.push(remoteDocumentStore.put(dbRemoteDocument));\n })\n .next(() => PersistencePromise.waitFor(writes));\n }\n\n private runOverlayMigration(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const mutationsStore = transaction.store<\n DbMutationBatchKey,\n DbMutationBatch\n >(DbMutationBatchStore);\n\n const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n this.serializer\n );\n const memoryPersistence = new MemoryPersistence(\n MemoryEagerDelegate.factory,\n this.serializer.remoteSerializer\n );\n\n return mutationsStore.loadAll().next(dbBatches => {\n const userToDocumentSet = new Map();\n dbBatches.forEach(dbBatch => {\n let documentSet =\n userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n userToDocumentSet.set(dbBatch.userId, documentSet);\n });\n return PersistencePromise.forEach(\n userToDocumentSet,\n (allDocumentKeysForUser, userId) => {\n const user = new User(userId);\n const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n this.serializer,\n user\n );\n // NOTE: The index manager and the reference delegate are\n // irrelevant for the purpose of recalculating and saving\n // overlays. We can therefore simply use the memory\n // implementation.\n const indexManager = memoryPersistence.getIndexManager(user);\n const mutationQueue = IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n memoryPersistence.referenceDelegate\n );\n const localDocumentsView = new LocalDocumentsView(\n remoteDocumentCache,\n mutationQueue,\n documentOverlayCache,\n indexManager\n );\n return localDocumentsView\n .recalculateAndSaveOverlaysForDocumentKeys(\n new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n allDocumentKeysForUser\n )\n .next();\n }\n );\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueueStore, {\n keyPath: DbMutationQueueKeyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutationStore);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatchStore\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatchStore);\n\n const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store(\n DbMutationBatchStore\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n keyPath: DbRemoteDocumentKeyPath\n });\n remoteDocumentStore.createIndex(\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath\n );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n keyPath: DbTargetDocumentKeyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTargetStore, {\n keyPath: DbTargetKeyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocumentStore);\n db.deleteObjectStore(DbTargetStore);\n db.deleteObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise {\n const globalStore = txn.store(\n DbTargetGlobalStore\n );\n const metadata: DbTargetGlobal = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadataStore, {\n keyPath: DbClientMetadataKeyPath\n });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n db.createObjectStore(DbBundleStore, {\n keyPath: DbBundleKeyPath\n });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n db.createObjectStore(DbNamedQueryStore, {\n keyPath: DbNamedQueryKeyPath\n });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n const indexConfigurationStore = db.createObjectStore(\n DbIndexConfigurationStore,\n {\n keyPath: DbIndexConfigurationKeyPath,\n autoIncrement: true\n }\n );\n indexConfigurationStore.createIndex(\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n { unique: false }\n );\n\n const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n keyPath: DbIndexStateKeyPath\n });\n indexStateStore.createIndex(\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n { unique: false }\n );\n\n const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n keyPath: DbIndexEntryKeyPath\n });\n indexEntryStore.createIndex(\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n { unique: false }\n );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n keyPath: DbDocumentOverlayKeyPath\n });\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n { unique: false }\n );\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n { unique: false }\n );\n}\n\nfunction extractKey(remoteDoc: DbRemoteDocumentLegacy): DocumentKey {\n if (remoteDoc.document) {\n return new DocumentKey(\n ResourcePath.fromString(remoteDoc.document.name!).popFirst(5)\n );\n } else if (remoteDoc.noDocument) {\n return DocumentKey.fromSegments(remoteDoc.noDocument.path);\n } else if (remoteDoc.unknownDocument) {\n return DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafari } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { DatabaseId } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { DocumentLike, WindowLike } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbBundleCache } from './indexeddb_bundle_cache';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport {\n IndexedDbRemoteDocumentCache,\n newIndexedDbRemoteDocumentCache\n} from './indexeddb_remote_document_cache';\nimport {\n DbClientMetadata,\n DbPrimaryClient,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport { SchemaConverter } from './indexeddb_schema_converter';\nimport {\n DbClientMetadataKey,\n DbClientMetadataStore,\n DbPrimaryClientKey,\n DbPrimaryClientStore,\n getObjectStores\n} from './indexeddb_sentinels';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { getStore, IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalSerializer } from './local_serializer';\nimport { LruParams } from './lru_garbage_collector';\nimport { Persistence, PrimaryStateListener } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence_transaction';\nimport { ClientId } from './shared_client_state';\nimport {\n isIndexedDbTransactionError,\n SimpleDb,\n SimpleDbStore\n} from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Failed to obtain exclusive access to the persistence layer. To allow ' +\n 'shared access, multi-tab synchronization has to be enabled in all tabs. ' +\n 'If you are using `experimentalForceOwningTab:true`, make sure that only ' +\n 'one tab has persistence enabled at any given time.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing IndexedDB or is known to have ' +\n 'an incomplete implementation. Offline persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie__\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\n/**\n * The name of the main (and currently only) IndexedDB database. This name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\nexport const MAIN_DATABASE = 'main';\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nexport class IndexedDbPersistence implements Persistence {\n private simpleDb: SimpleDb;\n\n private listenSequence: ListenSequence | null = null;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: DelayedOperation | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly targetCache: IndexedDbTargetCache;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly bundleCache: IndexedDbBundleCache;\n private readonly webStorage: Storage | null;\n readonly referenceDelegate: IndexedDbLruDelegateImpl;\n\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n private readonly allowTabSynchronization: boolean,\n\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n private readonly window: WindowLike | null,\n private readonly document: DocumentLike | null,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer,\n\n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n private readonly forceOwningTab: boolean,\n private readonly schemaVersion = SCHEMA_VERSION\n ) {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);\n this.dbName = persistenceKey + MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.simpleDb = new SimpleDb(\n this.dbName,\n this.schemaVersion,\n new SchemaConverter(this.serializer)\n );\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);\n this.bundleCache = new IndexedDbBundleCache();\n if (this.window && this.window.localStorage) {\n this.webStorage = this.window.localStorage;\n } else {\n this.webStorage = null;\n if (forceOwningTab === false) {\n logError(\n LOG_TAG,\n 'LocalStorage is unavailable. As a result, persistence may not work ' +\n 'reliably. In particular enablePersistence() could fail immediately ' +\n 'after refreshing the page.'\n );\n }\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */\n start(): Promise {\n debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => {\n if (!this.isPrimary && !this.allowTabSynchronization) {\n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.runTransaction(\n 'getHighestListenSequenceNumber',\n 'readonly',\n txn => this.targetCache.getHighestSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\n }\n\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */\n private updateClientMetadataAndTryBecomePrimary(): Promise {\n return this.runTransaction(\n 'updateClientMetadataAndTryBecomePrimary',\n 'readwrite',\n txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n })\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n }\n )\n .catch(e => {\n if (isIndexedDbTransactionError(e)) {\n logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return this.isPrimary;\n }\n\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n logDebug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = getStore(\n txn,\n DbClientMetadataStore\n );\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.webStorage) {\n for (const inactiveClient of inactiveClients) {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n }\n }\n }\n }\n\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\n\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */\n private canActAsPrimary(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.forceOwningTab) {\n return PersistencePromise.resolve(true);\n }\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClientKey)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n logDebug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n\n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.simpleDb.runTransaction(\n 'shutdown',\n 'readwrite',\n [DbPrimaryClientStore, DbClientMetadataStore],\n simpleDbTxn => {\n const persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n ListenSequence.INVALID\n );\n return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n this.removeClientMetadata(persistenceTransaction)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n getActiveClients(): Promise {\n return this.runTransaction('getActiveClients', 'readonly', txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n });\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getMutationQueue(\n user: User,\n indexManager: IndexManager\n ): IndexedDbMutationQueue {\n debugAssert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n debugAssert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n debugAssert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(user: User): IndexManager {\n debugAssert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return new IndexedDbIndexManager(\n user,\n this.serializer.remoteSerializer.databaseId\n );\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n debugAssert(\n this.started,\n 'Cannot initialize IndexedDbDocumentOverlayCache before persistence is started.'\n );\n return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);\n }\n\n getBundleCache(): BundleCache {\n debugAssert(\n this.started,\n 'Cannot initialize BundleCache before persistence is started.'\n );\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n const objectStores = getObjectStores(this.schemaVersion);\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence\n ? this.listenSequence.next()\n : ListenSequence.INVALID\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(persistenceTransaction)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(persistenceTransaction);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n logError(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(\n persistenceTransaction\n ).next(() => result);\n });\n } else {\n return this.verifyAllowTabSynchronization(\n persistenceTransaction\n ).next(() => transactionOperation(persistenceTransaction));\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\n\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n private verifyAllowTabSynchronization(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (\n !this.forceOwningTab &&\n (!this.allowTabSynchronization ||\n !currentPrimary!.allowTabSynchronization)\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\n }\n\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */\n private acquireOrExtendPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const newPrimary: DbPrimaryClient = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n logDebug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClientKey);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n logError(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n debugAssert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\n\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */\n private attachWindowUnloadHook(): void {\n if (typeof this.window?.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.markClientZombied();\n\n const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n if (\n isSafari() &&\n (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n navigator.userAgent.match(safariIndexdbBugVersionRegex))\n ) {\n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n }\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('pagehide', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n debugAssert(\n typeof this.window?.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window!.removeEventListener('pagehide', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\n\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage?.getItem(\n this.zombiedClientLocalStorageKey(clientId)\n ) !== null;\n logDebug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n logError(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\n }\n\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */\n private markClientZombied(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n logError('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbPrimaryClientStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbClientMetadataStore\n );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n databaseId: DatabaseId,\n persistenceKey: string\n): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseId.projectId;\n if (!databaseId.isDefaultDatabase) {\n database += '.' + databaseId.database;\n }\n\n return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n persistenceKey: string\n): Promise {\n if (!SimpleDb.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { IndexKind } from '../model/field_index';\nimport { BundledQuery } from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n DocumentsTarget as ProtoDocumentsTarget,\n QueryTarget as ProtoQueryTarget,\n Write as ProtoWrite\n} from '../protos/firestore_proto_api';\n\nimport { EncodedResourcePath } from './encoded_resource_path';\nimport { DbTimestampKey } from './indexeddb_sentinels';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n * 16. Parse timestamp strings before creating index entries.\n */\n\nexport const SCHEMA_VERSION = 16;\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport interface DbTimestamp {\n seconds: number;\n nanoseconds: number;\n}\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport interface DbPrimaryClient {\n ownerId: string;\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization: boolean;\n leaseTimestampMs: number;\n}\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport interface DbMutationQueue {\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId: string;\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastAcknowledgedBatchId: number;\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastStreamToken: string;\n}\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport interface DbMutationBatch {\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId: string;\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n batchId: BatchId;\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs: number;\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n baseMutations?: ProtoWrite[];\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */\n mutations: ProtoWrite[];\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport interface DbDocumentMutation {}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbNoDocument {\n path: string[];\n readTime: DbTimestamp;\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbUnknownDocument {\n path: string[];\n version: DbTimestamp;\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * The document key is split up across `prefixPath`, `collectionGroup` and\n * `documentId`.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport interface DbRemoteDocument {\n /** The path to the document's collection (excluding). */\n prefixPath: string[];\n\n /** The collection ID the document is direclty nested under. */\n collectionGroup: string;\n\n /** The document ID. */\n documentId: string;\n\n /** When the document was read from the backend. */\n readTime: DbTimestampKey;\n\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n unknownDocument?: DbUnknownDocument;\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument?: DbNoDocument;\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document?: ProtoDocument;\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n hasCommittedMutations: boolean;\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport interface DbRemoteDocumentGlobal {\n /**\n * Approximately the total size in bytes of all the\n * documents in the document cache.\n */\n byteSize: number;\n}\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport interface DbTarget {\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId: TargetId;\n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId: string;\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime: DbTimestamp;\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken: string;\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber: number;\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n lastLimboFreeSnapshotVersion?: DbTimestamp;\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query: DbQuery;\n}\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport interface DbTargetDocument {\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n targetId: TargetId;\n /**\n * The path to the document, as encoded in the key.\n */\n path: EncodedResourcePath;\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n sequenceNumber?: ListenSequenceNumber;\n}\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport interface DbTargetGlobal {\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId: TargetId;\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber: number;\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion: DbTimestamp;\n /**\n * The number of targets persisted.\n */\n targetCount: number;\n}\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport interface DbCollectionParent {\n /**\n * The collectionId (e.g. 'messages')\n */\n collectionId: string;\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n parent: EncodedResourcePath;\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport interface DbClientMetadata {\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n clientId: string;\n /** The last time this state was updated. */\n updateTimeMs: number;\n /** Whether the client's network connection is enabled. */\n networkEnabled: boolean;\n /** Whether this client is running in a foreground tab. */\n inForeground: boolean;\n}\n\n/** An object representing a bundle loaded by the SDK. */\nexport interface DbBundle {\n /** The ID of the loaded bundle. */\n bundleId: string;\n /** The create time of the loaded bundle. */\n createTime: DbTimestamp;\n /** The schema version of the loaded bundle. */\n version: number;\n}\n\n/** An object representing a named query loaded by the SDK via a bundle. */\nexport interface DbNamedQuery {\n /** The name of the query. */\n name: string;\n /** The read time of the results saved in the bundle from the named query. */\n readTime: DbTimestamp;\n /** The query saved in the bundle. */\n bundledQuery: BundledQuery;\n}\n\n/** An object representing the global configuration for a field index. */\nexport interface DbIndexConfiguration {\n /**\n * The index id for this entry. Undefined for indexes that are not yet\n * persisted.\n */\n indexId?: number;\n /** The collection group this index belongs to. */\n collectionGroup: string;\n /** The fields to index for this index. */\n fields: Array<[name: string, kind: IndexKind]>;\n}\n\n/**\n * An object describing how up-to-date the index backfill is for each user and\n * index.\n */\nexport interface DbIndexState {\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /**\n * A number that indicates when the index was last updated (relative to\n * other indexes).\n */\n sequenceNumber: number;\n /**\n * The latest read time that has been indexed by Firestore for this field\n * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed.\n */\n readTime: DbTimestamp;\n /**\n * The last document that has been indexed for this field index. Empty if\n * no documents have been indexed.\n */\n documentKey: EncodedResourcePath;\n /**\n * The largest mutation batch id that has been processed for this index. -1\n * if no mutations have been indexed.\n */\n largestBatchId: number;\n}\n\n/** An object that stores the encoded entries for all documents and fields. */\nexport interface DbIndexEntry {\n // TODO(indexing): Consider just storing `orderedDocumentKey` and decoding\n // the ordered key into a document key. This would reduce storage space on\n // disk but require us to port parts of OrderedCodeReader.\n\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /** The encoded array index value for this entry. */\n arrayValue: Uint8Array;\n /** The encoded directional value for equality and inequality filters. */\n directionalValue: Uint8Array;\n /**\n * The document key this entry points to. This entry is encoded by an ordered\n * encoder to match the key order of the index.\n */\n orderedDocumentKey: Uint8Array;\n /** The segments of the document key this entry points to. */\n documentKey: string[];\n}\n\n/**\n * An object representing a document overlay.\n */\nexport interface DbDocumentOverlay {\n /** The user ID to whom this overlay belongs. */\n userId: string;\n /** The path to the collection that contains the document. */\n collectionPath: string;\n /** The ID (key) of the document within the collection. */\n documentId: string;\n /** The collection group to which the document belongs. */\n collectionGroup: string;\n /** The largest batch ID that's been applied for this overlay. */\n largestBatchId: number;\n /** The overlay mutation. */\n overlayMutation: ProtoWrite;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from '../core/types';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\n\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nexport class LocalViewChanges {\n constructor(\n readonly targetId: TargetId,\n readonly fromCache: boolean,\n readonly addedKeys: DocumentKeySet,\n readonly removedKeys: DocumentKeySet\n ) {}\n\n static fromSnapshot(\n targetId: TargetId,\n viewSnapshot: ViewSnapshot\n ): LocalViewChanges {\n let addedKeys = documentKeySet();\n let removedKeys = documentKeySet();\n\n for (const docChange of viewSnapshot.docChanges) {\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n // do nothing\n }\n }\n\n return new LocalViewChanges(\n targetId,\n viewSnapshot.fromCache,\n addedKeys,\n removedKeys\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\n/**\n * A tracker to keep a record of important details during database local query\n * execution.\n */\nexport class QueryContext {\n /**\n * Counts the number of documents passed through during local query execution.\n */\n private _documentReadCount = 0;\n\n get documentReadCount(): number {\n return this._documentReadCount;\n }\n\n incrementDocumentReadCount(amount: number): void {\n this._documentReadCount += amount;\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\nimport { getUA, isSafari } from '@firebase/util';\n\nimport {\n LimitType,\n newQueryComparator,\n Query,\n queryMatches,\n queryMatchesAllDocuments,\n queryToTarget,\n queryWithLimit,\n stringifyQuery\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport {\n IndexOffset,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { Iterable } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { getAndroidVersion } from './simple_db';\n\nconst DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE = 100;\n\n/**\n * This cost represents the evaluation result of\n * (([index, docKey] + [docKey, docContent]) per document in the result set)\n * / ([docKey, docContent] per documents in full collection scan) coming from\n * experiment [enter PR experiment URL here].\n */\nfunction getDefaultRelativeIndexReadCostPerDocument(): number {\n // These values were derived from an experiment where several members of the\n // Firestore SDK team ran a performance test in various environments.\n // Googlers can see b/299284287 for details.\n if (isSafari()) {\n return 8;\n } else if (getAndroidVersion(getUA()) > 0) {\n return 6;\n } else {\n return 4;\n }\n}\n\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */\nexport class QueryEngine {\n private localDocumentsView!: LocalDocumentsView;\n private indexManager!: IndexManager;\n private initialized = false;\n\n indexAutoCreationEnabled = false;\n\n /**\n * SDK only decides whether it should create index when collection size is\n * larger than this.\n */\n indexAutoCreationMinCollectionSize =\n DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE;\n\n relativeIndexReadCostPerDocument =\n getDefaultRelativeIndexReadCostPerDocument();\n\n /** Sets the document view to query against. */\n initialize(\n localDocuments: LocalDocumentsView,\n indexManager: IndexManager\n ): void {\n this.localDocumentsView = localDocuments;\n this.indexManager = indexManager;\n this.initialized = true;\n }\n\n /** Returns all local documents matching the specified query. */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n lastLimboFreeSnapshotVersion: SnapshotVersion,\n remoteKeys: DocumentKeySet\n ): PersistencePromise {\n debugAssert(this.initialized, 'initialize() not called');\n\n // Stores the result from executing the query; using this object is more\n // convenient than passing the result between steps of the persistence\n // transaction and improves readability comparatively.\n const queryResult: { result: DocumentMap | null } = { result: null };\n\n return this.performQueryUsingIndex(transaction, query)\n .next(result => {\n queryResult.result = result;\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n return this.performQueryUsingRemoteKeys(\n transaction,\n query,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n ).next(result => {\n queryResult.result = result;\n });\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n const context = new QueryContext();\n return this.executeFullCollectionScan(transaction, query, context).next(\n result => {\n queryResult.result = result;\n if (this.indexAutoCreationEnabled) {\n return this.createCacheIndexes(\n transaction,\n query,\n context,\n result.size\n );\n }\n }\n );\n })\n .next(() => queryResult.result!);\n }\n\n createCacheIndexes(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext,\n resultSize: number\n ): PersistencePromise {\n if (context.documentReadCount < this.indexAutoCreationMinCollectionSize) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'SDK will not create cache indexes for query:',\n stringifyQuery(query),\n 'since it only creates cache indexes for collection contains',\n 'more than or equal to',\n this.indexAutoCreationMinCollectionSize,\n 'documents'\n );\n }\n return PersistencePromise.resolve();\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Query:',\n stringifyQuery(query),\n 'scans',\n context.documentReadCount,\n 'local documents and returns',\n resultSize,\n 'documents as results.'\n );\n }\n\n if (\n context.documentReadCount >\n this.relativeIndexReadCostPerDocument * resultSize\n ) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'The SDK decides to create cache indexes for query:',\n stringifyQuery(query),\n 'as using cache indexes may help improve performance.'\n );\n }\n return this.indexManager.createTargetIndexes(\n transaction,\n queryToTarget(query)\n );\n }\n\n return PersistencePromise.resolve();\n }\n\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */\n private performQueryUsingIndex(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve(null);\n }\n\n let target = queryToTarget(query);\n return this.indexManager\n .getIndexType(transaction, target)\n .next(indexType => {\n if (indexType === IndexType.NONE) {\n // The target cannot be served from any index.\n return null;\n }\n\n if (query.limit !== null && indexType === IndexType.PARTIAL) {\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n query = queryWithLimit(query, null, LimitType.First);\n target = queryToTarget(query);\n }\n\n return this.indexManager\n .getDocumentsMatchingTarget(transaction, target)\n .next(keys => {\n debugAssert(\n !!keys,\n 'Index manager must return results for partial and full indexes.'\n );\n const sortedKeys = documentKeySet(...keys);\n return this.localDocumentsView\n .getDocuments(transaction, sortedKeys)\n .next(indexedDocuments => {\n return this.indexManager\n .getMinOffset(transaction, target)\n .next(offset => {\n const previousResults = this.applyQuery(\n query,\n indexedDocuments\n );\n\n if (\n this.needsRefill(\n query,\n previousResults,\n sortedKeys,\n offset.readTime\n )\n ) {\n // A limit query whose boundaries change due to local\n // edits can be re-run against the cache by excluding the\n // limit. This ensures that all documents that match the\n // query's filters are included in the result set. The SDK\n // can then apply the limit once all local edits are\n // incorporated.\n return this.performQueryUsingIndex(\n transaction,\n queryWithLimit(query, null, LimitType.First)\n );\n }\n\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n offset\n ) as PersistencePromise;\n });\n });\n });\n });\n }\n\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */\n private performQueryUsingRemoteKeys(\n transaction: PersistenceTransaction,\n query: Query,\n remoteKeys: DocumentKeySet,\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): PersistencePromise {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve(null);\n }\n\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) {\n return PersistencePromise.resolve(null);\n }\n\n return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(\n documents => {\n const previousResults = this.applyQuery(query, documents);\n\n if (\n this.needsRefill(\n query,\n previousResults,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n )\n ) {\n return PersistencePromise.resolve(null);\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Re-using previous result from %s to execute query: %s',\n lastLimboFreeSnapshotVersion.toString(),\n stringifyQuery(query)\n );\n }\n\n // Retrieve all results for documents that were updated since the last\n // limbo-document free remote snapshot.\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n newIndexOffsetSuccessorFromReadTime(\n lastLimboFreeSnapshotVersion,\n INITIAL_LARGEST_BATCH_ID\n )\n ).next(results => results);\n }\n );\n }\n\n /** Applies the query filter and sorting to the provided documents. */\n private applyQuery(\n query: Query,\n documents: DocumentMap\n ): SortedSet {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let queryResults = new SortedSet(newQueryComparator(query));\n documents.forEach((_, maybeDoc) => {\n if (queryMatches(query, maybeDoc)) {\n queryResults = queryResults.add(maybeDoc);\n }\n });\n return queryResults;\n }\n\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */\n private needsRefill(\n query: Query,\n sortedPreviousResults: SortedSet,\n remoteKeys: DocumentKeySet,\n limboFreeSnapshotVersion: SnapshotVersion\n ): boolean {\n if (query.limit === null) {\n // Queries without limits do not need to be refilled.\n return false;\n }\n\n if (remoteKeys.size !== sortedPreviousResults.size) {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return true;\n }\n\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const docAtLimitEdge =\n query.limitType === LimitType.First\n ? sortedPreviousResults.last()\n : sortedPreviousResults.first();\n if (!docAtLimitEdge) {\n // We don't need to refill the query if there were already no documents.\n return false;\n }\n return (\n docAtLimitEdge.hasPendingWrites ||\n docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0\n );\n }\n\n private executeFullCollectionScan(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext\n ): PersistencePromise {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Using full collection scan to execute query:',\n stringifyQuery(query)\n );\n }\n\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n IndexOffset.min(),\n context\n );\n }\n\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */\n private appendRemainingResults(\n transaction: PersistenceTransaction,\n indexedResults: Iterable,\n query: Query,\n offset: IndexOffset\n ): PersistencePromise {\n // Retrieve all results for documents that were updated since the offset.\n return this.localDocumentsView\n .getDocumentsMatchingQuery(transaction, query, offset)\n .next(remainingResults => {\n // Merge with existing results\n indexedResults.forEach(d => {\n remainingResults = remainingResults.insert(d.key, d);\n });\n return remainingResults;\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 { User } from '../auth/user';\nimport { BundleConverter, BundledDocuments, NamedQuery } from '../core/bundle';\nimport {\n newQueryForPath,\n Query,\n queryCollectionGroup,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { BatchId, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n convertOverlayedDocumentMapToDocumentMap,\n documentKeySet,\n DocumentKeySet,\n DocumentMap,\n mutableDocumentMap,\n MutableDocumentMap,\n OverlayedDocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexSemanticComparator,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport {\n mutationExtractBaseValue,\n Mutation,\n PatchMutation,\n Precondition\n} from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { extractFieldMask } from '../model/object_value';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { fromVersion, JsonProtoSerializer } from '../remote/serializer';\nimport { diffArrays } from '../util/array';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { fromBundledQuery } from './local_serializer';\nimport { LocalStore } from './local_store';\nimport { LocalViewChanges } from './local_view_changes';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryEngine } from './query_engine';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { ClientId } from './shared_client_state';\nimport { isIndexedDbTransactionError } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData, TargetPurpose } from './target_data';\n\nexport const LOG_TAG = 'LocalStore';\n\n/**\n * The maximum time to leave a resume token buffered without writing it out.\n * This value is arbitrary: it's long enough to avoid several writes\n * (possibly indefinitely if updates come more frequently than this) but\n * short enough that restarting after crashing will still have a pretty\n * recent resume token.\n */\nconst RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n\n/** The result of a write to the local store. */\nexport interface LocalWriteResult {\n batchId: BatchId;\n changes: DocumentMap;\n}\n\n/** The result of a user-change operation in the local store. */\nexport interface UserChangeResult {\n readonly affectedDocuments: DocumentMap;\n readonly removedBatchIds: BatchId[];\n readonly addedBatchIds: BatchId[];\n}\n\n/** The result of executing a query against the local store. */\nexport interface QueryResult {\n readonly documents: DocumentMap;\n readonly remoteKeys: DocumentKeySet;\n}\n\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass LocalStoreImpl implements LocalStore {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n mutationQueue!: MutationQueue;\n\n /**\n * The overlays that can be used to short circuit applying all mutations from\n * mutation queue.\n */\n documentOverlayCache!: DocumentOverlayCache;\n\n /** The set of all cached remote documents. */\n remoteDocuments: RemoteDocumentCache;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments!: LocalDocumentsView;\n\n /** Manages the list of active field and collection indices. */\n indexManager!: IndexManager;\n\n /** The set of all cached bundle metadata and named queries. */\n bundleCache: BundleCache;\n\n /** Maps a target to its `TargetData`. */\n targetCache: TargetCache;\n\n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n targetDataByTarget = new SortedMap(primitiveComparator);\n\n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n targetIdByTarget = new ObjectMap(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n collectionGroupReadTime = new Map();\n\n constructor(\n /** Manages our in-memory or durable persistence. */\n readonly persistence: Persistence,\n readonly queryEngine: QueryEngine,\n initialUser: User,\n readonly serializer: JsonProtoSerializer\n ) {\n debugAssert(\n persistence.started,\n 'LocalStore was passed an unstarted persistence implementation'\n );\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.targetCache = persistence.getTargetCache();\n this.bundleCache = persistence.getBundleCache();\n\n this.initializeUserComponents(initialUser);\n }\n\n initializeUserComponents(user: User): void {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(user);\n this.indexManager = this.persistence.getIndexManager(user);\n this.mutationQueue = this.persistence.getMutationQueue(\n user,\n this.indexManager\n );\n this.localDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n this.mutationQueue,\n this.documentOverlayCache,\n this.indexManager\n );\n this.remoteDocuments.setIndexManager(this.indexManager);\n this.queryEngine.initialize(this.localDocuments, this.indexManager);\n }\n\n collectGarbage(garbageCollector: LruGarbageCollector): Promise {\n return this.persistence.runTransaction(\n 'Collect garbage',\n 'readwrite-primary',\n txn => garbageCollector.collect(txn, this.targetDataByTarget)\n );\n }\n}\n\ninterface DocumentChangeResult {\n changedDocuments: MutableDocumentMap;\n existenceChangedKeys: DocumentKeySet;\n}\n\nexport function newLocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence: Persistence,\n queryEngine: QueryEngine,\n initialUser: User,\n serializer: JsonProtoSerializer\n): LocalStore {\n return new LocalStoreImpl(persistence, queryEngine, initialUser, serializer);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nexport async function localStoreHandleUserChange(\n localStore: LocalStore,\n user: User\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n const result = await localStoreImpl.persistence.runTransaction(\n 'Handle user change',\n 'readonly',\n txn => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let oldBatches: MutationBatch[];\n return localStoreImpl.mutationQueue\n .getAllMutationBatches(txn)\n .next(promisedOldBatches => {\n oldBatches = promisedOldBatches;\n localStoreImpl.initializeUserComponents(user);\n return localStoreImpl.mutationQueue.getAllMutationBatches(txn);\n })\n .next(newBatches => {\n const removedBatchIds: BatchId[] = [];\n const addedBatchIds: BatchId[] = [];\n\n // Union the old/new changed keys.\n let changedKeys = documentKeySet();\n\n for (const batch of oldBatches) {\n removedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n for (const batch of newBatches) {\n addedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return localStoreImpl.localDocuments\n .getDocuments(txn, changedKeys)\n .next(affectedDocuments => {\n return {\n affectedDocuments,\n removedBatchIds,\n addedBatchIds\n };\n });\n });\n }\n );\n\n return result;\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\nexport function localStoreWriteLocally(\n localStore: LocalStore,\n mutations: Mutation[]\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const localWriteTime = Timestamp.now();\n const keys = mutations.reduce((keys, m) => keys.add(m.key), documentKeySet());\n\n let overlayedDocuments: OverlayedDocumentMap;\n let mutationBatch: MutationBatch;\n\n return localStoreImpl.persistence\n .runTransaction('Locally write mutations', 'readwrite', txn => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let remoteDocs = mutableDocumentMap();\n let docsWithoutRemoteVersion = documentKeySet();\n return localStoreImpl.remoteDocuments\n .getEntries(txn, keys)\n .next(docs => {\n remoteDocs = docs;\n remoteDocs.forEach((key, doc) => {\n if (!doc.isValidDocument()) {\n docsWithoutRemoteVersion = docsWithoutRemoteVersion.add(key);\n }\n });\n })\n .next(() => {\n // Load and apply all existing mutations. This lets us compute the\n // current base state for all non-idempotent transforms before applying\n // any additional user-provided writes.\n return localStoreImpl.localDocuments.getOverlayedDocuments(\n txn,\n remoteDocs\n );\n })\n .next((docs: OverlayedDocumentMap) => {\n overlayedDocuments = docs;\n\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const baseMutations: Mutation[] = [];\n\n for (const mutation of mutations) {\n const baseValue = mutationExtractBaseValue(\n mutation,\n overlayedDocuments.get(mutation.key)!.overlayedDocument\n );\n if (baseValue != null) {\n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n baseMutations.push(\n new PatchMutation(\n mutation.key,\n baseValue,\n extractFieldMask(baseValue.value.mapValue),\n Precondition.exists(true)\n )\n );\n }\n }\n\n return localStoreImpl.mutationQueue.addMutationBatch(\n txn,\n localWriteTime,\n baseMutations,\n mutations\n );\n })\n .next(batch => {\n mutationBatch = batch;\n const overlays = batch.applyToLocalDocumentSet(\n overlayedDocuments,\n docsWithoutRemoteVersion\n );\n return localStoreImpl.documentOverlayCache.saveOverlays(\n txn,\n batch.batchId,\n overlays\n );\n });\n })\n .then(() => ({\n batchId: mutationBatch.batchId,\n changes: convertOverlayedDocumentMapToDocumentMap(overlayedDocuments)\n }));\n}\n\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nexport function localStoreAcknowledgeBatch(\n localStore: LocalStore,\n batchResult: MutationBatchResult\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Acknowledge batch',\n 'readwrite-primary',\n txn => {\n const affected = batchResult.batch.keys();\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n return applyWriteToRemoteDocuments(\n localStoreImpl,\n txn,\n batchResult,\n documentBuffer\n )\n .next(() => documentBuffer.apply(txn))\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affected,\n batchResult.batch.batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n getKeysWithTransformResults(batchResult)\n )\n )\n .next(() => localStoreImpl.localDocuments.getDocuments(txn, affected));\n }\n );\n}\n\nfunction getKeysWithTransformResults(\n batchResult: MutationBatchResult\n): DocumentKeySet {\n let result = documentKeySet();\n\n for (let i = 0; i < batchResult.mutationResults.length; ++i) {\n const mutationResult = batchResult.mutationResults[i];\n if (mutationResult.transformResults.length > 0) {\n result = result.add(batchResult.batch.mutations[i].key);\n }\n }\n return result;\n}\n\n/**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\nexport function localStoreRejectBatch(\n localStore: LocalStore,\n batchId: BatchId\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Reject batch',\n 'readwrite-primary',\n txn => {\n let affectedKeys: DocumentKeySet;\n return localStoreImpl.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next((batch: MutationBatch | null) => {\n hardAssert(batch !== null, 'Attempt to reject nonexistent batch!');\n affectedKeys = batch.keys();\n return localStoreImpl.mutationQueue.removeMutationBatch(txn, batch);\n })\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affectedKeys,\n batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n affectedKeys\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getDocuments(txn, affectedKeys)\n );\n }\n );\n}\n\n/**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */\nexport function localStoreGetHighestUnacknowledgedBatchId(\n localStore: LocalStore\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get highest unacknowledged batch id',\n 'readonly',\n txn => localStoreImpl.mutationQueue.getHighestUnacknowledgedBatchId(txn)\n );\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nexport function localStoreGetLastRemoteSnapshotVersion(\n localStore: LocalStore\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get last remote snapshot version',\n 'readonly',\n txn => localStoreImpl.targetCache.getLastRemoteSnapshotVersion(txn)\n );\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport function localStoreApplyRemoteEventToLocalCache(\n localStore: LocalStore,\n remoteEvent: RemoteEvent\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const remoteVersion = remoteEvent.snapshotVersion;\n let newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n return localStoreImpl.persistence\n .runTransaction('Apply remote event', 'readwrite-primary', txn => {\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n const promises = [] as Array>;\n remoteEvent.targetChanges.forEach((change, targetId) => {\n const oldTargetData = newTargetDataByTargetMap.get(targetId);\n if (!oldTargetData) {\n return;\n }\n\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n promises.push(\n localStoreImpl.targetCache\n .removeMatchingKeys(txn, change.removedDocuments, targetId)\n .next(() => {\n return localStoreImpl.targetCache.addMatchingKeys(\n txn,\n change.addedDocuments,\n targetId\n );\n })\n );\n\n let newTargetData = oldTargetData.withSequenceNumber(\n txn.currentSequenceNumber\n );\n if (remoteEvent.targetMismatches.get(targetId) !== null) {\n newTargetData = newTargetData\n .withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n SnapshotVersion.min()\n )\n .withLastLimboFreeSnapshotVersion(SnapshotVersion.min());\n } else if (change.resumeToken.approximateByteSize() > 0) {\n newTargetData = newTargetData.withResumeToken(\n change.resumeToken,\n remoteVersion\n );\n }\n\n newTargetDataByTargetMap = newTargetDataByTargetMap.insert(\n targetId,\n newTargetData\n );\n\n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n if (shouldPersistTargetData(oldTargetData, newTargetData, change)) {\n promises.push(\n localStoreImpl.targetCache.updateTargetData(txn, newTargetData)\n );\n }\n });\n\n let changedDocs = mutableDocumentMap();\n let existenceChangedKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(key => {\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\n promises.push(\n localStoreImpl.persistence.referenceDelegate.updateLimboDocument(\n txn,\n key\n )\n );\n }\n });\n\n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n promises.push(\n populateDocumentChangeBuffer(\n txn,\n documentBuffer,\n remoteEvent.documentUpdates\n ).next(result => {\n changedDocs = result.changedDocuments;\n existenceChangedKeys = result.existenceChangedKeys;\n })\n );\n\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (!remoteVersion.isEqual(SnapshotVersion.min())) {\n const updateRemoteVersion = localStoreImpl.targetCache\n .getLastRemoteSnapshotVersion(txn)\n .next(lastRemoteSnapshotVersion => {\n debugAssert(\n remoteVersion.compareTo(lastRemoteSnapshotVersion) >= 0,\n 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteSnapshotVersion\n );\n return localStoreImpl.targetCache.setTargetsMetadata(\n txn,\n txn.currentSequenceNumber,\n remoteVersion\n );\n });\n promises.push(updateRemoteVersion);\n }\n\n return PersistencePromise.waitFor(promises)\n .next(() => documentBuffer.apply(txn))\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n changedDocs,\n existenceChangedKeys\n )\n )\n .next(() => changedDocs);\n })\n .then(changedDocs => {\n localStoreImpl.targetDataByTarget = newTargetDataByTargetMap;\n return changedDocs;\n });\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */\nfunction populateDocumentChangeBuffer(\n txn: PersistenceTransaction,\n documentBuffer: RemoteDocumentChangeBuffer,\n documents: MutableDocumentMap\n): PersistencePromise {\n let updatedKeys = documentKeySet();\n let existenceChangedKeys = documentKeySet();\n documents.forEach(k => (updatedKeys = updatedKeys.add(k)));\n return documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => {\n let changedDocuments = mutableDocumentMap();\n documents.forEach((key, doc) => {\n const existingDoc = existingDocs.get(key)!;\n\n // Check if see if there is a existence state change for this document.\n if (doc.isFoundDocument() !== existingDoc.isFoundDocument()) {\n existenceChangedKeys = existenceChangedKeys.add(key);\n }\n\n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n if (doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min())) {\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n documentBuffer.removeEntry(key, doc.readTime);\n changedDocuments = changedDocuments.insert(key, doc);\n } else if (\n !existingDoc.isValidDocument() ||\n doc.version.compareTo(existingDoc.version) > 0 ||\n (doc.version.compareTo(existingDoc.version) === 0 &&\n existingDoc.hasPendingWrites)\n ) {\n debugAssert(\n !SnapshotVersion.min().isEqual(doc.readTime),\n 'Cannot add a document when the remote version is zero'\n );\n documentBuffer.addEntry(doc);\n changedDocuments = changedDocuments.insert(key, doc);\n } else {\n logDebug(\n LOG_TAG,\n 'Ignoring outdated watch update for ',\n key,\n '. Current version:',\n existingDoc.version,\n ' Watch version:',\n doc.version\n );\n }\n });\n return { changedDocuments, existenceChangedKeys };\n });\n}\n\n/**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\nfunction shouldPersistTargetData(\n oldTargetData: TargetData,\n newTargetData: TargetData,\n change: TargetChange\n): boolean {\n // Always persist target data if we don't already have a resume token.\n if (oldTargetData.resumeToken.approximateByteSize() === 0) {\n return true;\n }\n\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n const timeDelta =\n newTargetData.snapshotVersion.toMicroseconds() -\n oldTargetData.snapshotVersion.toMicroseconds();\n if (timeDelta >= RESUME_TOKEN_MAX_AGE_MICROS) {\n return true;\n }\n\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n const changes =\n change.addedDocuments.size +\n change.modifiedDocuments.size +\n change.removedDocuments.size;\n return changes > 0;\n}\n\n/**\n * Notifies local store of the changed views to locally pin documents.\n */\nexport async function localStoreNotifyLocalViewChanges(\n localStore: LocalStore,\n viewChanges: LocalViewChanges[]\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n try {\n await localStoreImpl.persistence.runTransaction(\n 'notifyLocalViewChanges',\n 'readwrite',\n txn => {\n return PersistencePromise.forEach(\n viewChanges,\n (viewChange: LocalViewChanges) => {\n return PersistencePromise.forEach(\n viewChange.addedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.addReference(\n txn,\n viewChange.targetId,\n key\n )\n ).next(() =>\n PersistencePromise.forEach(\n viewChange.removedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.removeReference(\n txn,\n viewChange.targetId,\n key\n )\n )\n );\n }\n );\n }\n );\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n logDebug(LOG_TAG, 'Failed to update sequence numbers: ' + e);\n } else {\n throw e;\n }\n }\n\n for (const viewChange of viewChanges) {\n const targetId = viewChange.targetId;\n\n if (!viewChange.fromCache) {\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Can't set limbo-free snapshot version for unknown target: ${targetId}`\n );\n\n // Advance the last limbo free snapshot version\n const lastLimboFreeSnapshotVersion = targetData.snapshotVersion;\n const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData);\n\n // TODO(b/272564316): Apply the optimization done on other platforms.\n // This is a problem for web because saving the updated targetData from\n // non-primary client conflicts with what primary client saved.\n }\n }\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nexport function localStoreGetNextMutationBatch(\n localStore: LocalStore,\n afterBatchId?: BatchId\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get next mutation batch',\n 'readonly',\n txn => {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return localStoreImpl.mutationQueue.getNextMutationBatchAfterBatchId(\n txn,\n afterBatchId\n );\n }\n );\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\nexport function localStoreReadDocument(\n localStore: LocalStore,\n key: DocumentKey\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'read document',\n 'readonly',\n txn => localStoreImpl.localDocuments.getDocument(txn, key)\n );\n}\n\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nexport function localStoreAllocateTarget(\n localStore: LocalStore,\n target: Target\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence\n .runTransaction('Allocate target', 'readwrite', txn => {\n let targetData: TargetData;\n return localStoreImpl.targetCache\n .getTargetData(txn, target)\n .next((cached: TargetData | null) => {\n if (cached) {\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n targetData = cached;\n return PersistencePromise.resolve(targetData);\n } else {\n return localStoreImpl.targetCache\n .allocateTargetId(txn)\n .next(targetId => {\n targetData = new TargetData(\n target,\n targetId,\n TargetPurpose.Listen,\n txn.currentSequenceNumber\n );\n return localStoreImpl.targetCache\n .addTargetData(txn, targetData)\n .next(() => targetData);\n });\n }\n });\n })\n .then(targetData => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(\n targetData.targetId\n );\n if (\n cachedTargetData === null ||\n targetData.snapshotVersion.compareTo(cachedTargetData.snapshotVersion) >\n 0\n ) {\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n targetData.targetId,\n targetData\n );\n localStoreImpl.targetIdByTarget.set(target, targetData.targetId);\n }\n return targetData;\n });\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\nexport function localStoreGetTargetData(\n localStore: LocalStore,\n transaction: PersistenceTransaction,\n target: Target\n): PersistencePromise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetId = localStoreImpl.targetIdByTarget.get(target);\n if (targetId !== undefined) {\n return PersistencePromise.resolve(\n localStoreImpl.targetDataByTarget.get(targetId)\n );\n } else {\n return localStoreImpl.targetCache.getTargetData(transaction, target);\n }\n}\n\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nexport async function localStoreReleaseTarget(\n localStore: LocalStore,\n targetId: number,\n keepPersistedTargetData: boolean\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Tried to release nonexistent target: ${targetId}`\n );\n\n const mode = keepPersistedTargetData ? 'readwrite' : 'readwrite-primary';\n\n try {\n if (!keepPersistedTargetData) {\n await localStoreImpl.persistence.runTransaction(\n 'Release target',\n mode,\n txn => {\n return localStoreImpl.persistence.referenceDelegate.removeTarget(\n txn,\n targetData!\n );\n }\n );\n }\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n logDebug(\n LOG_TAG,\n `Failed to update sequence numbers for target ${targetId}: ${e}`\n );\n } else {\n throw e;\n }\n }\n\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.remove(targetId);\n localStoreImpl.targetIdByTarget.delete(targetData!.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */\nexport function localStoreExecuteQuery(\n localStore: LocalStore,\n query: Query,\n usePreviousResults: boolean\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let lastLimboFreeSnapshotVersion = SnapshotVersion.min();\n let remoteKeys = documentKeySet();\n\n return localStoreImpl.persistence.runTransaction(\n 'Execute query',\n 'readwrite', // Use readwrite instead of readonly so indexes can be created\n txn => {\n return localStoreGetTargetData(localStoreImpl, txn, queryToTarget(query))\n .next(targetData => {\n if (targetData) {\n lastLimboFreeSnapshotVersion =\n targetData.lastLimboFreeSnapshotVersion;\n return localStoreImpl.targetCache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(result => {\n remoteKeys = result;\n });\n }\n })\n .next(() =>\n localStoreImpl.queryEngine.getDocumentsMatchingQuery(\n txn,\n query,\n usePreviousResults\n ? lastLimboFreeSnapshotVersion\n : SnapshotVersion.min(),\n usePreviousResults ? remoteKeys : documentKeySet()\n )\n )\n .next(documents => {\n setMaxReadTime(\n localStoreImpl,\n queryCollectionGroup(query),\n documents\n );\n return { documents, remoteKeys };\n });\n }\n );\n}\n\nfunction applyWriteToRemoteDocuments(\n localStoreImpl: LocalStoreImpl,\n txn: PersistenceTransaction,\n batchResult: MutationBatchResult,\n documentBuffer: RemoteDocumentChangeBuffer\n): PersistencePromise {\n const batch = batchResult.batch;\n const docKeys = batch.keys();\n let promiseChain = PersistencePromise.resolve();\n docKeys.forEach(docKey => {\n promiseChain = promiseChain\n .next(() => documentBuffer.getEntry(txn, docKey))\n .next(doc => {\n const ackVersion = batchResult.docVersions.get(docKey);\n hardAssert(\n ackVersion !== null,\n 'ackVersions should contain every doc in the write.'\n );\n if (doc.version.compareTo(ackVersion!) < 0) {\n batch.applyToRemoteDocument(doc, batchResult);\n if (doc.isValidDocument()) {\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n doc.setReadTime(batchResult.commitVersion);\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain.next(() =>\n localStoreImpl.mutationQueue.removeMutationBatch(txn, batch)\n );\n}\n\n/** Returns the local view of the documents affected by a mutation batch. */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreLookupMutationDocuments(\n localStore: LocalStore,\n batchId: BatchId\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const mutationQueueImpl = debugCast(\n localStoreImpl.mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n return localStoreImpl.persistence.runTransaction(\n 'Lookup mutation documents',\n 'readonly',\n txn => {\n return mutationQueueImpl.lookupMutationKeys(txn, batchId).next(keys => {\n if (keys) {\n return localStoreImpl.localDocuments.getDocuments(\n txn,\n keys\n ) as PersistencePromise;\n } else {\n return PersistencePromise.resolve(null);\n }\n });\n }\n );\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreRemoveCachedMutationBatchMetadata(\n localStore: LocalStore,\n batchId: BatchId\n): void {\n const mutationQueueImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n mutationQueueImpl.removeCachedMutationKeys(batchId);\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetActiveClients(\n localStore: LocalStore\n): Promise {\n const persistenceImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).persistence,\n IndexedDbPersistence // We only support IndexedDb in multi-tab mode.\n );\n return persistenceImpl.getActiveClients();\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetCachedTarget(\n localStore: LocalStore,\n targetId: TargetId\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetCacheImpl = debugCast(\n localStoreImpl.targetCache,\n IndexedDbTargetCache // We only support IndexedDb in multi-tab mode.\n );\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetId);\n if (cachedTargetData) {\n return Promise.resolve(cachedTargetData.target);\n } else {\n return localStoreImpl.persistence.runTransaction(\n 'Get target data',\n 'readonly',\n txn => {\n return targetCacheImpl\n .getTargetDataForTarget(txn, targetId)\n .next(targetData => (targetData ? targetData.target : null));\n }\n );\n }\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetNewDocumentChanges(\n localStore: LocalStore,\n collectionGroup: string\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n const readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n\n return localStoreImpl.persistence\n .runTransaction('Get new document changes', 'readonly', txn =>\n localStoreImpl.remoteDocuments.getAllFromCollectionGroup(\n txn,\n collectionGroup,\n newIndexOffsetSuccessorFromReadTime(readTime, INITIAL_LARGEST_BATCH_ID),\n /* limit= */ Number.MAX_SAFE_INTEGER\n )\n )\n .then(changedDocs => {\n setMaxReadTime(localStoreImpl, collectionGroup, changedDocs);\n return changedDocs;\n });\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction setMaxReadTime(\n localStoreImpl: LocalStoreImpl,\n collectionGroup: string,\n changedDocs: SortedMap\n): void {\n let readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n changedDocs.forEach((_, doc) => {\n if (doc.readTime.compareTo(readTime) > 0) {\n readTime = doc.readTime;\n }\n });\n localStoreImpl.collectionGroupReadTime.set(collectionGroup, readTime);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\nfunction umbrellaTarget(bundleName: string): Target {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return queryToTarget(\n newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${bundleName}`))\n );\n}\n\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport async function localStoreApplyBundledDocuments(\n localStore: LocalStore,\n bundleConverter: BundleConverter,\n documents: BundledDocuments,\n bundleName: string\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let documentKeys = documentKeySet();\n let documentMap = mutableDocumentMap();\n for (const bundleDoc of documents) {\n const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name!);\n if (bundleDoc.document) {\n documentKeys = documentKeys.add(documentKey);\n }\n const doc = bundleConverter.toMutableDocument(bundleDoc);\n doc.setReadTime(\n bundleConverter.toSnapshotVersion(bundleDoc.metadata.readTime!)\n );\n documentMap = documentMap.insert(documentKey, doc);\n }\n\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n const umbrellaTargetData = await localStoreAllocateTarget(\n localStoreImpl,\n umbrellaTarget(bundleName)\n );\n return localStoreImpl.persistence.runTransaction(\n 'Apply bundle documents',\n 'readwrite',\n txn => {\n return populateDocumentChangeBuffer(txn, documentBuffer, documentMap)\n .next(documentChangeResult => {\n documentBuffer.apply(txn);\n return documentChangeResult;\n })\n .next(documentChangeResult => {\n return localStoreImpl.targetCache\n .removeMatchingKeysForTargetId(txn, umbrellaTargetData.targetId)\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n txn,\n documentKeys,\n umbrellaTargetData.targetId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n documentChangeResult.changedDocuments,\n documentChangeResult.existenceChangedKeys\n )\n )\n .next(() => documentChangeResult.changedDocuments);\n });\n }\n );\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\nexport function localStoreHasNewerBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const currentReadTime = fromVersion(bundleMetadata.createTime!);\n return localStoreImpl.persistence\n .runTransaction('hasNewerBundle', 'readonly', transaction => {\n return localStoreImpl.bundleCache.getBundleMetadata(\n transaction,\n bundleMetadata.id!\n );\n })\n .then(cached => {\n return !!cached && cached.createTime!.compareTo(currentReadTime) >= 0;\n });\n}\n\n/**\n * Saves the given `BundleMetadata` to local persistence.\n */\nexport function localStoreSaveBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save bundle',\n 'readwrite',\n transaction => {\n return localStoreImpl.bundleCache.saveBundleMetadata(\n transaction,\n bundleMetadata\n );\n }\n );\n}\n\n/**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */\nexport function localStoreGetNamedQuery(\n localStore: LocalStore,\n queryName: string\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get named query',\n 'readonly',\n transaction =>\n localStoreImpl.bundleCache.getNamedQuery(transaction, queryName)\n );\n}\n\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nexport async function localStoreSaveNamedQuery(\n localStore: LocalStore,\n query: ProtoNamedQuery,\n documents: DocumentKeySet = documentKeySet()\n): Promise {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const allocated = await localStoreAllocateTarget(\n localStore,\n queryToTarget(fromBundledQuery(query.bundledQuery!))\n );\n\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save named query',\n 'readwrite',\n transaction => {\n const readTime = fromVersion(query.readTime!);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (allocated.snapshotVersion.compareTo(readTime) >= 0) {\n return localStoreImpl.bundleCache.saveNamedQuery(transaction, query);\n }\n\n // Update existing target data because the query from the bundle is newer.\n const newTargetData = allocated.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n readTime\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n newTargetData.targetId,\n newTargetData\n );\n return localStoreImpl.targetCache\n .updateTargetData(transaction, newTargetData)\n .next(() =>\n localStoreImpl.targetCache.removeMatchingKeysForTargetId(\n transaction,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n transaction,\n documents,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.bundleCache.saveNamedQuery(transaction, query)\n );\n }\n );\n}\n\nexport async function localStoreConfigureFieldIndexes(\n localStore: LocalStore,\n newFieldIndexes: FieldIndex[]\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n const promises: Array> = [];\n return localStoreImpl.persistence.runTransaction(\n 'Configure indexes',\n 'readwrite',\n transaction =>\n indexManager\n .getFieldIndexes(transaction)\n .next(oldFieldIndexes =>\n diffArrays(\n oldFieldIndexes,\n newFieldIndexes,\n fieldIndexSemanticComparator,\n fieldIndex => {\n promises.push(\n indexManager.addFieldIndex(transaction, fieldIndex)\n );\n },\n fieldIndex => {\n promises.push(\n indexManager.deleteFieldIndex(transaction, fieldIndex)\n );\n }\n )\n )\n .next(() => PersistencePromise.waitFor(promises))\n );\n}\n\nexport function localStoreSetIndexAutoCreationEnabled(\n localStore: LocalStore,\n isEnabled: boolean\n): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n localStoreImpl.queryEngine.indexAutoCreationEnabled = isEnabled;\n}\n\nexport function localStoreDeleteAllFieldIndexes(\n localStore: LocalStore\n): Promise {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n return localStoreImpl.persistence.runTransaction(\n 'Delete All Indexes',\n 'readwrite',\n transaction => indexManager.deleteAllFieldIndexes(transaction)\n );\n}\n\n/**\n * Test-only hooks into the SDK for use exclusively by tests.\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('creating instances is not supported');\n }\n\n static setIndexAutoCreationSettings(\n localStore: LocalStore,\n settings: {\n indexAutoCreationMinCollectionSize?: number;\n relativeIndexReadCostPerDocument?: number;\n }\n ): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n if (settings.indexAutoCreationMinCollectionSize !== undefined) {\n localStoreImpl.queryEngine.indexAutoCreationMinCollectionSize =\n settings.indexAutoCreationMinCollectionSize;\n }\n if (settings.relativeIndexReadCostPerDocument !== undefined) {\n localStoreImpl.queryEngine.relativeIndexReadCostPerDocument =\n settings.relativeIndexReadCostPerDocument;\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\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n debugAssert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n// firestore_bundle_loaded_v2_\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(targetId: TargetId): QueryTargetState;\n\n /** Removes the Query Target ID association from the local client. */\n removeLocalQueryTarget(targetId: TargetId): void;\n\n /** Checks whether the target is associated with the local client. */\n isLocalQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Processes an update to a query target.\n *\n * Called by the primary client to notify secondary clients of document\n * changes or state transitions that affect the provided query target.\n */\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void;\n\n /**\n * Removes the target's metadata entry.\n *\n * Called by the primary client when all clients stopped listening to a query\n * target.\n */\n clearQueryState(targetId: TargetId): void;\n\n /**\n * Gets the active Query Targets IDs for all active clients.\n *\n * The implementation for this may require O(n) runtime, where 'n' is the size\n * of the result set.\n */\n // Visible for testing\n getAllActiveQueryTargets(): SortedSet;\n\n /**\n * Checks whether the provided target ID is currently being listened to by\n * any of the active clients.\n *\n * The implementation may require O(n*log m) runtime, where 'n' is the number\n * of clients and 'm' the number of targets.\n */\n isActiveQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Starts the SharedClientState, reads existing client data and registers\n * listeners for updates to new and existing clients.\n */\n start(): Promise;\n\n /** Shuts down the `SharedClientState` and its listeners. */\n shutdown(): void;\n\n /**\n * Changes the active user and removes all existing user-specific data. The\n * user change does not call back into SyncEngine (for example, no mutations\n * will be marked as removed).\n */\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void;\n\n /** Changes the shared online state of all clients. */\n setOnlineState(onlineState: OnlineState): void;\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n\n /**\n * Notifies other clients when remote documents have changed due to loading\n * a bundle.\n *\n * @param collectionGroups The collection groups affected by this bundle.\n */\n notifyBundleLoaded(collectionGroups: Set): void;\n}\n\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nexport class MutationMetadata {\n constructor(\n readonly user: User,\n readonly batchId: BatchId,\n readonly state: MutationBatchState,\n readonly error?: FirestoreError\n ) {\n debugAssert(\n (error !== undefined) === (state === 'rejected'),\n `MutationMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n user: User,\n batchId: BatchId,\n value: string\n ): MutationMetadata | null {\n const mutationBatch = JSON.parse(value) as MutationMetadataSchema;\n\n let validData =\n typeof mutationBatch === 'object' &&\n ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !==\n -1 &&\n (mutationBatch.error === undefined ||\n typeof mutationBatch.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && mutationBatch.error) {\n validData =\n typeof mutationBatch.error.message === 'string' &&\n typeof mutationBatch.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n mutationBatch.error.code as Code,\n mutationBatch.error.message\n );\n }\n }\n\n if (validData) {\n return new MutationMetadata(\n user,\n batchId,\n mutationBatch.state,\n firestoreError\n );\n } else {\n logError(\n LOG_TAG,\n `Failed to parse mutation state for ID '${batchId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const batchMetadata: MutationMetadataSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n batchMetadata.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(batchMetadata);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nexport class QueryTargetMetadata {\n constructor(\n readonly targetId: TargetId,\n readonly state: QueryTargetState,\n readonly error?: FirestoreError\n ) {\n debugAssert(\n (error !== undefined) === (state === 'rejected'),\n `QueryTargetMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n targetId: TargetId,\n value: string\n ): QueryTargetMetadata | null {\n const targetState = JSON.parse(value) as QueryTargetStateSchema;\n\n let validData =\n typeof targetState === 'object' &&\n ['not-current', 'current', 'rejected'].indexOf(targetState.state) !==\n -1 &&\n (targetState.error === undefined ||\n typeof targetState.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && targetState.error) {\n validData =\n typeof targetState.error.message === 'string' &&\n typeof targetState.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n targetState.error.code as Code,\n targetState.error.message\n );\n }\n }\n\n if (validData) {\n return new QueryTargetMetadata(\n targetId,\n targetState.state,\n firestoreError\n );\n } else {\n logError(\n LOG_TAG,\n `Failed to parse target state for ID '${targetId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const targetState: QueryTargetStateSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n targetState.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(targetState);\n }\n}\n\n/**\n * Metadata state of a single client denoting the query targets it is actively\n * listening to the watch.\n */\n// Visible for testing.\nexport interface ClientState {\n readonly activeTargetIds: TargetIdSet;\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */\nclass RemoteClientState implements ClientState {\n private constructor(\n readonly clientId: ClientId,\n readonly activeTargetIds: TargetIdSet\n ) {}\n\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n clientId: ClientId,\n value: string\n ): RemoteClientState | null {\n const clientState = JSON.parse(value) as ClientStateSchema;\n\n let validData =\n typeof clientState === 'object' &&\n clientState.activeTargetIds instanceof Array;\n\n let activeTargetIdsSet = targetIdSet();\n\n for (let i = 0; validData && i < clientState.activeTargetIds.length; ++i) {\n validData = isSafeInteger(clientState.activeTargetIds[i]);\n activeTargetIdsSet = activeTargetIdsSet.add(\n clientState.activeTargetIds[i]\n );\n }\n\n if (validData) {\n return new RemoteClientState(clientId, activeTargetIdsSet);\n } else {\n logError(\n LOG_TAG,\n `Failed to parse client data for instance '${clientId}': ${value}`\n );\n return null;\n }\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */\nexport class SharedOnlineState {\n constructor(readonly clientId: string, readonly onlineState: OnlineState) {}\n\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(value: string): SharedOnlineState | null {\n const onlineState = JSON.parse(value) as SharedOnlineStateSchema;\n\n const validData =\n typeof onlineState === 'object' &&\n ['Unknown', 'Online', 'Offline'].indexOf(onlineState.onlineState) !==\n -1 &&\n typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(\n onlineState.clientId,\n onlineState.onlineState as OnlineState\n );\n } else {\n logError(LOG_TAG, `Failed to parse online state: ${value}`);\n return null;\n }\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nexport class LocalClientState implements ClientState {\n activeTargetIds = targetIdSet();\n\n addQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.add(targetId);\n }\n\n removeQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.delete(targetId);\n }\n\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */\n toWebStorageJSON(): string {\n const data: ClientStateSchema = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n return JSON.stringify(data);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */\nexport class WebStorageSharedClientState implements SharedClientState {\n syncEngine: SharedClientStateSyncer | null = null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n private readonly storage: Storage;\n private readonly localClientStorageKey: string;\n private readonly sequenceNumberKey: string;\n private readonly storageListener = this.handleWebStorageEvent.bind(this);\n private readonly onlineStateKey: string;\n private readonly bundleLoadedKey: string;\n private readonly clientStateKeyRe: RegExp;\n private readonly mutationBatchKeyRe: RegExp;\n private readonly queryTargetKeyRe: RegExp;\n private activeClients = new SortedMap(\n primitiveComparator\n );\n private started = false;\n private currentUser: User;\n\n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n private earlyEvents: StorageEvent[] = [];\n\n constructor(\n private readonly window: WindowLike,\n private readonly queue: AsyncQueue,\n private readonly persistenceKey: string,\n private readonly localClientId: ClientId,\n initialUser: User\n ) {\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const escapedPersistenceKey = persistenceKey.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&'\n );\n\n this.storage = this.window.localStorage;\n this.currentUser = initialUser;\n this.localClientStorageKey = createWebStorageClientStateKey(\n this.persistenceKey,\n this.localClientId\n );\n this.sequenceNumberKey = createWebStorageSequenceNumberKey(\n this.persistenceKey\n );\n this.activeClients = this.activeClients.insert(\n this.localClientId,\n new LocalClientState()\n );\n\n this.clientStateKeyRe = new RegExp(\n `^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`\n );\n this.mutationBatchKeyRe = new RegExp(\n `^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)(?:_(.*))?$`\n );\n this.queryTargetKeyRe = new RegExp(\n `^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)$`\n );\n\n this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey);\n\n this.bundleLoadedKey = createBundleLoadedKey(this.persistenceKey);\n\n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener('storage', this.storageListener);\n }\n\n /** Returns 'true' if WebStorage is available in the current environment. */\n static isAvailable(window: WindowLike | null): window is WindowLike {\n return !!(window && window.localStorage);\n }\n\n async start(): Promise {\n debugAssert(!this.started, 'WebStorageSharedClientState already started');\n debugAssert(\n this.syncEngine !== null,\n 'syncEngine property must be set before calling start()'\n );\n debugAssert(\n this.onlineStateHandler !== null,\n 'onlineStateHandler property must be set before calling start()'\n );\n\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const existingClients = await this.syncEngine!.getActiveClients();\n\n for (const clientId of existingClients) {\n if (clientId === this.localClientId) {\n continue;\n }\n\n const storageItem = this.getItem(\n createWebStorageClientStateKey(this.persistenceKey, clientId)\n );\n if (storageItem) {\n const clientState = RemoteClientState.fromWebStorageEntry(\n clientId,\n storageItem\n );\n if (clientState) {\n this.activeClients = this.activeClients.insert(\n clientState.clientId,\n clientState\n );\n }\n }\n }\n\n this.persistClientState();\n\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const onlineStateJSON = this.storage.getItem(this.onlineStateKey);\n if (onlineStateJSON) {\n const onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\n if (onlineState) {\n this.handleOnlineStateEvent(onlineState);\n }\n }\n\n for (const event of this.earlyEvents) {\n this.handleWebStorageEvent(event);\n }\n\n this.earlyEvents = [];\n\n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener('pagehide', () => this.shutdown());\n\n this.started = true;\n }\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {\n this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.extractActiveQueryTargets(this.activeClients);\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n let found = false;\n this.activeClients.forEach((key, value) => {\n if (value.activeTargetIds.has(targetId)) {\n found = true;\n }\n });\n return found;\n }\n\n addPendingMutation(batchId: BatchId): void {\n this.persistMutationState(batchId, 'pending');\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n this.persistMutationState(batchId, state, error);\n\n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.removeMutationState(batchId);\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n let queryState: QueryTargetState = 'not-current';\n\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(targetId)) {\n const storageItem = this.storage.getItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n\n if (storageItem) {\n const metadata = QueryTargetMetadata.fromWebStorageEntry(\n targetId,\n storageItem\n );\n if (metadata) {\n queryState = metadata.state;\n }\n }\n }\n\n this.localClientState.addQueryTarget(targetId);\n this.persistClientState();\n\n return queryState;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localClientState.removeQueryTarget(targetId);\n this.persistClientState();\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localClientState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n this.removeItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.persistQueryTargetState(targetId, state, error);\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n removedBatchIds.forEach(batchId => {\n this.removeMutationState(batchId);\n });\n this.currentUser = user;\n addedBatchIds.forEach(batchId => {\n this.addPendingMutation(batchId);\n });\n }\n\n setOnlineState(onlineState: OnlineState): void {\n this.persistOnlineState(onlineState);\n }\n\n notifyBundleLoaded(collectionGroups: Set): void {\n this.persistBundleLoadedState(collectionGroups);\n }\n\n shutdown(): void {\n if (this.started) {\n this.window.removeEventListener('storage', this.storageListener);\n this.removeItem(this.localClientStorageKey);\n this.started = false;\n }\n }\n\n private getItem(key: string): string | null {\n const value = this.storage.getItem(key);\n logDebug(LOG_TAG, 'READ', key, value);\n return value;\n }\n\n private setItem(key: string, value: string): void {\n logDebug(LOG_TAG, 'SET', key, value);\n this.storage.setItem(key, value);\n }\n\n private removeItem(key: string): void {\n logDebug(LOG_TAG, 'REMOVE', key);\n this.storage.removeItem(key);\n }\n\n private handleWebStorageEvent(event: Event): void {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const storageEvent = event as StorageEvent;\n if (storageEvent.storageArea === this.storage) {\n logDebug(LOG_TAG, 'EVENT', storageEvent.key, storageEvent.newValue);\n\n if (storageEvent.key === this.localClientStorageKey) {\n logError(\n 'Received WebStorage notification for local change. Another client might have ' +\n 'garbage-collected our state'\n );\n return;\n }\n\n this.queue.enqueueRetryable(async () => {\n if (!this.started) {\n this.earlyEvents.push(storageEvent);\n return;\n }\n\n if (storageEvent.key === null) {\n return;\n }\n\n if (this.clientStateKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue != null) {\n const clientState = this.fromWebStorageClientState(\n storageEvent.key,\n storageEvent.newValue\n );\n if (clientState) {\n return this.handleClientStateEvent(\n clientState.clientId,\n clientState\n );\n }\n } else {\n const clientId = this.fromWebStorageClientStateKey(\n storageEvent.key\n )!;\n return this.handleClientStateEvent(clientId, null);\n }\n } else if (this.mutationBatchKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const mutationMetadata = this.fromWebStorageMutationMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (mutationMetadata) {\n return this.handleMutationBatchEvent(mutationMetadata);\n }\n }\n } else if (this.queryTargetKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (queryTargetMetadata) {\n return this.handleQueryTargetEvent(queryTargetMetadata);\n }\n }\n } else if (storageEvent.key === this.onlineStateKey) {\n if (storageEvent.newValue !== null) {\n const onlineState = this.fromWebStorageOnlineState(\n storageEvent.newValue\n );\n if (onlineState) {\n return this.handleOnlineStateEvent(onlineState);\n }\n }\n } else if (storageEvent.key === this.sequenceNumberKey) {\n debugAssert(\n !!this.sequenceNumberHandler,\n 'Missing sequenceNumberHandler'\n );\n const sequenceNumber = fromWebStorageSequenceNumber(\n storageEvent.newValue\n );\n if (sequenceNumber !== ListenSequence.INVALID) {\n this.sequenceNumberHandler!(sequenceNumber);\n }\n } else if (storageEvent.key === this.bundleLoadedKey) {\n const collectionGroups = this.fromWebStoreBundleLoadedState(\n storageEvent.newValue!\n );\n await Promise.all(\n collectionGroups.map(cg =>\n this.syncEngine!.synchronizeWithChangedDocuments(cg)\n )\n );\n }\n });\n }\n }\n\n private get localClientState(): LocalClientState {\n return this.activeClients.get(this.localClientId) as LocalClientState;\n }\n\n private persistClientState(): void {\n this.setItem(\n this.localClientStorageKey,\n this.localClientState.toWebStorageJSON()\n );\n }\n\n private persistMutationState(\n batchId: BatchId,\n state: MutationBatchState,\n error?: FirestoreError\n ): void {\n const mutationState = new MutationMetadata(\n this.currentUser,\n batchId,\n state,\n error\n );\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\n }\n\n private removeMutationState(batchId: BatchId): void {\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.removeItem(mutationKey);\n }\n\n private persistOnlineState(onlineState: OnlineState): void {\n const entry: SharedOnlineStateSchema = {\n clientId: this.localClientId,\n onlineState\n };\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n }\n\n private persistQueryTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n const targetKey = createWebStorageQueryTargetMetadataKey(\n this.persistenceKey,\n targetId\n );\n const targetMetadata = new QueryTargetMetadata(targetId, state, error);\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n }\n\n private persistBundleLoadedState(collectionGroups: Set): void {\n const json = JSON.stringify(Array.from(collectionGroups));\n this.setItem(this.bundleLoadedKey, json);\n }\n\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */\n private fromWebStorageClientStateKey(key: string): ClientId | null {\n const match = this.clientStateKeyRe.exec(key);\n return match ? match[1] : null;\n }\n\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */\n private fromWebStorageClientState(\n key: string,\n value: string\n ): RemoteClientState | null {\n const clientId = this.fromWebStorageClientStateKey(key);\n debugAssert(clientId !== null, `Cannot parse client state key '${key}'`);\n return RemoteClientState.fromWebStorageEntry(clientId, value);\n }\n\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageMutationMetadata(\n key: string,\n value: string\n ): MutationMetadata | null {\n const match = this.mutationBatchKeyRe.exec(key);\n debugAssert(match !== null, `Cannot parse mutation batch key '${key}'`);\n\n const batchId = Number(match[1]);\n const userId = match[2] !== undefined ? match[2] : null;\n return MutationMetadata.fromWebStorageEntry(\n new User(userId),\n batchId,\n value\n );\n }\n\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageQueryTargetMetadata(\n key: string,\n value: string\n ): QueryTargetMetadata | null {\n const match = this.queryTargetKeyRe.exec(key);\n debugAssert(match !== null, `Cannot parse query target key '${key}'`);\n\n const targetId = Number(match[1]);\n return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\n }\n\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageOnlineState(value: string): SharedOnlineState | null {\n return SharedOnlineState.fromWebStorageEntry(value);\n }\n\n private fromWebStoreBundleLoadedState(value: string): string[] {\n return JSON.parse(value) as string[];\n }\n\n private async handleMutationBatchEvent(\n mutationBatch: MutationMetadata\n ): Promise {\n if (mutationBatch.user.uid !== this.currentUser.uid) {\n logDebug(\n LOG_TAG,\n `Ignoring mutation for non-active user ${mutationBatch.user.uid}`\n );\n return;\n }\n\n return this.syncEngine!.applyBatchState(\n mutationBatch.batchId,\n mutationBatch.state,\n mutationBatch.error\n );\n }\n\n private handleQueryTargetEvent(\n targetMetadata: QueryTargetMetadata\n ): Promise {\n return this.syncEngine!.applyTargetState(\n targetMetadata.targetId,\n targetMetadata.state,\n targetMetadata.error\n );\n }\n\n private handleClientStateEvent(\n clientId: ClientId,\n clientState: RemoteClientState | null\n ): Promise {\n const updatedClients = clientState\n ? this.activeClients.insert(clientId, clientState)\n : this.activeClients.remove(clientId);\n\n const existingTargets = this.extractActiveQueryTargets(this.activeClients);\n const newTargets = this.extractActiveQueryTargets(updatedClients);\n\n const addedTargets: TargetId[] = [];\n const removedTargets: TargetId[] = [];\n\n newTargets.forEach(targetId => {\n if (!existingTargets.has(targetId)) {\n addedTargets.push(targetId);\n }\n });\n\n existingTargets.forEach(targetId => {\n if (!newTargets.has(targetId)) {\n removedTargets.push(targetId);\n }\n });\n\n return this.syncEngine!.applyActiveTargetsChange(\n addedTargets,\n removedTargets\n ).then(() => {\n this.activeClients = updatedClients;\n });\n }\n\n private handleOnlineStateEvent(onlineState: SharedOnlineState): void {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n if (this.activeClients.get(onlineState.clientId)) {\n this.onlineStateHandler!(onlineState.onlineState);\n }\n }\n\n private extractActiveQueryTargets(\n clients: SortedMap\n ): SortedSet {\n let activeTargets = targetIdSet();\n clients.forEach((kev, value) => {\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\n });\n return activeTargets;\n }\n}\n\nfunction fromWebStorageSequenceNumber(\n seqString: string | null\n): ListenSequenceNumber {\n let sequenceNumber = ListenSequence.INVALID;\n if (seqString != null) {\n try {\n const parsed = JSON.parse(seqString);\n hardAssert(\n typeof parsed === 'number',\n 'Found non-numeric sequence number'\n );\n sequenceNumber = parsed;\n } catch (e) {\n logError(LOG_TAG, 'Failed to read sequence number from WebStorage', e);\n }\n }\n return sequenceNumber;\n}\n\n/**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */\nexport class MemorySharedClientState implements SharedClientState {\n private localState = new LocalClientState();\n private queryState: { [targetId: number]: QueryTargetState } = {};\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n addPendingMutation(batchId: BatchId): void {\n // No op.\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n // No op.\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n this.localState.addQueryTarget(targetId);\n return this.queryState[targetId] || 'not-current';\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.queryState[targetId] = state;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localState.removeQueryTarget(targetId);\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n delete this.queryState[targetId];\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.localState.activeTargetIds;\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n start(): Promise {\n this.localState = new LocalClientState();\n return Promise.resolve();\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n // No op.\n }\n\n setOnlineState(onlineState: OnlineState): void {\n // No op.\n }\n\n shutdown(): void {}\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {}\n\n notifyBundleLoaded(collectionGroups: Set): void {\n // No op.\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\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\n\nexport class NoopConnectivityMonitor implements ConnectivityMonitor {\n addCallback(callback: (status: NetworkStatus) => void): void {\n // No-op.\n }\n\n shutdown(): void {\n // No-op.\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\nimport {\n ConnectivityMonitor,\n ConnectivityMonitorCallback,\n NetworkStatus\n} from '../../remote/connectivity_monitor';\nimport { logDebug } from '../../util/log';\n\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'ConnectivityMonitor';\n\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nexport class BrowserConnectivityMonitor implements ConnectivityMonitor {\n private readonly networkAvailableListener = (): void =>\n this.onNetworkAvailable();\n private readonly networkUnavailableListener = (): void =>\n this.onNetworkUnavailable();\n private callbacks: ConnectivityMonitorCallback[] = [];\n\n constructor() {\n this.configureNetworkMonitoring();\n }\n\n addCallback(callback: (status: NetworkStatus) => void): void {\n this.callbacks.push(callback);\n }\n\n shutdown(): void {\n window.removeEventListener('online', this.networkAvailableListener);\n window.removeEventListener('offline', this.networkUnavailableListener);\n }\n\n private configureNetworkMonitoring(): void {\n window.addEventListener('online', this.networkAvailableListener);\n window.addEventListener('offline', this.networkUnavailableListener);\n }\n\n private onNetworkAvailable(): void {\n logDebug(LOG_TAG, 'Network connectivity changed: AVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.AVAILABLE);\n }\n }\n\n private onNetworkUnavailable(): void {\n logDebug(LOG_TAG, 'Network connectivity changed: UNAVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.UNAVAILABLE);\n }\n }\n\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static isAvailable(): boolean {\n return (\n typeof window !== 'undefined' &&\n window.addEventListener !== undefined &&\n window.removeEventListener !== undefined\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\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\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 { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n return this.performRPCRequest(rpcName, url, headers, req).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\n\nimport { Stream } from './connection';\n\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nexport class StreamBridge implements Stream {\n private wrappedOnConnected: (() => void) | undefined;\n private wrappedOnOpen: (() => void) | undefined;\n private wrappedOnClose: ((err?: FirestoreError) => void) | undefined;\n private wrappedOnMessage: ((msg: O) => void) | undefined;\n\n private sendFn: (msg: I) => void;\n private closeFn: () => void;\n\n constructor(args: { sendFn: (msg: I) => void; closeFn: () => void }) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n\n onConnected(callback: () => void): void {\n debugAssert(\n !this.wrappedOnConnected,\n 'Called onConnected on stream twice!'\n );\n this.wrappedOnConnected = callback;\n }\n\n onOpen(callback: () => void): void {\n debugAssert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n }\n\n onClose(callback: (err?: FirestoreError) => void): void {\n debugAssert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n }\n\n onMessage(callback: (msg: O) => void): void {\n debugAssert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n }\n\n close(): void {\n this.closeFn();\n }\n\n send(msg: I): void {\n this.sendFn(msg);\n }\n\n callOnConnected(): void {\n debugAssert(\n this.wrappedOnConnected !== undefined,\n 'Cannot call onConnected because no callback was set'\n );\n this.wrappedOnConnected();\n }\n\n callOnOpen(): void {\n debugAssert(\n this.wrappedOnOpen !== undefined,\n 'Cannot call onOpen because no callback was set'\n );\n this.wrappedOnOpen();\n }\n\n callOnClose(err?: FirestoreError): void {\n debugAssert(\n this.wrappedOnClose !== undefined,\n 'Cannot call onClose because no callback was set'\n );\n this.wrappedOnClose(err);\n }\n\n callOnMessage(msg: O): void {\n debugAssert(\n this.wrappedOnMessage !== undefined,\n 'Cannot call onMessage because no callback was set'\n );\n this.wrappedOnMessage(msg);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 createWebChannelTransport,\n ErrorCode,\n EventType,\n WebChannel,\n WebChannelError,\n WebChannelOptions,\n XhrIo,\n getStatEventTarget,\n EventTarget,\n StatEvent,\n Event,\n FetchXmlHttpFactory,\n Stat\n} from '@firebase/webchannel-wrapper/webchannel-blob';\n\nimport { Token } from '../../api/credentials';\nimport { ExperimentalLongPollingOptions } from '../../api/long_polling_options';\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport {\n mapCodeFromRpcStatus,\n mapCodeFromHttpResponseErrorStatus\n} from '../../remote/rpc_error';\nimport { StreamBridge } from '../../remote/stream_bridge';\nimport { fail, hardAssert } from '../../util/assert';\nimport { generateUniqueDebugId } from '../../util/debug_uid';\nimport { Code, FirestoreError } from '../../util/error';\nimport { logDebug, logWarn } from '../../util/log';\nimport { Rejecter, Resolver } from '../../util/promise';\nimport { StringMap } from '../../util/types';\n\nconst LOG_TAG = 'WebChannelConnection';\n\nconst RPC_STREAM_SERVICE = 'google.firestore.v1.Firestore';\n\nconst XHR_TIMEOUT_SECS = 15;\n\nexport class WebChannelConnection extends RestConnection {\n private readonly forceLongPolling: boolean;\n private readonly autoDetectLongPolling: boolean;\n private readonly useFetchStreams: boolean;\n private readonly longPollingOptions: ExperimentalLongPollingOptions;\n\n constructor(info: DatabaseInfo) {\n super(info);\n this.forceLongPolling = info.forceLongPolling;\n this.autoDetectLongPolling = info.autoDetectLongPolling;\n this.useFetchStreams = info.useFetchStreams;\n this.longPollingOptions = info.longPollingOptions;\n }\n\n protected performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise {\n const streamId = generateUniqueDebugId();\n return new Promise((resolve: Resolver, reject: Rejecter) => {\n const xhr = new XhrIo();\n xhr.setWithCredentials(true);\n xhr.listenOnce(EventType.COMPLETE, () => {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const json = xhr.getResponseJson() as Resp;\n logDebug(\n LOG_TAG,\n `XHR for RPC '${rpcName}' ${streamId} received:`,\n JSON.stringify(json)\n );\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} timed out`);\n reject(\n new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out')\n );\n break;\n case ErrorCode.HTTP_ERROR:\n const status = xhr.getStatus();\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with status:`,\n status,\n 'response text:',\n xhr.getResponseText()\n );\n if (status > 0) {\n let response = xhr.getResponseJson();\n if (Array.isArray(response)) {\n response = response[0];\n }\n const responseError = (response as WebChannelError)?.error;\n if (\n !!responseError &&\n !!responseError.status &&\n !!responseError.message\n ) {\n const firestoreErrorCode = mapCodeFromHttpResponseErrorStatus(\n responseError.status\n );\n reject(\n new FirestoreError(\n firestoreErrorCode,\n responseError.message\n )\n );\n } else {\n reject(\n new FirestoreError(\n Code.UNKNOWN,\n 'Server responded with status ' + xhr.getStatus()\n )\n );\n }\n } else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n reject(\n new FirestoreError(Code.UNAVAILABLE, 'Connection failed.')\n );\n }\n break;\n default:\n fail(\n `RPC '${rpcName}' ${streamId} ` +\n 'failed with unanticipated webchannel error: ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.'\n );\n }\n } finally {\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} completed.`);\n }\n });\n\n const requestString = JSON.stringify(body);\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} sending request:`, body);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n }\n\n openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\n const streamId = generateUniqueDebugId();\n const urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n const webchannelTransport = createWebChannelTransport();\n const requestStats = getStatEventTarget();\n const request: WebChannelOptions = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: true,\n supportsCrossDomainXhr: true,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 10 * 60 * 1000\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n };\n\n const longPollingTimeoutSeconds = this.longPollingOptions.timeoutSeconds;\n if (longPollingTimeoutSeconds !== undefined) {\n request.longPollingTimeout = Math.round(longPollingTimeoutSeconds * 1000);\n }\n\n if (this.useFetchStreams) {\n request.xmlHttpFactory = new FetchXmlHttpFactory({});\n }\n\n this.modifyHeadersForRequest(\n request.initMessageHeaders!,\n authToken,\n appCheckToken\n );\n\n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n //\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n request.encodeInitMessageHeaders = true;\n\n const url = urlParts.join('');\n logDebug(\n LOG_TAG,\n `Creating RPC '${rpcName}' stream ${streamId}: ${url}`,\n request\n );\n const channel = webchannelTransport.createWebChannel(url, request);\n\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let opened = false;\n\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n let closed = false;\n\n const streamBridge = new StreamBridge({\n sendFn: (msg: Req) => {\n if (!closed) {\n if (!opened) {\n logDebug(\n LOG_TAG,\n `Opening RPC '${rpcName}' stream ${streamId} transport.`\n );\n channel.open();\n opened = true;\n }\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} sending:`,\n msg\n );\n channel.send(msg);\n } else {\n logDebug(\n LOG_TAG,\n `Not sending because RPC '${rpcName}' stream ${streamId} ` +\n 'is closed:',\n msg\n );\n }\n },\n closeFn: () => channel.close()\n });\n\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n const unguardedEventListen = (\n target: EventTarget,\n type: string | number,\n fn: (param: T) => void\n ): void => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n target.listen(type, (param: unknown) => {\n try {\n fn(param as T);\n } catch (e) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n });\n };\n\n unguardedEventListen(channel, WebChannel.EventType.OPEN, () => {\n if (!closed) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport opened.`\n );\n streamBridge.callOnConnected();\n }\n });\n\n unguardedEventListen(channel, WebChannel.EventType.CLOSE, () => {\n if (!closed) {\n closed = true;\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport closed`\n );\n streamBridge.callOnClose();\n }\n });\n\n unguardedEventListen(channel, WebChannel.EventType.ERROR, err => {\n if (!closed) {\n closed = true;\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport errored:`,\n err\n );\n streamBridge.callOnClose(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'The operation could not be completed'\n )\n );\n }\n });\n\n // WebChannel delivers message events as array. If batching is not enabled\n // (it's off by default) each message will be delivered alone, resulting in\n // a single element array.\n interface WebChannelResponse {\n data: Resp[];\n }\n\n unguardedEventListen(\n channel,\n WebChannel.EventType.MESSAGE,\n msg => {\n if (!closed) {\n const msgData = msg.data[0];\n hardAssert(!!msgData, 'Got a webchannel message without data.');\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const msgDataOrError: WebChannelError | object = msgData;\n const error =\n msgDataOrError.error ||\n (msgDataOrError as WebChannelError[])[0]?.error;\n if (error) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received error:`,\n error\n );\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const status: string = error.status;\n let code = mapCodeFromRpcStatus(status);\n let message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n } else {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received:`,\n msgData\n );\n streamBridge.callOnMessage(msgData);\n }\n }\n }\n );\n\n unguardedEventListen(requestStats, Event.STAT_EVENT, event => {\n if (event.stat === Stat.PROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected buffering proxy`\n );\n } else if (event.stat === Stat.NOPROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected no buffering proxy`\n );\n }\n });\n\n setTimeout(() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\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/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\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/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ 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 { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider, Token } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetData } from '../local/target_data';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport {\n ListenRequest as ProtoListenRequest,\n ListenResponse as ProtoListenResponse,\n WriteRequest as ProtoWriteRequest,\n WriteResponse as ProtoWriteResponse\n} from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExponentialBackoff } from './backoff';\nimport { Connection, Stream } from './connection';\nimport {\n fromVersion,\n fromWatchChange,\n fromWriteResults,\n getEncodedDatabaseId,\n JsonProtoSerializer,\n toListenRequestLabels,\n toMutation,\n toTarget,\n versionFromListenResponse\n} from './serializer';\nimport { WatchChange } from './watch_change';\n\nconst LOG_TAG = 'PersistentStream';\n\n// The generated proto interfaces for these class are missing the database\n// field. So we add it here.\n// TODO(b/36015800): Remove this once the api generator is fixed.\ninterface ListenRequest extends ProtoListenRequest {\n database?: string;\n}\nexport interface WriteRequest extends ProtoWriteRequest {\n database?: string;\n}\n/**\n * PersistentStream can be in one of 5 states (each described in detail below)\n * based on the following state transition diagram:\n *\n * start() called auth & connection succeeded\n * INITIAL ----------------> STARTING -----------------------------> OPEN\n * ^ | |\n * | | error occurred |\n * | \\-----------------------------v-----/\n * | |\n * backoff | |\n * elapsed | start() called |\n * \\--- BACKOFF <---------------- ERROR\n *\n * [any state] --------------------------> INITIAL\n * stop() called or\n * idle timer expired\n */\nconst enum PersistentStreamState {\n /**\n * The streaming RPC is not yet running and there's no error condition.\n * Calling start() will start the stream immediately without backoff.\n * While in this state isStarted() will return false.\n */\n Initial,\n\n /**\n * The stream is starting, either waiting for an auth token or for the stream\n * to successfully open. While in this state, isStarted() will return true but\n * isOpen() will return false.\n */\n Starting,\n\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted() and isOpen() will return true.\n */\n Open,\n\n /**\n * The stream is healthy and has been connected for more than 10 seconds. We\n * therefore assume that the credentials we passed were valid. Both\n * isStarted() and isOpen() will return true.\n */\n Healthy,\n\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n */\n Error,\n\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After waiting is complete, the stream will try to open.\n * While in this state isStarted() will return true but isOpen() will return\n * false.\n */\n Backoff\n}\n\n/**\n * Provides a common interface that is shared by the listeners for stream\n * events by the concrete implementation classes.\n */\nexport interface PersistentStreamListener {\n /**\n * Called after receiving an acknowledgement from the server, confirming that\n * we are able to connect to it.\n */\n onConnected: () => Promise;\n /**\n * Called after the stream was established and can accept outgoing\n * messages\n */\n onOpen: () => Promise;\n /**\n * Called after the stream has closed. If there was an error, the\n * FirestoreError will be set.\n */\n onClose: (err?: FirestoreError) => Promise;\n}\n\n/** The time a stream stays open after it is marked idle. */\nconst IDLE_TIMEOUT_MS = 60 * 1000;\n\n/** The time a stream stays open until we consider it healthy. */\nconst HEALTHY_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nexport abstract class PersistentStream<\n SendType,\n ReceiveType,\n ListenerType extends PersistentStreamListener\n> {\n private state = PersistentStreamState.Initial;\n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n private closeCount = 0;\n\n private idleTimer: DelayedOperation | null = null;\n private healthCheck: DelayedOperation | null = null;\n private stream: Stream | null = null;\n\n protected backoff: ExponentialBackoff;\n\n constructor(\n private queue: AsyncQueue,\n connectionTimerId: TimerId,\n private idleTimerId: TimerId,\n private healthTimerId: TimerId,\n protected connection: Connection,\n private authCredentialsProvider: CredentialsProvider,\n private appCheckCredentialsProvider: CredentialsProvider,\n protected listener: ListenerType\n ) {\n this.backoff = new ExponentialBackoff(queue, connectionTimerId);\n }\n\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */\n isStarted(): boolean {\n return (\n this.state === PersistentStreamState.Starting ||\n this.state === PersistentStreamState.Backoff ||\n this.isOpen()\n );\n }\n\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */\n isOpen(): boolean {\n return (\n this.state === PersistentStreamState.Open ||\n this.state === PersistentStreamState.Healthy\n );\n }\n\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */\n start(): void {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n\n debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Already started'\n );\n this.auth();\n }\n\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */\n async stop(): Promise {\n if (this.isStarted()) {\n await this.close(PersistentStreamState.Initial);\n }\n }\n\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */\n inhibitBackoff(): void {\n debugAssert(\n !this.isStarted(),\n 'Can only inhibit backoff in a stopped state'\n );\n\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n }\n\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */\n markIdle(): void {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n if (this.isOpen() && this.idleTimer === null) {\n this.idleTimer = this.queue.enqueueAfterDelay(\n this.idleTimerId,\n IDLE_TIMEOUT_MS,\n () => this.handleIdleCloseTimer()\n );\n }\n }\n\n /** Sends a message to the underlying stream. */\n protected sendRequest(msg: SendType): void {\n this.cancelIdleCheck();\n this.stream!.send(msg);\n }\n\n /** Called by the idle timer when the stream should close due to inactivity. */\n private async handleIdleCloseTimer(): Promise {\n if (this.isOpen()) {\n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(PersistentStreamState.Initial);\n }\n }\n\n /** Marks the stream as active again. */\n private cancelIdleCheck(): void {\n if (this.idleTimer) {\n this.idleTimer.cancel();\n this.idleTimer = null;\n }\n }\n\n /** Cancels the health check delayed operation. */\n private cancelHealthCheck(): void {\n if (this.healthCheck) {\n this.healthCheck.cancel();\n this.healthCheck = null;\n }\n }\n\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */\n private async close(\n finalState: PersistentStreamState,\n error?: FirestoreError\n ): Promise {\n debugAssert(this.isStarted(), 'Only started streams should be closed.');\n debugAssert(\n finalState === PersistentStreamState.Error || isNullOrUndefined(error),\n \"Can't provide an error when not in an error state.\"\n );\n\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.cancelIdleCheck();\n this.cancelHealthCheck();\n this.backoff.cancel();\n\n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.closeCount++;\n\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n } else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n logError(error.toString());\n logError(\n 'Using maximum backoff delay to prevent overloading the backend.'\n );\n this.backoff.resetToMax();\n } else if (\n error &&\n error.code === Code.UNAUTHENTICATED &&\n this.state !== PersistentStreamState.Healthy\n ) {\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken();\n this.appCheckCredentialsProvider.invalidateToken();\n }\n\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\n\n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = finalState;\n\n // Notify the listener that the stream closed.\n await this.listener.onClose(error);\n }\n\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n protected tearDown(): void {}\n\n /**\n * Used by subclasses to start the concrete RPC and return the underlying\n * connection stream.\n */\n protected abstract startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Called after the stream has received a message. The function will be\n * called on the right queue and must return a Promise.\n * @param message - The message received from the stream.\n */\n protected abstract onMessage(message: ReceiveType): Promise;\n\n private auth(): void {\n debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Must be in initial state to auth'\n );\n\n this.state = PersistentStreamState.Starting;\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n const closeCount = this.closeCount;\n\n Promise.all([\n this.authCredentialsProvider.getToken(),\n this.appCheckCredentialsProvider.getToken()\n ]).then(\n ([authToken, appCheckToken]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n if (this.closeCount === closeCount) {\n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.startStream(authToken, appCheckToken);\n }\n },\n (error: Error) => {\n dispatchIfNotClosed(() => {\n const rpcError = new FirestoreError(\n Code.UNKNOWN,\n 'Fetching auth token failed: ' + error.message\n );\n return this.handleStreamClose(rpcError);\n });\n }\n );\n }\n\n private startStream(\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Trying to start stream in a non-starting state'\n );\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n this.stream = this.startRpc(authToken, appCheckToken);\n this.stream.onConnected(() => {\n dispatchIfNotClosed(() => this.listener!.onConnected());\n });\n this.stream.onOpen(() => {\n dispatchIfNotClosed(() => {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Expected stream to be in state Starting, but was ' + this.state\n );\n this.state = PersistentStreamState.Open;\n debugAssert(\n this.healthCheck === null,\n 'Expected healthCheck to be null'\n );\n this.healthCheck = this.queue.enqueueAfterDelay(\n this.healthTimerId,\n HEALTHY_TIMEOUT_MS,\n () => {\n if (this.isOpen()) {\n this.state = PersistentStreamState.Healthy;\n }\n return Promise.resolve();\n }\n );\n return this.listener!.onOpen();\n });\n });\n this.stream.onClose((error?: FirestoreError) => {\n dispatchIfNotClosed(() => {\n return this.handleStreamClose(error);\n });\n });\n this.stream.onMessage((msg: ReceiveType) => {\n dispatchIfNotClosed(() => {\n return this.onMessage(msg);\n });\n });\n }\n\n private performBackoff(): void {\n debugAssert(\n this.state === PersistentStreamState.Error,\n 'Should only perform backoff when in Error state'\n );\n this.state = PersistentStreamState.Backoff;\n\n this.backoff.backoffAndRun(async () => {\n debugAssert(\n this.state === PersistentStreamState.Backoff,\n 'Backoff elapsed but state is now: ' + this.state\n );\n\n this.state = PersistentStreamState.Initial;\n this.start();\n debugAssert(this.isStarted(), 'PersistentStream should have started');\n });\n }\n\n // Visible for tests\n handleStreamClose(error?: FirestoreError): Promise {\n debugAssert(\n this.isStarted(),\n \"Can't handle server close on non-started stream\"\n );\n logDebug(LOG_TAG, `close with error: ${error}`);\n\n this.stream = null;\n\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return this.close(PersistentStreamState.Error, error);\n }\n\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */\n private getCloseGuardedDispatcher(\n startCloseCount: number\n ): (fn: () => Promise) => void {\n return (fn: () => Promise): void => {\n this.queue.enqueueAndForget(() => {\n if (this.closeCount === startCloseCount) {\n return fn();\n } else {\n logDebug(\n LOG_TAG,\n 'stream callback skipped by getCloseGuardedDispatcher.'\n );\n return Promise.resolve();\n }\n });\n };\n }\n}\n\n/** Listener for the PersistentWatchStream */\nexport interface WatchStreamListener extends PersistentStreamListener {\n /**\n * Called on a watchChange. The snapshot parameter will be MIN if the watch\n * change did not have a snapshot associated with it.\n */\n onWatchChange: (\n watchChange: WatchChange,\n snapshot: SnapshotVersion\n ) => Promise;\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */\nexport class PersistentListenStream extends PersistentStream<\n ProtoListenRequest,\n ProtoListenResponse,\n WatchStreamListener\n> {\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n private serializer: JsonProtoSerializer,\n listener: WatchStreamListener\n ) {\n super(\n queue,\n TimerId.ListenStreamConnectionBackoff,\n TimerId.ListenStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\n return this.connection.openStream(\n 'Listen',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(watchChangeProto: ProtoListenResponse): Promise {\n // A successful response means the stream is healthy\n this.backoff.reset();\n\n const watchChange = fromWatchChange(this.serializer, watchChangeProto);\n const snapshot = versionFromListenResponse(watchChangeProto);\n return this.listener!.onWatchChange(watchChange, snapshot);\n }\n\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n watch(targetData: TargetData): void {\n const request: ListenRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n request.addTarget = toTarget(this.serializer, targetData);\n\n const labels = toListenRequestLabels(this.serializer, targetData);\n if (labels) {\n request.labels = labels;\n }\n\n this.sendRequest(request);\n }\n\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */\n unwatch(targetId: TargetId): void {\n const request: ListenRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n request.removeTarget = targetId;\n this.sendRequest(request);\n }\n}\n\n/** Listener for the PersistentWriteStream */\nexport interface WriteStreamListener extends PersistentStreamListener {\n /**\n * Called by the PersistentWriteStream upon a successful handshake response\n * from the server, which is the receiver's cue to send any pending writes.\n */\n onHandshakeComplete: () => Promise;\n\n /**\n * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse\n * from the server that contains a mutation result.\n */\n onMutationResult: (\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ) => Promise;\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */\nexport class PersistentWriteStream extends PersistentStream<\n ProtoWriteRequest,\n ProtoWriteResponse,\n WriteStreamListener\n> {\n private handshakeComplete_ = false;\n\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n private serializer: JsonProtoSerializer,\n listener: WriteStreamListener\n ) {\n super(\n queue,\n TimerId.WriteStreamConnectionBackoff,\n TimerId.WriteStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n /**\n * The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n *\n * PersistentWriteStream manages propagating this value from responses to the\n * next request.\n */\n private lastStreamToken: string | Uint8Array | undefined;\n\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get handshakeComplete(): boolean {\n return this.handshakeComplete_;\n }\n\n // Override of PersistentStream.start\n start(): void {\n this.handshakeComplete_ = false;\n this.lastStreamToken = undefined;\n super.start();\n }\n\n protected tearDown(): void {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\n return this.connection.openStream(\n 'Write',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(responseProto: ProtoWriteResponse): Promise {\n // Always capture the last stream token.\n hardAssert(\n !!responseProto.streamToken,\n 'Got a write response without a stream token'\n );\n this.lastStreamToken = responseProto.streamToken;\n\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n hardAssert(\n !responseProto.writeResults || responseProto.writeResults.length === 0,\n 'Got mutation results for handshake'\n );\n this.handshakeComplete_ = true;\n return this.listener!.onHandshakeComplete();\n } else {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.backoff.reset();\n\n const results = fromWriteResults(\n responseProto.writeResults,\n responseProto.commitTime\n );\n const commitVersion = fromVersion(responseProto.commitTime!);\n return this.listener!.onMutationResult(commitVersion, results);\n }\n }\n\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */\n writeHandshake(): void {\n debugAssert(this.isOpen(), 'Writing handshake requires an opened stream');\n debugAssert(!this.handshakeComplete_, 'Handshake already completed');\n debugAssert(\n !this.lastStreamToken,\n 'Stream token should be empty during handshake'\n );\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const request: WriteRequest = {};\n request.database = getEncodedDatabaseId(this.serializer);\n this.sendRequest(request);\n }\n\n /** Sends a group of mutations to the Firestore backend to apply. */\n writeMutations(mutations: Mutation[]): void {\n debugAssert(this.isOpen(), 'Writing mutations requires an opened stream');\n debugAssert(\n this.handshakeComplete_,\n 'Handshake must be complete before writing mutations'\n );\n debugAssert(\n !!this.lastStreamToken,\n 'Trying to write mutation without a token'\n );\n\n const request: WriteRequest = {\n streamToken: this.lastStreamToken,\n writes: mutations.map(mutation => toMutation(this.serializer, mutation))\n };\n\n this.sendRequest(request);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider,\n readonly appCheckCredentials: CredentialsProvider,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnlineState } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\n\nconst LOG_TAG = 'OnlineStateTracker';\n\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\n// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394.\n// @jdimond thinks that bug is sufficiently fixed so that we can set this back\n// to 1. If that works okay, we could potentially remove this logic entirely.\nconst MAX_WATCH_STREAM_FAILURES = 1;\n\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nconst ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nexport class OnlineStateTracker {\n /** The current OnlineState. */\n private state = OnlineState.Unknown;\n\n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n private watchStreamFailures = 0;\n\n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n private onlineStateTimer: DelayedOperation | null = null;\n\n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n private shouldWarnClientIsOffline = true;\n\n constructor(\n private asyncQueue: AsyncQueue,\n private onlineStateHandler: (onlineState: OnlineState) => void\n ) {}\n\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */\n handleWatchStreamStart(): void {\n if (this.watchStreamFailures === 0) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n debugAssert(\n this.onlineStateTimer === null,\n `onlineStateTimer shouldn't be started yet`\n );\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(\n TimerId.OnlineStateTimeout,\n ONLINE_STATE_TIMEOUT_MS,\n () => {\n this.onlineStateTimer = null;\n debugAssert(\n this.state === OnlineState.Unknown,\n 'Timer should be canceled if we transitioned to a different state.'\n );\n this.logClientOfflineWarningIfNecessary(\n `Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` +\n `seconds.`\n );\n this.setAndBroadcast(OnlineState.Offline);\n\n // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n\n return Promise.resolve();\n }\n );\n }\n }\n\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */\n handleWatchStreamFailure(error: FirestoreError): void {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n // To get to OnlineState.Online, set() must have been called which would\n // have reset our heuristics.\n debugAssert(\n this.watchStreamFailures === 0,\n 'watchStreamFailures must be 0'\n );\n debugAssert(\n this.onlineStateTimer === null,\n 'onlineStateTimer must be null'\n );\n } else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n\n this.logClientOfflineWarningIfNecessary(\n `Connection failed ${MAX_WATCH_STREAM_FAILURES} ` +\n `times. Most recent error: ${error.toString()}`\n );\n\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\n }\n\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */\n set(newState: OnlineState): void {\n this.clearOnlineStateTimer();\n this.watchStreamFailures = 0;\n\n if (newState === OnlineState.Online) {\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.shouldWarnClientIsOffline = false;\n }\n\n this.setAndBroadcast(newState);\n }\n\n private setAndBroadcast(newState: OnlineState): void {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n }\n\n private logClientOfflineWarningIfNecessary(details: string): void {\n const message =\n `Could not reach Cloud Firestore backend. ${details}\\n` +\n `This typically indicates that your device does not have a healthy ` +\n `Internet connection at the moment. The client will operate in offline ` +\n `mode until it is able to successfully connect to the backend.`;\n if (this.shouldWarnClientIsOffline) {\n logError(message);\n this.shouldWarnClientIsOffline = false;\n } else {\n logDebug(LOG_TAG, message);\n }\n }\n\n private clearOnlineStateTimer(): void {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = 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 { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { OnlineState, TargetId } from '../core/types';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreGetLastRemoteSnapshotVersion,\n localStoreGetNextMutationBatch\n} from '../local/local_store_impl';\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { TargetData } from '../local/target_data';\nimport { MutationResult } from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { debugAssert, debugCast } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\nimport {\n Datastore,\n newPersistentWatchStream,\n newPersistentWriteStream\n} from './datastore';\nimport { OnlineStateTracker } from './online_state_tracker';\nimport {\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\nimport { RemoteSyncer } from './remote_syncer';\nimport { isPermanentWriteError } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchChangeAggregator,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst LOG_TAG = 'RemoteStore';\n\n// TODO(b/35853402): Negotiate this with the stream.\nconst MAX_PENDING_WRITES = 10;\n\n/** Reasons for why the RemoteStore may be offline. */\nconst enum OfflineCause {\n /** The user has explicitly disabled the network (via `disableNetwork()`). */\n UserDisabled,\n /** An IndexedDb failure occurred while persisting a stream update. */\n IndexedDbFailed,\n /** The tab is not the primary tab (only relevant with multi-tab). */\n IsSecondary,\n /** We are restarting the streams due to an Auth credential change. */\n CredentialChange,\n /** The connectivity state of the environment has changed. */\n ConnectivityChange,\n /** The RemoteStore has been shut down. */\n Shutdown\n}\n\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nexport interface RemoteStore {\n /**\n * SyncEngine to notify of watch and write events. This must be set\n * immediately after construction.\n */\n remoteSyncer: RemoteSyncer;\n}\n\nclass RemoteStoreImpl implements RemoteStore {\n remoteSyncer: RemoteSyncer = {};\n\n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n writePipeline: MutationBatch[] = [];\n\n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n listenTargets = new Map();\n\n connectivityMonitor: ConnectivityMonitor;\n watchStream?: PersistentListenStream;\n writeStream?: PersistentWriteStream;\n watchChangeAggregator?: WatchChangeAggregator;\n\n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n offlineCauses = new Set();\n\n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n onNetworkStatusChange: Array<(enabled: boolean) => Promise> = [];\n\n onlineStateTracker: OnlineStateTracker;\n\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n readonly localStore: LocalStore,\n /** The client-side proxy for interacting with the backend. */\n readonly datastore: Datastore,\n readonly asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n ) {\n this.connectivityMonitor = connectivityMonitor;\n this.connectivityMonitor.addCallback((_: NetworkStatus) => {\n asyncQueue.enqueueAndForget(async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n if (canUseNetwork(this)) {\n logDebug(\n LOG_TAG,\n 'Restarting streams for network reachability change.'\n );\n await restartNetwork(this);\n }\n });\n });\n\n this.onlineStateTracker = new OnlineStateTracker(\n asyncQueue,\n onlineStateHandler\n );\n }\n}\n\nexport function newRemoteStore(\n localStore: LocalStore,\n datastore: Datastore,\n asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n): RemoteStore {\n return new RemoteStoreImpl(\n localStore,\n datastore,\n asyncQueue,\n onlineStateHandler,\n connectivityMonitor\n );\n}\n\n/** Re-enables the network. Idempotent. */\nexport function remoteStoreEnableNetwork(\n remoteStore: RemoteStore\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.UserDisabled);\n return enableNetworkInternal(remoteStoreImpl);\n}\n\nasync function enableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n if (canUseNetwork(remoteStoreImpl)) {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ true);\n }\n }\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\nexport async function remoteStoreDisableNetwork(\n remoteStore: RemoteStore\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.UserDisabled);\n await disableNetworkInternal(remoteStoreImpl);\n\n // Set the OnlineState to Offline so get()s return from cache, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n}\n\nasync function disableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ false);\n }\n}\n\nexport async function remoteStoreShutdown(\n remoteStore: RemoteStore\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n logDebug(LOG_TAG, 'RemoteStore shutting down.');\n remoteStoreImpl.offlineCauses.add(OfflineCause.Shutdown);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.connectivityMonitor.shutdown();\n\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nexport function remoteStoreListen(\n remoteStore: RemoteStore,\n targetData: TargetData\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n\n if (remoteStoreImpl.listenTargets.has(targetData.targetId)) {\n return;\n }\n\n // Mark this as something the client is currently listening for.\n remoteStoreImpl.listenTargets.set(targetData.targetId, targetData);\n\n if (shouldStartWatchStream(remoteStoreImpl)) {\n // The listen will be sent in onWatchStreamOpen\n startWatchStream(remoteStoreImpl);\n } else if (ensureWatchStream(remoteStoreImpl).isOpen()) {\n sendWatchRequest(remoteStoreImpl, targetData);\n }\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */\nexport function remoteStoreUnlisten(\n remoteStore: RemoteStore,\n targetId: TargetId\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const watchStream = ensureWatchStream(remoteStoreImpl);\n\n debugAssert(\n remoteStoreImpl.listenTargets.has(targetId),\n `unlisten called on target no currently watched: ${targetId}`\n );\n\n remoteStoreImpl.listenTargets.delete(targetId);\n if (watchStream.isOpen()) {\n sendUnwatchRequest(remoteStoreImpl, targetId);\n }\n\n if (remoteStoreImpl.listenTargets.size === 0) {\n if (watchStream.isOpen()) {\n watchStream.markIdle();\n } else if (canUseNetwork(remoteStoreImpl)) {\n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */\nfunction sendWatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetData: TargetData\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(\n targetData.targetId\n );\n\n if (\n targetData.resumeToken.approximateByteSize() > 0 ||\n targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0\n ) {\n const expectedCount = remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(\n targetData.targetId\n ).size;\n targetData = targetData.withExpectedCount(expectedCount);\n }\n\n ensureWatchStream(remoteStoreImpl).watch(targetData);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */\nfunction sendUnwatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetId: TargetId\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(targetId);\n ensureWatchStream(remoteStoreImpl).unwatch(targetId);\n}\n\nfunction startWatchStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWatchStream(remoteStoreImpl),\n 'startWatchStream() called when shouldStartWatchStream() is false.'\n );\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget,\n 'getRemoteKeysForTarget() not set'\n );\n\n remoteStoreImpl.watchChangeAggregator = new WatchChangeAggregator({\n getRemoteKeysForTarget: targetId =>\n remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(targetId),\n getTargetDataForTarget: targetId =>\n remoteStoreImpl.listenTargets.get(targetId) || null,\n getDatabaseId: () => remoteStoreImpl.datastore.serializer.databaseId\n });\n ensureWatchStream(remoteStoreImpl).start();\n remoteStoreImpl.onlineStateTracker.handleWatchStreamStart();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */\nfunction shouldStartWatchStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWatchStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.listenTargets.size > 0\n );\n}\n\nexport function canUseNetwork(remoteStore: RemoteStore): boolean {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.offlineCauses.size === 0;\n}\n\nfunction cleanUpWatchStreamState(remoteStoreImpl: RemoteStoreImpl): void {\n remoteStoreImpl.watchChangeAggregator = undefined;\n}\n\nasync function onWatchStreamConnected(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n // Mark the client as online since we got a \"connected\" notification.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Online);\n}\n\nasync function onWatchStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n remoteStoreImpl.listenTargets.forEach((targetData, targetId) => {\n sendWatchRequest(remoteStoreImpl, targetData);\n });\n}\n\nasync function onWatchStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWatchStream(remoteStoreImpl),\n 'Watch stream was stopped gracefully while still needed.'\n );\n }\n\n cleanUpWatchStreamState(remoteStoreImpl);\n\n // If we still need the watch stream, retry the connection.\n if (shouldStartWatchStream(remoteStoreImpl)) {\n remoteStoreImpl.onlineStateTracker.handleWatchStreamFailure(error!);\n\n startWatchStream(remoteStoreImpl);\n } else {\n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\nasync function onWatchStreamChange(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchChange,\n snapshotVersion: SnapshotVersion\n): Promise {\n // Mark the client as online since we got a message from the server\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Online);\n\n if (\n watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause\n ) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await handleTargetError(remoteStoreImpl, watchChange);\n } catch (e) {\n logDebug(\n LOG_TAG,\n 'Failed to remove targets %s: %s ',\n watchChange.targetIds.join(','),\n e\n );\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n return;\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n remoteStoreImpl.watchChangeAggregator!.handleDocumentChange(watchChange);\n } else if (watchChange instanceof ExistenceFilterChange) {\n remoteStoreImpl.watchChangeAggregator!.handleExistenceFilter(watchChange);\n } else {\n debugAssert(\n watchChange instanceof WatchTargetChange,\n 'Expected watchChange to be an instance of WatchTargetChange'\n );\n remoteStoreImpl.watchChangeAggregator!.handleTargetChange(watchChange);\n }\n\n if (!snapshotVersion.isEqual(SnapshotVersion.min())) {\n try {\n const lastRemoteSnapshotVersion =\n await localStoreGetLastRemoteSnapshotVersion(\n remoteStoreImpl.localStore\n );\n if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0) {\n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await raiseWatchSnapshot(remoteStoreImpl, snapshotVersion);\n }\n } catch (e) {\n logDebug(LOG_TAG, 'Failed to raise snapshot:', e);\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */\nasync function disableNetworkUntilRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n e: FirestoreError,\n op?: () => Promise\n): Promise {\n if (isIndexedDbTransactionError(e)) {\n debugAssert(\n !remoteStoreImpl.offlineCauses.has(OfflineCause.IndexedDbFailed),\n 'Unexpected network event when IndexedDB was marked failed.'\n );\n remoteStoreImpl.offlineCauses.add(OfflineCause.IndexedDbFailed);\n\n // Disable network and raise offline snapshots\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n\n if (!op) {\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n op = () =>\n localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore);\n }\n\n // Probe IndexedDB periodically and re-enable network\n remoteStoreImpl.asyncQueue.enqueueRetryable(async () => {\n logDebug(LOG_TAG, 'Retrying IndexedDB access');\n await op!();\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IndexedDbFailed);\n await enableNetworkInternal(remoteStoreImpl);\n });\n } else {\n throw e;\n }\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */\nfunction executeWithRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n op: () => Promise\n): Promise {\n return op().catch(e => disableNetworkUntilRecovery(remoteStoreImpl, e, op));\n}\n\n/**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\nfunction raiseWatchSnapshot(\n remoteStoreImpl: RemoteStoreImpl,\n snapshotVersion: SnapshotVersion\n): Promise {\n debugAssert(\n !snapshotVersion.isEqual(SnapshotVersion.min()),\n \"Can't raise event for unknown SnapshotVersion\"\n );\n const remoteEvent =\n remoteStoreImpl.watchChangeAggregator!.createRemoteEvent(snapshotVersion);\n\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n remoteEvent.targetChanges.forEach((change, targetId) => {\n if (change.resumeToken.approximateByteSize() > 0) {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n // A watched target might have been removed already.\n if (targetData) {\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(change.resumeToken, snapshotVersion)\n );\n }\n }\n });\n\n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n remoteEvent.targetMismatches.forEach((targetId, targetPurpose) => {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n if (!targetData) {\n // A watched target might have been removed already.\n return;\n }\n\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n targetData.snapshotVersion\n )\n );\n\n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n sendUnwatchRequest(remoteStoreImpl, targetId);\n\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const requestTargetData = new TargetData(\n targetData.target,\n targetId,\n targetPurpose,\n targetData.sequenceNumber\n );\n sendWatchRequest(remoteStoreImpl, requestTargetData);\n });\n\n // Finally raise remote event\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applyRemoteEvent,\n 'applyRemoteEvent() not set'\n );\n return remoteStoreImpl.remoteSyncer.applyRemoteEvent(remoteEvent);\n}\n\n/** Handles an error on a target */\nasync function handleTargetError(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchTargetChange\n): Promise {\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectListen,\n 'rejectListen() not set'\n );\n debugAssert(!!watchChange.cause, 'Handling target error without a cause');\n const error = watchChange.cause!;\n for (const targetId of watchChange.targetIds) {\n // A watched target might have been removed already.\n if (remoteStoreImpl.listenTargets.has(targetId)) {\n await remoteStoreImpl.remoteSyncer.rejectListen(targetId, error);\n remoteStoreImpl.listenTargets.delete(targetId);\n remoteStoreImpl.watchChangeAggregator!.removeTarget(targetId);\n }\n }\n}\n\n/**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */\nexport async function fillWritePipeline(\n remoteStore: RemoteStore\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const writeStream = ensureWriteStream(remoteStoreImpl);\n\n let lastBatchIdRetrieved =\n remoteStoreImpl.writePipeline.length > 0\n ? remoteStoreImpl.writePipeline[remoteStoreImpl.writePipeline.length - 1]\n .batchId\n : BATCHID_UNKNOWN;\n\n while (canAddToWritePipeline(remoteStoreImpl)) {\n try {\n const batch = await localStoreGetNextMutationBatch(\n remoteStoreImpl.localStore,\n lastBatchIdRetrieved\n );\n\n if (batch === null) {\n if (remoteStoreImpl.writePipeline.length === 0) {\n writeStream.markIdle();\n }\n break;\n } else {\n lastBatchIdRetrieved = batch.batchId;\n addToWritePipeline(remoteStoreImpl, batch);\n }\n } catch (e) {\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */\nfunction canAddToWritePipeline(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n remoteStoreImpl.writePipeline.length < MAX_PENDING_WRITES\n );\n}\n\n// For testing\nexport function outstandingWrites(remoteStore: RemoteStore): number {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.writePipeline.length;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */\nfunction addToWritePipeline(\n remoteStoreImpl: RemoteStoreImpl,\n batch: MutationBatch\n): void {\n debugAssert(\n canAddToWritePipeline(remoteStoreImpl),\n 'addToWritePipeline called when pipeline is full'\n );\n remoteStoreImpl.writePipeline.push(batch);\n\n const writeStream = ensureWriteStream(remoteStoreImpl);\n if (writeStream.isOpen() && writeStream.handshakeComplete) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nfunction shouldStartWriteStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWriteStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.writePipeline.length > 0\n );\n}\n\nfunction startWriteStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWriteStream(remoteStoreImpl),\n 'startWriteStream() called when shouldStartWriteStream() is false.'\n );\n ensureWriteStream(remoteStoreImpl).start();\n}\n\nasync function onWriteStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n ensureWriteStream(remoteStoreImpl).writeHandshake();\n}\n\nasync function onWriteHandshakeComplete(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n const writeStream = ensureWriteStream(remoteStoreImpl);\n // Send the write pipeline now that the stream is established.\n for (const batch of remoteStoreImpl.writePipeline) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nasync function onMutationResult(\n remoteStoreImpl: RemoteStoreImpl,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n): Promise {\n // This is a response to a write containing mutations and should be\n // correlated to the first write in our write pipeline.\n debugAssert(\n remoteStoreImpl.writePipeline.length > 0,\n 'Got result for empty write pipeline'\n );\n const batch = remoteStoreImpl.writePipeline.shift()!;\n const success = MutationBatchResult.from(batch, commitVersion, results);\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applySuccessfulWrite,\n 'applySuccessfulWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.applySuccessfulWrite!(success)\n );\n\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n}\n\nasync function onWriteStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWriteStream(remoteStoreImpl),\n 'Write stream was stopped gracefully while still needed.'\n );\n }\n\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n if (error && ensureWriteStream(remoteStoreImpl).handshakeComplete) {\n // This error affects the actual write.\n await handleWriteError(remoteStoreImpl, error!);\n }\n\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\nasync function handleWriteError(\n remoteStoreImpl: RemoteStoreImpl,\n error: FirestoreError\n): Promise {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (isPermanentWriteError(error.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const batch = remoteStoreImpl.writePipeline.shift()!;\n\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n ensureWriteStream(remoteStoreImpl).inhibitBackoff();\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectFailedWrite,\n 'rejectFailedWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.rejectFailedWrite!(batch.batchId, error)\n );\n\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n // Transient error, just let the retry logic kick in.\n }\n}\n\nasync function restartNetwork(remoteStore: RemoteStore): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.ConnectivityChange);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.ConnectivityChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\nexport async function remoteStoreHandleCredentialChange(\n remoteStore: RemoteStore,\n user: User\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.asyncQueue.verifyOperationInProgress();\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.handleCredentialChange,\n 'handleCredentialChange() not set'\n );\n\n logDebug(LOG_TAG, 'RemoteStore received new credentials');\n const usesNetwork = canUseNetwork(remoteStoreImpl);\n\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n remoteStoreImpl.offlineCauses.add(OfflineCause.CredentialChange);\n await disableNetworkInternal(remoteStoreImpl);\n if (usesNetwork) {\n // Don't set the network status to Unknown if we are offline.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n await remoteStoreImpl.remoteSyncer.handleCredentialChange(user);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.CredentialChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */\nexport async function remoteStoreApplyPrimaryState(\n remoteStore: RemoteStore,\n isPrimary: boolean\n): Promise {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n if (isPrimary) {\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IsSecondary);\n await enableNetworkInternal(remoteStoreImpl);\n } else if (!isPrimary) {\n remoteStoreImpl.offlineCauses.add(OfflineCause.IsSecondary);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWatchStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentListenStream {\n if (!remoteStoreImpl.watchStream) {\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.watchStream = newPersistentWatchStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onConnected: onWatchStreamConnected.bind(null, remoteStoreImpl),\n onOpen: onWatchStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWatchStreamClose.bind(null, remoteStoreImpl),\n onWatchChange: onWatchStreamChange.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.watchStream!.inhibitBackoff();\n if (shouldStartWatchStream(remoteStoreImpl)) {\n startWatchStream(remoteStoreImpl);\n } else {\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n } else {\n await remoteStoreImpl.watchStream!.stop();\n cleanUpWatchStreamState(remoteStoreImpl);\n }\n });\n }\n\n return remoteStoreImpl.watchStream;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWriteStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentWriteStream {\n if (!remoteStoreImpl.writeStream) {\n debugAssert(\n remoteStoreImpl.writePipeline.length === 0,\n 'Should not issue writes before WriteStream is enabled'\n );\n\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.writeStream = newPersistentWriteStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onConnected: () => Promise.resolve(),\n onOpen: onWriteStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWriteStreamClose.bind(null, remoteStoreImpl),\n onHandshakeComplete: onWriteHandshakeComplete.bind(\n null,\n remoteStoreImpl\n ),\n onMutationResult: onMutationResult.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.writeStream!.inhibitBackoff();\n\n // This will start the write stream if necessary.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n await remoteStoreImpl.writeStream!.stop();\n\n if (remoteStoreImpl.writePipeline.length > 0) {\n logDebug(\n LOG_TAG,\n `Stopping write stream with ${remoteStoreImpl.writePipeline.length} pending writes`\n );\n remoteStoreImpl.writePipeline = [];\n }\n }\n });\n }\n\n return remoteStoreImpl.writeStream;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation implements PromiseLike {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue(op: () => Promise): Promise;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap } from '../util/sorted_map';\n\nimport { documentMap } from './collections';\nimport { Document } from './document';\nimport { DocumentComparator } from './document_comparator';\nimport { DocumentKey } from './document_key';\n\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */\n\nexport class DocumentSet {\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n static emptySet(oldSet: DocumentSet): DocumentSet {\n return new DocumentSet(oldSet.comparator);\n }\n\n private comparator: DocumentComparator;\n private keyedMap: SortedMap;\n private sortedSet: SortedMap;\n\n /** The default ordering is by key if the comparator is omitted */\n constructor(comp?: DocumentComparator) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = (d1: Document, d2: Document) =>\n comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n } else {\n this.comparator = (d1: Document, d2: Document) =>\n DocumentKey.comparator(d1.key, d2.key);\n }\n\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap(this.comparator);\n }\n\n has(key: DocumentKey): boolean {\n return this.keyedMap.get(key) != null;\n }\n\n get(key: DocumentKey): Document | null {\n return this.keyedMap.get(key);\n }\n\n first(): Document | null {\n return this.sortedSet.minKey();\n }\n\n last(): Document | null {\n return this.sortedSet.maxKey();\n }\n\n isEmpty(): boolean {\n return this.sortedSet.isEmpty();\n }\n\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */\n indexOf(key: DocumentKey): number {\n const doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n }\n\n get size(): number {\n return this.sortedSet.size;\n }\n\n /** Iterates documents in order defined by \"comparator\" */\n forEach(cb: (doc: Document) => void): void {\n this.sortedSet.inorderTraversal((k, v) => {\n cb(k);\n return false;\n });\n }\n\n /** Inserts or updates a document with the same key */\n add(doc: Document): DocumentSet {\n // First remove the element if we have it.\n const set = this.delete(doc.key);\n return set.copy(\n set.keyedMap.insert(doc.key, doc),\n set.sortedSet.insert(doc, null)\n );\n }\n\n /** Deletes a document with a given key */\n delete(key: DocumentKey): DocumentSet {\n const doc = this.get(key);\n if (!doc) {\n return this;\n }\n\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n }\n\n isEqual(other: DocumentSet | null | undefined): boolean {\n if (!(other instanceof DocumentSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.sortedSet.getIterator();\n const otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n const thisDoc = thisIt.getNext().key;\n const otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc)) {\n return false;\n }\n }\n return true;\n }\n\n toString(): string {\n const docStrings: string[] = [];\n this.forEach(doc => {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n } else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n }\n\n private copy(\n keyedMap: SortedMap,\n sortedSet: SortedMap\n ): DocumentSet {\n const newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { Query, queryEquals } from './query';\n\nexport const enum ChangeType {\n Added,\n Removed,\n Modified,\n Metadata\n}\n\nexport interface DocumentViewChange {\n type: ChangeType;\n doc: Document;\n}\n\nexport const enum SyncState {\n Local,\n Synced\n}\n\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nexport class DocumentChangeSet {\n private changeMap = new SortedMap(\n DocumentKey.comparator\n );\n\n track(change: DocumentViewChange): void {\n const key = change.doc.key;\n const oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n\n // Merge the new change with the existing change.\n if (\n change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata\n ) {\n this.changeMap = this.changeMap.insert(key, change);\n } else if (\n change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.remove(key);\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n } else if (\n change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else {\n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail(\n 'unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange)\n );\n }\n }\n\n getChanges(): DocumentViewChange[] {\n const changes: DocumentViewChange[] = [];\n this.changeMap.inorderTraversal(\n (key: DocumentKey, change: DocumentViewChange) => {\n changes.push(change);\n }\n );\n return changes;\n }\n}\n\nexport class ViewSnapshot {\n constructor(\n readonly query: Query,\n readonly docs: DocumentSet,\n readonly oldDocs: DocumentSet,\n readonly docChanges: DocumentViewChange[],\n readonly mutatedKeys: DocumentKeySet,\n readonly fromCache: boolean,\n readonly syncStateChanged: boolean,\n readonly excludesMetadataChanges: boolean,\n readonly hasCachedResults: boolean\n ) {}\n\n /** Returns a view snapshot as if all documents in the snapshot were added. */\n static fromInitialDocuments(\n query: Query,\n documents: DocumentSet,\n mutatedKeys: DocumentKeySet,\n fromCache: boolean,\n hasCachedResults: boolean\n ): ViewSnapshot {\n const changes: DocumentViewChange[] = [];\n documents.forEach(doc => {\n changes.push({ type: ChangeType.Added, doc });\n });\n\n return new ViewSnapshot(\n query,\n documents,\n DocumentSet.emptySet(documents),\n changes,\n mutatedKeys,\n fromCache,\n /* syncStateChanged= */ true,\n /* excludesMetadataChanges= */ false,\n hasCachedResults\n );\n }\n\n get hasPendingWrites(): boolean {\n return !this.mutatedKeys.isEmpty();\n }\n\n isEqual(other: ViewSnapshot): boolean {\n if (\n this.fromCache !== other.fromCache ||\n this.hasCachedResults !== other.hasCachedResults ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.mutatedKeys.isEqual(other.mutatedKeys) ||\n !queryEquals(this.query, other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)\n ) {\n return false;\n }\n const changes: DocumentViewChange[] = this.docChanges;\n const otherChanges: DocumentViewChange[] = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (let i = 0; i < changes.length; i++) {\n if (\n changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)\n ) {\n return false;\n }\n }\n return 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 { debugAssert, debugCast } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { EventHandler } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { canonifyQuery, Query, queryEquals, stringifyQuery } from './query';\nimport { OnlineState } from './types';\nimport { ChangeType, DocumentViewChange, ViewSnapshot } from './view_snapshot';\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nclass QueryListenersInfo {\n viewSnap: ViewSnapshot | undefined = undefined;\n listeners: QueryListener[] = [];\n\n // Helper methods that checks if the query has listeners that listening to remote store\n hasRemoteListeners(): boolean {\n return this.listeners.some(listener => listener.listensToRemoteStore());\n }\n}\n\n/**\n * Interface for handling events from the EventManager.\n */\nexport interface Observer {\n next: EventHandler;\n error: EventHandler;\n}\n\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n *\n * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be\n * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This\n * allows users to tree-shake the Watch logic.\n */\nexport interface EventManager {\n onListen?: (\n query: Query,\n enableRemoteListen: boolean\n ) => Promise;\n onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise;\n onFirstRemoteStoreListen?: (query: Query) => Promise;\n onLastRemoteStoreUnlisten?: (query: Query) => Promise;\n}\n\nexport function newEventManager(): EventManager {\n return new EventManagerImpl();\n}\n\nexport class EventManagerImpl implements EventManager {\n queries = new ObjectMap(\n q => canonifyQuery(q),\n queryEquals\n );\n\n onlineState = OnlineState.Unknown;\n\n snapshotsInSyncListeners: Set> = new Set();\n\n /** Callback invoked when a Query is first listen to. */\n onListen?: (\n query: Query,\n enableRemoteListen: boolean\n ) => Promise;\n /** Callback invoked once all listeners to a Query are removed. */\n onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise;\n\n /**\n * Callback invoked when a Query starts listening to the remote store, while\n * already listening to the cache.\n */\n onFirstRemoteStoreListen?: (query: Query) => Promise;\n /**\n * Callback invoked when a Query stops listening to the remote store, while\n * still listening to the cache.\n */\n onLastRemoteStoreUnlisten?: (query: Query) => Promise;\n}\n\nfunction validateEventManager(eventManagerImpl: EventManagerImpl): void {\n debugAssert(!!eventManagerImpl.onListen, 'onListen not set');\n debugAssert(\n !!eventManagerImpl.onFirstRemoteStoreListen,\n 'onFirstRemoteStoreListen not set'\n );\n debugAssert(!!eventManagerImpl.onUnlisten, 'onUnlisten not set');\n debugAssert(\n !!eventManagerImpl.onLastRemoteStoreUnlisten,\n 'onLastRemoteStoreUnlisten not set'\n );\n}\n\nconst enum ListenerSetupAction {\n InitializeLocalListenAndRequireWatchConnection,\n InitializeLocalListenOnly,\n RequireWatchConnectionOnly,\n NoActionRequired\n}\n\nconst enum ListenerRemovalAction {\n TerminateLocalListenAndRequireWatchDisconnection,\n TerminateLocalListenOnly,\n RequireWatchDisconnectionOnly,\n NoActionRequired\n}\n\nexport async function eventManagerListen(\n eventManager: EventManager,\n listener: QueryListener\n): Promise {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n validateEventManager(eventManagerImpl);\n\n let listenerAction = ListenerSetupAction.NoActionRequired;\n\n const query = listener.query;\n\n let queryInfo = eventManagerImpl.queries.get(query);\n if (!queryInfo) {\n queryInfo = new QueryListenersInfo();\n listenerAction = listener.listensToRemoteStore()\n ? ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection\n : ListenerSetupAction.InitializeLocalListenOnly;\n } else if (\n !queryInfo.hasRemoteListeners() &&\n listener.listensToRemoteStore()\n ) {\n // Query has been listening to local cache, and tries to add a new listener sourced from watch.\n listenerAction = ListenerSetupAction.RequireWatchConnectionOnly;\n }\n\n try {\n switch (listenerAction) {\n case ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection:\n queryInfo.viewSnap = await eventManagerImpl.onListen!(\n query,\n /** enableRemoteListen= */ true\n );\n break;\n case ListenerSetupAction.InitializeLocalListenOnly:\n queryInfo.viewSnap = await eventManagerImpl.onListen!(\n query,\n /** enableRemoteListen= */ false\n );\n break;\n case ListenerSetupAction.RequireWatchConnectionOnly:\n await eventManagerImpl.onFirstRemoteStoreListen!(query);\n break;\n default:\n break;\n }\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Initialization of query '${stringifyQuery(listener.query)}' failed`\n );\n listener.onError(firestoreError);\n return;\n }\n\n eventManagerImpl.queries.set(query, queryInfo);\n queryInfo.listeners.push(listener);\n\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n const raisedEvent = listener.applyOnlineStateChange(\n eventManagerImpl.onlineState\n );\n debugAssert(\n !raisedEvent,\n \"applyOnlineStateChange() shouldn't raise an event for brand-new listeners.\"\n );\n\n if (queryInfo.viewSnap) {\n const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap);\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n }\n}\n\nexport async function eventManagerUnlisten(\n eventManager: EventManager,\n listener: QueryListener\n): Promise {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n validateEventManager(eventManagerImpl);\n\n const query = listener.query;\n let listenerAction = ListenerRemovalAction.NoActionRequired;\n\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n const i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n\n if (queryInfo.listeners.length === 0) {\n listenerAction = listener.listensToRemoteStore()\n ? ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection\n : ListenerRemovalAction.TerminateLocalListenOnly;\n } else if (\n !queryInfo.hasRemoteListeners() &&\n listener.listensToRemoteStore()\n ) {\n // The removed listener is the last one that sourced from watch.\n listenerAction = ListenerRemovalAction.RequireWatchDisconnectionOnly;\n }\n }\n }\n switch (listenerAction) {\n case ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection:\n eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten!(\n query,\n /** disableRemoteListen= */ true\n );\n case ListenerRemovalAction.TerminateLocalListenOnly:\n eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten!(\n query,\n /** disableRemoteListen= */ false\n );\n case ListenerRemovalAction.RequireWatchDisconnectionOnly:\n return eventManagerImpl.onLastRemoteStoreUnlisten!(query);\n default:\n return;\n }\n}\n\nexport function eventManagerOnWatchChange(\n eventManager: EventManager,\n viewSnaps: ViewSnapshot[]\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n let raisedEvent = false;\n for (const viewSnap of viewSnaps) {\n const query = viewSnap.query;\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n if (listener.onViewSnapshot(viewSnap)) {\n raisedEvent = true;\n }\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function eventManagerOnWatchError(\n eventManager: EventManager,\n query: Query,\n error: FirestoreError\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n const queryInfo = eventManagerImpl.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n listener.onError(error);\n }\n }\n\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n eventManagerImpl.queries.delete(query);\n}\n\nexport function eventManagerOnOnlineStateChange(\n eventManager: EventManager,\n onlineState: OnlineState\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.onlineState = onlineState;\n let raisedEvent = false;\n eventManagerImpl.queries.forEach((_, queryInfo) => {\n for (const listener of queryInfo.listeners) {\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n if (listener.applyOnlineStateChange(onlineState)) {\n raisedEvent = true;\n }\n }\n });\n if (raisedEvent) {\n raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function addSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.snapshotsInSyncListeners.add(observer);\n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n observer.next();\n}\n\nexport function removeSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n eventManagerImpl.snapshotsInSyncListeners.delete(observer);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction raiseSnapshotsInSyncEvent(eventManagerImpl: EventManagerImpl): void {\n eventManagerImpl.snapshotsInSyncListeners.forEach(observer => {\n observer.next();\n });\n}\n\nexport enum ListenerDataSource {\n /** Listen to both cache and server changes */\n Default = 'default',\n\n /** Listen to changes in cache only */\n Cache = 'cache'\n}\n\nexport interface ListenOptions {\n /** Raise events even when only the metadata changes */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Wait for a sync with the server when online, but still raise events while\n * offline.\n */\n readonly waitForSyncWhenOnline?: boolean;\n\n /** Set the source events raised from. */\n readonly source?: ListenerDataSource;\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nexport class QueryListener {\n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n private raisedInitialEvent = false;\n\n private options: ListenOptions;\n\n private snap: ViewSnapshot | null = null;\n\n private onlineState = OnlineState.Unknown;\n\n constructor(\n readonly query: Query,\n private queryObserver: Observer,\n options?: ListenOptions\n ) {\n this.options = options || {};\n }\n\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */\n onViewSnapshot(snap: ViewSnapshot): boolean {\n debugAssert(\n snap.docChanges.length > 0 || snap.syncStateChanged,\n 'We got a new snapshot with no changes?'\n );\n\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const docChanges: DocumentViewChange[] = [];\n for (const docChange of snap.docChanges) {\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(\n snap.query,\n snap.docs,\n snap.oldDocs,\n docChanges,\n snap.mutatedKeys,\n snap.fromCache,\n snap.syncStateChanged,\n /* excludesMetadataChanges= */ true,\n snap.hasCachedResults\n );\n }\n let raisedEvent = false;\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n raisedEvent = true;\n }\n } else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n raisedEvent = true;\n }\n\n this.snap = snap;\n return raisedEvent;\n }\n\n onError(error: FirestoreError): void {\n this.queryObserver.error(error);\n }\n\n /** Returns whether a snapshot was raised. */\n applyOnlineStateChange(onlineState: OnlineState): boolean {\n this.onlineState = onlineState;\n let raisedEvent = false;\n if (\n this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)\n ) {\n this.raiseInitialEvent(this.snap);\n raisedEvent = true;\n }\n return raisedEvent;\n }\n\n private shouldRaiseInitialEvent(\n snap: ViewSnapshot,\n onlineState: OnlineState\n ): boolean {\n debugAssert(\n !this.raisedInitialEvent,\n 'Determining whether to raise first event but already had first event'\n );\n\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n\n // Always raise event if listening to cache\n if (!this.listensToRemoteStore()) {\n return true;\n }\n\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const maybeOnline = onlineState !== OnlineState.Offline;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n debugAssert(\n snap.fromCache,\n 'Waiting for sync, but snapshot is not from cache'\n );\n return false;\n }\n\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n return (\n !snap.docs.isEmpty() ||\n snap.hasCachedResults ||\n onlineState === OnlineState.Offline\n );\n }\n\n private shouldRaiseEvent(snap: ViewSnapshot): boolean {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (snap.docChanges.length > 0) {\n return true;\n }\n\n const hasPendingWritesChanged =\n this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeMetadataChanges === true;\n }\n\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n return false;\n }\n\n private raiseInitialEvent(snap: ViewSnapshot): void {\n debugAssert(\n !this.raisedInitialEvent,\n 'Trying to raise initial events for second time'\n );\n snap = ViewSnapshot.fromInitialDocuments(\n snap.query,\n snap.docs,\n snap.mutatedKeys,\n snap.fromCache,\n snap.hasCachedResults\n );\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n }\n\n listensToRemoteStore(): boolean {\n return this.options.source !== ListenerDataSource.Cache;\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 {\n BundleElement,\n BundleMetadata\n} from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */\nexport class SizedBundleElement {\n constructor(\n public readonly payload: BundleElement,\n // How many bytes this element takes to store in the bundle.\n public readonly byteLength: number\n ) {}\n\n isBundleMetadata(): boolean {\n return 'metadata' in this.payload;\n }\n}\n\nexport type BundleSource =\n | ReadableStream\n | ArrayBuffer\n | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n serializer: JsonProtoSerializer;\n\n close(): Promise;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): Promise;\n\n /**\n * Returns the next BundleElement (together with its byte size in the bundle)\n * that has not been read from underlying ReadableStream. Returns null if we\n * have reached the end of the stream.\n */\n nextElement(): Promise;\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 { LoadBundleTaskProgress } from '@firebase/firestore-types';\n\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreApplyBundledDocuments,\n localStoreSaveNamedQuery\n} from '../local/local_store_impl';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api';\nimport {\n fromDocument,\n fromName,\n fromVersion,\n JsonProtoSerializer\n} from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { SizedBundleElement } from '../util/bundle_reader';\n\nimport {\n BundleConverter,\n BundledDocument,\n BundledDocuments,\n BundleLoadResult\n} from './bundle';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */\nexport class BundleConverterImpl implements BundleConverter {\n constructor(private readonly serializer: JsonProtoSerializer) {}\n\n toDocumentKey(name: string): DocumentKey {\n return fromName(this.serializer, name);\n }\n\n /**\n * Converts a BundleDocument to a MutableDocument.\n */\n toMutableDocument(bundledDoc: BundledDocument): MutableDocument {\n if (bundledDoc.metadata.exists) {\n debugAssert(\n !!bundledDoc.document,\n 'Document is undefined when metadata.exist is true.'\n );\n return fromDocument(this.serializer, bundledDoc.document!, false);\n } else {\n return MutableDocument.newNoDocument(\n this.toDocumentKey(bundledDoc.metadata.name!),\n this.toSnapshotVersion(bundledDoc.metadata.readTime!)\n );\n }\n }\n\n toSnapshotVersion(time: ApiTimestamp): SnapshotVersion {\n return fromVersion(time);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */\nexport class BundleLoader {\n /** The current progress of loading */\n private progress: LoadBundleTaskProgress;\n /** Batched queries to be saved into storage */\n private queries: ProtoNamedQuery[] = [];\n /** Batched documents to be saved into storage */\n private documents: BundledDocuments = [];\n /** The collection groups affected by this bundle. */\n private collectionGroups = new Set();\n\n constructor(\n private bundleMetadata: ProtoBundleMetadata,\n private localStore: LocalStore,\n private serializer: JsonProtoSerializer\n ) {\n this.progress = bundleInitialProgress(bundleMetadata);\n }\n\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */\n addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null {\n debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');\n\n this.progress.bytesLoaded += element.byteLength;\n\n let documentsLoaded = this.progress.documentsLoaded;\n\n if (element.payload.namedQuery) {\n this.queries.push(element.payload.namedQuery);\n } else if (element.payload.documentMetadata) {\n this.documents.push({ metadata: element.payload.documentMetadata });\n if (!element.payload.documentMetadata.exists) {\n ++documentsLoaded;\n }\n const path = ResourcePath.fromString(\n element.payload.documentMetadata.name!\n );\n debugAssert(\n path.length >= 2,\n 'The document name does not point to a document.'\n );\n this.collectionGroups.add(path.get(path.length - 2));\n } else if (element.payload.document) {\n debugAssert(\n this.documents.length > 0 &&\n this.documents[this.documents.length - 1].metadata.name ===\n element.payload.document.name,\n 'The document being added does not match the stored metadata.'\n );\n this.documents[this.documents.length - 1].document =\n element.payload.document;\n ++documentsLoaded;\n }\n\n if (documentsLoaded !== this.progress.documentsLoaded) {\n this.progress.documentsLoaded = documentsLoaded;\n return { ...this.progress };\n }\n\n return null;\n }\n\n private getQueryDocumentMapping(\n documents: BundledDocuments\n ): Map {\n const queryDocumentMap = new Map();\n const bundleConverter = new BundleConverterImpl(this.serializer);\n for (const bundleDoc of documents) {\n if (bundleDoc.metadata.queries) {\n const documentKey = bundleConverter.toDocumentKey(\n bundleDoc.metadata.name!\n );\n for (const queryName of bundleDoc.metadata.queries) {\n const documentKeys = (\n queryDocumentMap.get(queryName) || documentKeySet()\n ).add(documentKey);\n queryDocumentMap.set(queryName, documentKeys);\n }\n }\n }\n\n return queryDocumentMap;\n }\n\n /**\n * Update the progress to 'Success' and return the updated progress.\n */\n async complete(): Promise {\n debugAssert(\n this.documents[this.documents.length - 1]?.metadata.exists !== true ||\n !!this.documents[this.documents.length - 1].document,\n 'Bundled documents end with a document metadata element instead of a document.'\n );\n debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n const changedDocs = await localStoreApplyBundledDocuments(\n this.localStore,\n new BundleConverterImpl(this.serializer),\n this.documents,\n this.bundleMetadata.id!\n );\n\n const queryDocumentMap = this.getQueryDocumentMapping(this.documents);\n\n for (const q of this.queries) {\n await localStoreSaveNamedQuery(\n this.localStore,\n q,\n queryDocumentMap.get(q.name!)\n );\n }\n\n this.progress.taskState = 'Success';\n return {\n progress: this.progress,\n changedCollectionGroups: this.collectionGroups,\n changedDocs\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */\nexport function bundleInitialProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Running',\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\nexport function bundleSuccessProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Success',\n documentsLoaded: metadata.totalDocuments!,\n bytesLoaded: metadata.totalBytes!,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n limboResolutionEnabled: boolean,\n targetChange?: TargetChange,\n targetIsPendingReset?: boolean\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n\n targetIsPendingReset = targetIsPendingReset ?? false;\n const limboChanges =\n limboResolutionEnabled && !targetIsPendingReset\n ? this.updateLimboDocuments()\n : [];\n\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n const synced =\n this.limboDocuments.size === 0 && this.current && !targetIsPendingReset;\n\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* limboResolutionEnabled= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n\n return order(c1) - order(c2);\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 { LoadBundleTask } from '../api/bundle';\nimport { User } from '../auth/user';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport {\n localStoreAcknowledgeBatch,\n localStoreAllocateTarget,\n localStoreApplyRemoteEventToLocalCache,\n localStoreExecuteQuery,\n localStoreGetActiveClients,\n localStoreGetCachedTarget,\n localStoreGetHighestUnacknowledgedBatchId,\n localStoreGetNewDocumentChanges,\n localStoreHandleUserChange,\n localStoreHasNewerBundle,\n localStoreLookupMutationDocuments,\n localStoreNotifyLocalViewChanges,\n localStoreRejectBatch,\n localStoreReleaseTarget,\n localStoreRemoveCachedMutationBatchMetadata,\n localStoreSaveBundle,\n localStoreWriteLocally\n} from '../local/local_store_impl';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { ReferenceSet } from '../local/reference_set';\nimport { ClientId, SharedClientState } from '../local/shared_client_state';\nimport { QueryTargetState } from '../local/shared_client_state_syncer';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatchResult } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport {\n canUseNetwork,\n fillWritePipeline,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreListen,\n remoteStoreUnlisten\n} from '../remote/remote_store';\nimport { debugAssert, debugCast, fail, hardAssert } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { Deferred } from '../util/promise';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n bundleInitialProgress,\n BundleLoader,\n bundleSuccessProgress\n} from './bundle_impl';\nimport {\n EventManager,\n eventManagerOnOnlineStateChange,\n eventManagerOnWatchChange,\n eventManagerOnWatchError\n} from './event_manager';\nimport { ListenSequence } from './listen_sequence';\nimport {\n canonifyQuery,\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryEquals,\n queryCollectionGroup,\n queryToTarget,\n stringifyQuery\n} from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { SyncEngine } from './sync_engine';\nimport { Target } from './target';\nimport { TargetIdGenerator } from './target_id_generator';\nimport {\n BatchId,\n MutationBatchState,\n OnlineState,\n OnlineStateSource,\n TargetId\n} from './types';\nimport {\n AddedLimboDocument,\n LimboDocumentChange,\n RemovedLimboDocument,\n View,\n ViewChange\n} from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'SyncEngine';\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass QueryView {\n constructor(\n /**\n * The query itself.\n */\n public query: Query,\n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n public targetId: TargetId,\n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n public view: View\n ) {}\n}\n\n/** Tracks a limbo resolution. */\nclass LimboResolution {\n constructor(public key: DocumentKey) {}\n\n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n receivedDocument: boolean = false;\n}\n\n/**\n * A function that updates a QueryView with a set of document changes (and a\n * remote event if applicable).\n */\ntype ApplyDocChangesHandler = (\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n) => Promise;\n\n/**\n * Callbacks implemented by EventManager to handle notifications from\n * SyncEngine.\n */\ninterface SyncEngineListener {\n /** Handles new view snapshots. */\n onWatchChange?(snapshots: ViewSnapshot[]): void;\n\n /** Handles the failure of a query. */\n onWatchError?(query: Query, error: FirestoreError): void;\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass SyncEngineImpl implements SyncEngine {\n syncEngineListener: SyncEngineListener = {};\n\n /**\n * A callback that updates the QueryView based on the provided change.\n *\n * PORTING NOTE: On other platforms, this logic lives in\n * `emitNewSnapshotsAndNotifyLocalStore()`, but on Web it is extracted to\n * ensure that all view logic only exists in bundles that include views.\n */\n applyDocChanges?: ApplyDocChangesHandler;\n\n queryViewsByQuery = new ObjectMap(\n q => canonifyQuery(q),\n queryEquals\n );\n queriesByTarget = new Map();\n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n enqueuedLimboResolutions = new Set();\n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n activeLimboTargetsByKey = new SortedMap(\n DocumentKey.comparator\n );\n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n activeLimboResolutionsByTarget = new Map();\n limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n mutationUserCallbacks = {} as {\n [uidKey: string]: SortedMap>;\n };\n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n pendingWritesCallbacks = new Map>>();\n limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\n\n onlineState = OnlineState.Unknown;\n\n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n _isPrimaryClient: undefined | boolean = undefined;\n\n constructor(\n readonly localStore: LocalStore,\n readonly remoteStore: RemoteStore,\n readonly eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n readonly sharedClientState: SharedClientState,\n public currentUser: User,\n readonly maxConcurrentLimboResolutions: number\n ) {}\n\n get isPrimaryClient(): boolean {\n return this._isPrimaryClient === true;\n }\n}\n\nexport function newSyncEngine(\n localStore: LocalStore,\n remoteStore: RemoteStore,\n eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n sharedClientState: SharedClientState,\n currentUser: User,\n maxConcurrentLimboResolutions: number,\n isPrimary: boolean\n): SyncEngine {\n const syncEngine = new SyncEngineImpl(\n localStore,\n remoteStore,\n eventManager,\n sharedClientState,\n currentUser,\n maxConcurrentLimboResolutions\n );\n if (isPrimary) {\n syncEngine._isPrimaryClient = true;\n }\n return syncEngine;\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nexport async function syncEngineListen(\n syncEngine: SyncEngine,\n query: Query,\n shouldListenToRemote: boolean = true\n): Promise {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n\n let viewSnapshot;\n\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n if (queryView) {\n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n syncEngineImpl.sharedClientState.addLocalQueryTarget(queryView.targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n } else {\n viewSnapshot = await allocateTargetAndMaybeListen(\n syncEngineImpl,\n query,\n shouldListenToRemote,\n /** shouldInitializeView= */ true\n );\n debugAssert(!!viewSnapshot, 'viewSnapshot is not initialized');\n }\n\n return viewSnapshot;\n}\n\n/** Query has been listening to the cache, and tries to initiate the remote store listen */\nexport async function triggerRemoteStoreListen(\n syncEngine: SyncEngine,\n query: Query\n): Promise {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n await allocateTargetAndMaybeListen(\n syncEngineImpl,\n query,\n /** shouldListenToRemote= */ true,\n /** shouldInitializeView= */ false\n );\n}\n\nasync function allocateTargetAndMaybeListen(\n syncEngineImpl: SyncEngineImpl,\n query: Query,\n shouldListenToRemote: boolean,\n shouldInitializeView: boolean\n): Promise {\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(query)\n );\n\n const targetId = targetData.targetId;\n\n // PORTING NOTE: When the query is listening to cache only, we skip sending it over to Watch by\n // not registering it in shared client state, and directly calculate initial snapshots and\n // subsequent updates from cache. Otherwise, register the target ID with local Firestore client\n // as active watch target.\n const status: QueryTargetState = shouldListenToRemote\n ? syncEngineImpl.sharedClientState.addLocalQueryTarget(targetId)\n : 'not-current';\n\n let viewSnapshot;\n if (shouldInitializeView) {\n viewSnapshot = await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n query,\n targetId,\n status === 'current',\n targetData.resumeToken\n );\n }\n\n if (syncEngineImpl.isPrimaryClient && shouldListenToRemote) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n\n return viewSnapshot;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */\nasync function initializeViewAndComputeSnapshot(\n syncEngineImpl: SyncEngineImpl,\n query: Query,\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n): Promise {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n syncEngineImpl.applyDocChanges = (queryView, changes, remoteEvent) =>\n applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent);\n\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const synthesizedTargetChange =\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current && syncEngineImpl.onlineState !== OnlineState.Offline,\n resumeToken\n );\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient,\n synthesizedTargetChange\n );\n updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges);\n\n debugAssert(\n !!viewChange.snapshot,\n 'applyChanges for new view should always return a snapshot'\n );\n\n const data = new QueryView(query, targetId, view);\n\n syncEngineImpl.queryViewsByQuery.set(query, data);\n if (syncEngineImpl.queriesByTarget.has(targetId)) {\n syncEngineImpl.queriesByTarget.get(targetId)!.push(query);\n } else {\n syncEngineImpl.queriesByTarget.set(targetId, [query]);\n }\n\n return viewChange.snapshot;\n}\n\n/** Stops listening to the query. */\nexport async function syncEngineUnlisten(\n syncEngine: SyncEngine,\n query: Query,\n shouldUnlistenToRemote: boolean\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n debugAssert(\n !!queryView,\n 'Trying to unlisten on query not found:' + stringifyQuery(query)\n );\n\n // Only clean up the query view and target if this is the only query mapped\n // to the target.\n const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId)!;\n if (queries.length > 1) {\n syncEngineImpl.queriesByTarget.set(\n queryView.targetId,\n queries.filter(q => !queryEquals(q, query))\n );\n syncEngineImpl.queryViewsByQuery.delete(query);\n return;\n }\n\n // No other queries are mapped to the target, clean up the query and the target.\n if (syncEngineImpl.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n const targetRemainsActive =\n syncEngineImpl.sharedClientState.isActiveQueryTarget(queryView.targetId);\n\n if (!targetRemainsActive) {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ false\n )\n .then(() => {\n syncEngineImpl.sharedClientState.clearQueryState(queryView.targetId);\n if (shouldUnlistenToRemote) {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\n }\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n } else {\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ true\n );\n }\n}\n\n/** Unlistens to the remote store while still listening to the cache. */\nexport async function triggerRemoteStoreUnlisten(\n syncEngine: SyncEngine,\n query: Query\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n debugAssert(\n !!queryView,\n 'Trying to unlisten on query not found:' + stringifyQuery(query)\n );\n const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId)!;\n\n if (syncEngineImpl.isPrimaryClient && queries.length === 1) {\n // PORTING NOTE: Unregister the target ID with local Firestore client as\n // watch target.\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\n }\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */\nexport async function syncEngineWrite(\n syncEngine: SyncEngine,\n batch: Mutation[],\n userCallback: Deferred\n): Promise {\n const syncEngineImpl = syncEngineEnsureWriteCallbacks(syncEngine);\n\n try {\n const result = await localStoreWriteLocally(\n syncEngineImpl.localStore,\n batch\n );\n syncEngineImpl.sharedClientState.addPendingMutation(result.batchId);\n addMutationCallback(syncEngineImpl, result.batchId, userCallback);\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.changes\n );\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } catch (e) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const error = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to persist write`\n );\n userCallback.reject(error);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */\nexport async function syncEngineApplyRemoteEvent(\n syncEngine: SyncEngine,\n remoteEvent: RemoteEvent\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreApplyRemoteEventToLocalCache(\n syncEngineImpl.localStore,\n remoteEvent\n );\n // Update `receivedDocument` as appropriate for any limbo targets.\n remoteEvent.targetChanges.forEach((targetChange, targetId) => {\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution) {\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n hardAssert(\n targetChange.addedDocuments.size +\n targetChange.modifiedDocuments.size +\n targetChange.removedDocuments.size <=\n 1,\n 'Limbo resolution for single document contains multiple changes.'\n );\n if (targetChange.addedDocuments.size > 0) {\n limboResolution.receivedDocument = true;\n } else if (targetChange.modifiedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 'Received remove for limbo target document without add.'\n );\n limboResolution.receivedDocument = false;\n } else {\n // This was probably just a CURRENT targetChange or similar.\n }\n }\n });\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n remoteEvent\n );\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\nexport function syncEngineApplyOnlineStateChange(\n syncEngine: SyncEngine,\n onlineState: OnlineState,\n source: OnlineStateSource\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (\n (syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.RemoteStore) ||\n (!syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.SharedClientState)\n ) {\n const newViewSnapshots = [] as ViewSnapshot[];\n syncEngineImpl.queryViewsByQuery.forEach((query, queryView) => {\n const viewChange = queryView.view.applyOnlineStateChange(onlineState);\n debugAssert(\n viewChange.limboChanges.length === 0,\n 'OnlineState should not affect limbo documents.'\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n\n eventManagerOnOnlineStateChange(syncEngineImpl.eventManager, onlineState);\n\n if (newViewSnapshots.length) {\n debugAssert(\n !!syncEngineImpl.syncEngineListener.onWatchChange,\n 'Active views but EventManager callbacks are not assigned'\n );\n syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots);\n }\n\n syncEngineImpl.onlineState = onlineState;\n if (syncEngineImpl.isPrimaryClient) {\n syncEngineImpl.sharedClientState.setOnlineState(onlineState);\n }\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */\nexport async function syncEngineRejectListen(\n syncEngine: SyncEngine,\n targetId: TargetId,\n err: FirestoreError\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // PORTING NOTE: Multi-tab only.\n syncEngineImpl.sharedClientState.updateQueryState(targetId, 'rejected', err);\n\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n const limboKey = limboResolution && limboResolution.key;\n if (limboKey) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let documentUpdates = new SortedMap(\n DocumentKey.comparator\n );\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n documentUpdates = documentUpdates.insert(\n limboKey,\n MutableDocument.newNoDocument(limboKey, SnapshotVersion.min())\n );\n const resolvedLimboDocuments = documentKeySet().add(limboKey);\n const event = new RemoteEvent(\n SnapshotVersion.min(),\n /* targetChanges= */ new Map(),\n /* targetMismatches= */ new SortedMap(\n primitiveComparator\n ),\n documentUpdates,\n resolvedLimboDocuments\n );\n\n await syncEngineApplyRemoteEvent(syncEngineImpl, event);\n\n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(limboKey);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(targetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n } else {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => removeAndCleanupTarget(syncEngineImpl, targetId, err))\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nexport async function syncEngineApplySuccessfulWrite(\n syncEngine: SyncEngine,\n mutationBatchResult: MutationBatchResult\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const batchId = mutationBatchResult.batch.batchId;\n\n try {\n const changes = await localStoreAcknowledgeBatch(\n syncEngineImpl.localStore,\n mutationBatchResult\n );\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n processUserCallback(syncEngineImpl, batchId, /*error=*/ null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'acknowledged'\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\nexport async function syncEngineRejectFailedWrite(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreRejectBatch(\n syncEngineImpl.localStore,\n batchId\n );\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n processUserCallback(syncEngineImpl, batchId, error);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'rejected',\n error\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */\nexport async function syncEngineRegisterPendingWritesCallback(\n syncEngine: SyncEngine,\n callback: Deferred\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (!canUseNetwork(syncEngineImpl.remoteStore)) {\n logDebug(\n LOG_TAG,\n 'The network is disabled. The task returned by ' +\n \"'awaitPendingWrites()' will not complete until the network is enabled.\"\n );\n }\n\n try {\n const highestBatchId = await localStoreGetHighestUnacknowledgedBatchId(\n syncEngineImpl.localStore\n );\n if (highestBatchId === BATCHID_UNKNOWN) {\n // Trigger the callback right away if there is no pending writes at the moment.\n callback.resolve();\n return;\n }\n\n const callbacks =\n syncEngineImpl.pendingWritesCallbacks.get(highestBatchId) || [];\n callbacks.push(callback);\n syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n 'Initialization of waitForPendingWrites() operation failed'\n );\n callback.reject(firestoreError);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */\nfunction triggerPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId\n): void {\n (syncEngineImpl.pendingWritesCallbacks.get(batchId) || []).forEach(\n callback => {\n callback.resolve();\n }\n );\n\n syncEngineImpl.pendingWritesCallbacks.delete(batchId);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */\nfunction rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n errorMessage: string\n): void {\n syncEngineImpl.pendingWritesCallbacks.forEach(callbacks => {\n callbacks.forEach(callback => {\n callback.reject(new FirestoreError(Code.CANCELLED, errorMessage));\n });\n });\n\n syncEngineImpl.pendingWritesCallbacks.clear();\n}\n\nfunction addMutationCallback(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId,\n callback: Deferred\n): void {\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap>(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n}\n\n/**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\nfunction processUserCallback(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError | null\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (newCallbacks) {\n const callback = newCallbacks.get(batchId);\n if (callback) {\n debugAssert(\n batchId === newCallbacks.minKey(),\n 'Mutation callbacks processed out-of-order?'\n );\n if (error) {\n callback.reject(error);\n } else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n }\n}\n\nfunction removeAndCleanupTarget(\n syncEngineImpl: SyncEngineImpl,\n targetId: number,\n error: FirestoreError | null = null\n): void {\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(targetId);\n\n debugAssert(\n syncEngineImpl.queriesByTarget.has(targetId) &&\n syncEngineImpl.queriesByTarget.get(targetId)!.length !== 0,\n `There are no queries mapped to target id ${targetId}`\n );\n\n for (const query of syncEngineImpl.queriesByTarget.get(targetId)!) {\n syncEngineImpl.queryViewsByQuery.delete(query);\n if (error) {\n syncEngineImpl.syncEngineListener.onWatchError!(query, error);\n }\n }\n\n syncEngineImpl.queriesByTarget.delete(targetId);\n\n if (syncEngineImpl.isPrimaryClient) {\n const limboKeys =\n syncEngineImpl.limboDocumentRefs.removeReferencesForId(targetId);\n limboKeys.forEach(limboKey => {\n const isReferenced =\n syncEngineImpl.limboDocumentRefs.containsKey(limboKey);\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboKey);\n }\n });\n }\n}\n\nfunction removeLimboTarget(\n syncEngineImpl: SyncEngineImpl,\n key: DocumentKey\n): void {\n syncEngineImpl.enqueuedLimboResolutions.delete(key.path.canonicalString());\n\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const limboTargetId = syncEngineImpl.activeLimboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n\n remoteStoreUnlisten(syncEngineImpl.remoteStore, limboTargetId);\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(key);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(limboTargetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n}\n\nfunction updateTrackedLimbos(\n syncEngineImpl: SyncEngineImpl,\n targetId: TargetId,\n limboChanges: LimboDocumentChange[]\n): void {\n for (const limboChange of limboChanges) {\n if (limboChange instanceof AddedLimboDocument) {\n syncEngineImpl.limboDocumentRefs.addReference(limboChange.key, targetId);\n trackLimboChange(syncEngineImpl, limboChange);\n } else if (limboChange instanceof RemovedLimboDocument) {\n logDebug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n syncEngineImpl.limboDocumentRefs.removeReference(\n limboChange.key,\n targetId\n );\n const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(\n limboChange.key\n );\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboChange.key);\n }\n } else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n}\n\nfunction trackLimboChange(\n syncEngineImpl: SyncEngineImpl,\n limboChange: AddedLimboDocument\n): void {\n const key = limboChange.key;\n const keyString = key.path.canonicalString();\n if (\n !syncEngineImpl.activeLimboTargetsByKey.get(key) &&\n !syncEngineImpl.enqueuedLimboResolutions.has(keyString)\n ) {\n logDebug(LOG_TAG, 'New document in limbo: ' + key);\n syncEngineImpl.enqueuedLimboResolutions.add(keyString);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n }\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */\nfunction pumpEnqueuedLimboResolutions(syncEngineImpl: SyncEngineImpl): void {\n while (\n syncEngineImpl.enqueuedLimboResolutions.size > 0 &&\n syncEngineImpl.activeLimboTargetsByKey.size <\n syncEngineImpl.maxConcurrentLimboResolutions\n ) {\n const keyString = syncEngineImpl.enqueuedLimboResolutions\n .values()\n .next().value;\n syncEngineImpl.enqueuedLimboResolutions.delete(keyString);\n const key = new DocumentKey(ResourcePath.fromString(keyString));\n const limboTargetId = syncEngineImpl.limboTargetIdGenerator.next();\n syncEngineImpl.activeLimboResolutionsByTarget.set(\n limboTargetId,\n new LimboResolution(key)\n );\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.insert(key, limboTargetId);\n remoteStoreListen(\n syncEngineImpl.remoteStore,\n new TargetData(\n queryToTarget(newQueryForPath(key.path)),\n limboTargetId,\n TargetPurpose.LimboResolution,\n ListenSequence.INVALID\n )\n );\n }\n}\n\n// Visible for testing\nexport function syncEngineGetActiveLimboDocumentResolutions(\n syncEngine: SyncEngine\n): SortedMap {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.activeLimboTargetsByKey;\n}\n\n// Visible for testing\nexport function syncEngineGetEnqueuedLimboDocumentResolutions(\n syncEngine: SyncEngine\n): Set {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.enqueuedLimboResolutions;\n}\n\nexport async function syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine: SyncEngine,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const newSnaps: ViewSnapshot[] = [];\n const docChangesInAllViews: LocalViewChanges[] = [];\n const queriesProcessed: Array> = [];\n\n if (syncEngineImpl.queryViewsByQuery.isEmpty()) {\n // Return early since `onWatchChange()` might not have been assigned yet.\n return;\n }\n\n syncEngineImpl.queryViewsByQuery.forEach((_, queryView) => {\n debugAssert(\n !!syncEngineImpl.applyDocChanges,\n 'ApplyDocChangesHandler not set'\n );\n queriesProcessed.push(\n syncEngineImpl\n .applyDocChanges(queryView, changes, remoteEvent)\n .then(viewSnapshot => {\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n if (viewSnapshot || remoteEvent) {\n if (syncEngineImpl.isPrimaryClient) {\n const isCurrent = viewSnapshot && !viewSnapshot.fromCache;\n syncEngineImpl.sharedClientState.updateQueryState(\n queryView.targetId,\n isCurrent ? 'current' : 'not-current'\n );\n }\n }\n\n // Update views if there are actual changes.\n if (!!viewSnapshot) {\n newSnaps.push(viewSnapshot);\n const docChanges = LocalViewChanges.fromSnapshot(\n queryView.targetId,\n viewSnapshot\n );\n docChangesInAllViews.push(docChanges);\n }\n })\n );\n });\n\n await Promise.all(queriesProcessed);\n syncEngineImpl.syncEngineListener.onWatchChange!(newSnaps);\n await localStoreNotifyLocalViewChanges(\n syncEngineImpl.localStore,\n docChangesInAllViews\n );\n}\n\nasync function applyDocChanges(\n syncEngineImpl: SyncEngineImpl,\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise {\n let viewDocChanges = queryView.view.computeDocChanges(changes);\n if (viewDocChanges.needsRefill) {\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n viewDocChanges = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ false\n ).then(({ documents }) => {\n return queryView.view.computeDocChanges(documents, viewDocChanges);\n });\n }\n\n const targetChange =\n remoteEvent && remoteEvent.targetChanges.get(queryView.targetId);\n const targetIsPendingReset =\n remoteEvent && remoteEvent.targetMismatches.get(queryView.targetId) != null;\n const viewChange = queryView.view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient,\n targetChange,\n targetIsPendingReset\n );\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewChange.limboChanges\n );\n return viewChange.snapshot;\n}\n\nexport async function syncEngineHandleCredentialChange(\n syncEngine: SyncEngine,\n user: User\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const userChanged = !syncEngineImpl.currentUser.isEqual(user);\n\n if (userChanged) {\n logDebug(LOG_TAG, 'User change. New user:', user.toKey());\n\n const result = await localStoreHandleUserChange(\n syncEngineImpl.localStore,\n user\n );\n syncEngineImpl.currentUser = user;\n\n // Fails tasks waiting for pending writes requested by previous user.\n rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl,\n \"'waitForPendingWrites' promise is rejected due to a user change.\"\n );\n // TODO(b/114226417): Consider calling this only in the primary tab.\n syncEngineImpl.sharedClientState.handleUserChange(\n user,\n result.removedBatchIds,\n result.addedBatchIds\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.affectedDocuments\n );\n }\n}\n\nexport function syncEngineGetRemoteKeysForTarget(\n syncEngine: SyncEngine,\n targetId: TargetId\n): DocumentKeySet {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution && limboResolution.receivedDocument) {\n return documentKeySet().add(limboResolution.key);\n } else {\n let keySet = documentKeySet();\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n if (!queries) {\n return keySet;\n }\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n keySet = keySet.unionWith(queryView.view.syncedDocuments);\n }\n return keySet;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */\nasync function synchronizeViewAndComputeSnapshot(\n syncEngine: SyncEngine,\n queryView: QueryView\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ true\n );\n const viewSnapshot =\n queryView.view.synchronizeWithPersistedState(queryResult);\n if (syncEngineImpl.isPrimaryClient) {\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewSnapshot.limboChanges\n );\n }\n return viewSnapshot;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineSynchronizeWithChangedDocuments(\n syncEngine: SyncEngine,\n collectionGroup: string\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n return localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n collectionGroup\n ).then(changes =>\n syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes)\n );\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyBatchState(\n syncEngine: SyncEngine,\n batchId: BatchId,\n batchState: MutationBatchState,\n error?: FirestoreError\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const documents = await localStoreLookupMutationDocuments(\n syncEngineImpl.localStore,\n batchId\n );\n\n if (documents === null) {\n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n logDebug(LOG_TAG, 'Cannot apply mutation batch with id: ' + batchId);\n return;\n }\n\n if (batchState === 'pending') {\n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } else if (batchState === 'acknowledged' || batchState === 'rejected') {\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n processUserCallback(syncEngineImpl, batchId, error ? error : null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n localStoreRemoveCachedMutationBatchMetadata(\n syncEngineImpl.localStore,\n batchId\n );\n } else {\n fail(`Unknown batchState: ${batchState}`);\n }\n\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, documents);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyPrimaryState(\n syncEngine: SyncEngine,\n isPrimary: boolean\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n ensureWatchCallbacks(syncEngineImpl);\n syncEngineEnsureWriteCallbacks(syncEngineImpl);\n if (isPrimary === true && syncEngineImpl._isPrimaryClient !== true) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const activeTargets =\n syncEngineImpl.sharedClientState.getAllActiveQueryTargets();\n const activeQueries = await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets.toArray(),\n /*transitionToPrimary=*/ true\n );\n syncEngineImpl._isPrimaryClient = true;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, true);\n for (const targetData of activeQueries) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n } else if (isPrimary === false && syncEngineImpl._isPrimaryClient !== false) {\n const activeTargets: TargetId[] = [];\n\n let p = Promise.resolve();\n syncEngineImpl.queriesByTarget.forEach((_, targetId) => {\n if (syncEngineImpl.sharedClientState.isLocalQueryTarget(targetId)) {\n activeTargets.push(targetId);\n } else {\n p = p.then(() => {\n removeAndCleanupTarget(syncEngineImpl, targetId);\n return localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n });\n }\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n await p;\n\n await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets,\n /*transitionToPrimary=*/ false\n );\n resetLimboDocuments(syncEngineImpl);\n syncEngineImpl._isPrimaryClient = false;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, false);\n }\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction resetLimboDocuments(syncEngine: SyncEngine): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.activeLimboResolutionsByTarget.forEach((_, targetId) => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n syncEngineImpl.limboDocumentRefs.removeAllReferences();\n syncEngineImpl.activeLimboResolutionsByTarget = new Map<\n TargetId,\n LimboResolution\n >();\n syncEngineImpl.activeLimboTargetsByKey = new SortedMap(\n DocumentKey.comparator\n );\n}\n\n/**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n// PORTING NOTE: Multi-Tab only.\nasync function synchronizeQueryViewsAndRaiseSnapshots(\n syncEngine: SyncEngine,\n targets: TargetId[],\n transitionToPrimary: boolean\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const activeQueries: TargetData[] = [];\n const newViewSnapshots: ViewSnapshot[] = [];\n for (const targetId of targets) {\n let targetData: TargetData;\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n\n if (queries && queries.length !== 0) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(queries[0])\n );\n\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n\n const viewChange = await synchronizeViewAndComputeSnapshot(\n syncEngineImpl,\n queryView\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n }\n } else {\n debugAssert(\n transitionToPrimary,\n 'A secondary tab should never have an active view without an active target.'\n );\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Target for id ${targetId} not found`);\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target!),\n targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n }\n\n activeQueries.push(targetData!);\n }\n\n syncEngineImpl.syncEngineListener.onWatchChange!(newViewSnapshots);\n return activeQueries;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction synthesizeTargetToQuery(target: Target): Query {\n return newQuery(\n target.path,\n target.collectionGroup,\n target.orderBy,\n target.filters,\n target.limit,\n LimitType.First,\n target.startAt,\n target.endAt\n );\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nexport function syncEngineGetActiveClients(\n syncEngine: SyncEngine\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return localStoreGetActiveClients(syncEngineImpl.localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyTargetState(\n syncEngine: SyncEngine,\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n): Promise {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (syncEngineImpl._isPrimaryClient) {\n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n logDebug(LOG_TAG, 'Ignoring unexpected query state notification.');\n return;\n }\n\n const query = syncEngineImpl.queriesByTarget.get(targetId);\n if (query && query.length > 0) {\n switch (state) {\n case 'current':\n case 'not-current': {\n const changes = await localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n queryCollectionGroup(query[0])\n );\n const synthesizedRemoteEvent =\n RemoteEvent.createSynthesizedRemoteEventForCurrentChange(\n targetId,\n state === 'current',\n ByteString.EMPTY_BYTE_STRING\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n synthesizedRemoteEvent\n );\n break;\n }\n case 'rejected': {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ true\n );\n removeAndCleanupTarget(syncEngineImpl, targetId, error);\n break;\n }\n default:\n fail('Unexpected target state: ' + state);\n }\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */\nexport async function syncEngineApplyActiveTargetsChange(\n syncEngine: SyncEngine,\n added: TargetId[],\n removed: TargetId[]\n): Promise {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n if (!syncEngineImpl._isPrimaryClient) {\n return;\n }\n\n for (const targetId of added) {\n // A target is already listening to remote store if it is already registered to\n // sharedClientState.\n const targetAlreadyListeningToRemoteStore =\n syncEngineImpl.queriesByTarget.has(targetId) &&\n syncEngineImpl.sharedClientState.isActiveQueryTarget(targetId);\n if (targetAlreadyListeningToRemoteStore) {\n logDebug(LOG_TAG, 'Adding an already active target ' + targetId);\n continue;\n }\n\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Query data for active target ${targetId} not found`);\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target),\n targetData.targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n\n for (const targetId of removed) {\n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n if (!syncEngineImpl.queriesByTarget.has(targetId)) {\n continue;\n }\n\n // Release queries that are still active.\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n removeAndCleanupTarget(syncEngineImpl, targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nfunction ensureWatchCallbacks(syncEngine: SyncEngine): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applyRemoteEvent =\n syncEngineApplyRemoteEvent.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.getRemoteKeysForTarget =\n syncEngineGetRemoteKeysForTarget.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectListen =\n syncEngineRejectListen.bind(null, syncEngineImpl);\n syncEngineImpl.syncEngineListener.onWatchChange =\n eventManagerOnWatchChange.bind(null, syncEngineImpl.eventManager);\n syncEngineImpl.syncEngineListener.onWatchError =\n eventManagerOnWatchError.bind(null, syncEngineImpl.eventManager);\n return syncEngineImpl;\n}\n\nexport function syncEngineEnsureWriteCallbacks(\n syncEngine: SyncEngine\n): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applySuccessfulWrite =\n syncEngineApplySuccessfulWrite.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectFailedWrite =\n syncEngineRejectFailedWrite.bind(null, syncEngineImpl);\n return syncEngineImpl;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */\nexport function syncEngineLoadBundle(\n syncEngine: SyncEngine,\n bundleReader: BundleReader,\n task: LoadBundleTask\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n loadBundleImpl(syncEngineImpl, bundleReader, task).then(collectionGroups => {\n syncEngineImpl.sharedClientState.notifyBundleLoaded(collectionGroups);\n });\n}\n\n/** Loads a bundle and returns the list of affected collection groups. */\nasync function loadBundleImpl(\n syncEngine: SyncEngineImpl,\n reader: BundleReader,\n task: LoadBundleTask\n): Promise> {\n try {\n const metadata = await reader.getMetadata();\n const skip = await localStoreHasNewerBundle(\n syncEngine.localStore,\n metadata\n );\n if (skip) {\n await reader.close();\n task._completeWith(bundleSuccessProgress(metadata));\n return Promise.resolve(new Set());\n }\n\n task._updateProgress(bundleInitialProgress(metadata));\n\n const loader = new BundleLoader(\n metadata,\n syncEngine.localStore,\n reader.serializer\n );\n let element = await reader.nextElement();\n while (element) {\n debugAssert(\n !element.payload.metadata,\n 'Unexpected BundleMetadata element.'\n );\n const progress = await loader.addSizedElement(element);\n if (progress) {\n task._updateProgress(progress);\n }\n\n element = await reader.nextElement();\n }\n\n const result = await loader.complete();\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine,\n result.changedDocs,\n /* remoteEvent */ undefined\n );\n\n // Save metadata, so loading the same bundle will skip.\n await localStoreSaveBundle(syncEngine.localStore, metadata);\n task._completeWith(result.progress);\n return Promise.resolve(result.changedCollectionGroups);\n } catch (e) {\n logWarn(LOG_TAG, `Loading bundle failed with ${e}`);\n task._failWith(e as FirestoreError);\n return Promise.resolve(new Set());\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 { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport {\n IndexBackfiller,\n IndexBackfillerScheduler\n} from '../local/index_backfiller';\nimport {\n indexedDbStoragePrefix,\n IndexedDbPersistence\n} from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { newLocalStore } from '../local/local_store_impl';\nimport { LruParams } from '../local/lru_garbage_collector';\nimport { LruScheduler } from '../local/lru_garbage_collector_impl';\nimport {\n MemoryEagerDelegate,\n MemoryLruDelegate,\n MemoryPersistence\n} from '../local/memory_persistence';\nimport { Scheduler, Persistence } from '../local/persistence';\nimport { QueryEngine } from '../local/query_engine';\nimport {\n ClientId,\n MemorySharedClientState,\n SharedClientState,\n WebStorageSharedClientState\n} from '../local/shared_client_state';\nimport { newConnection, newConnectivityMonitor } from '../platform/connection';\nimport { getDocument, getWindow } from '../platform/dom';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport {\n fillWritePipeline,\n newRemoteStore,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreShutdown\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { DatabaseInfo } from './database_info';\nimport { EventManager, newEventManager } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport {\n newSyncEngine,\n syncEngineApplyActiveTargetsChange,\n syncEngineApplyBatchState,\n syncEngineApplyOnlineStateChange,\n syncEngineApplyPrimaryState,\n syncEngineApplyTargetState,\n syncEngineEnsureWriteCallbacks,\n syncEngineGetActiveClients,\n syncEngineHandleCredentialChange,\n syncEngineSynchronizeWithChangedDocuments\n} from './sync_engine_impl';\nimport { OnlineStateSource } from './types';\n\nexport interface ComponentConfiguration {\n asyncQueue: AsyncQueue;\n databaseInfo: DatabaseInfo;\n authCredentials: CredentialsProvider;\n appCheckCredentials: CredentialsProvider;\n clientId: ClientId;\n initialUser: User;\n maxConcurrentLimboResolutions: number;\n}\n\n/**\n * Initializes and wires components that are needed to interface with the local\n * cache. Implementations override `initialize()` to provide all components.\n */\nexport interface OfflineComponentProvider {\n persistence: Persistence;\n sharedClientState: SharedClientState;\n localStore: LocalStore;\n gcScheduler: Scheduler | null;\n indexBackfillerScheduler: Scheduler | null;\n synchronizeTabs: boolean;\n\n initialize(cfg: ComponentConfiguration): Promise;\n\n terminate(): Promise;\n}\n\n/**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */\nexport class MemoryOfflineComponentProvider\n implements OfflineComponentProvider\n{\n persistence!: Persistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n serializer!: JsonProtoSerializer;\n\n async initialize(cfg: ComponentConfiguration): Promise {\n this.serializer = newSerializer(cfg.databaseInfo.databaseId);\n this.sharedClientState = this.createSharedClientState(cfg);\n this.persistence = this.createPersistence(cfg);\n await this.persistence.start();\n this.localStore = this.createLocalStore(cfg);\n this.gcScheduler = this.createGarbageCollectionScheduler(\n cfg,\n this.localStore\n );\n this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(\n cfg,\n this.localStore\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n return new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer);\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n\n async terminate(): Promise {\n this.gcScheduler?.stop();\n this.indexBackfillerScheduler?.stop();\n this.sharedClientState.shutdown();\n await this.persistence.shutdown();\n }\n}\n\nexport class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider {\n constructor(protected readonly cacheSizeBytes: number | undefined) {\n super();\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n hardAssert(\n this.persistence.referenceDelegate instanceof MemoryLruDelegate,\n 'referenceDelegate is expected to be an instance of MemoryLruDelegate.'\n );\n\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n return new MemoryPersistence(\n p => MemoryLruDelegate.factory(p, lruParams),\n this.serializer\n );\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */\nexport class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider {\n persistence!: IndexedDbPersistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined,\n protected readonly forceOwnership: boolean | undefined\n ) {\n super();\n }\n\n async initialize(cfg: ComponentConfiguration): Promise {\n await super.initialize(cfg);\n\n await this.onlineComponentProvider.initialize(this, cfg);\n\n // Enqueue writes from a previous session\n await syncEngineEnsureWriteCallbacks(\n this.onlineComponentProvider.syncEngine\n );\n await fillWritePipeline(this.onlineComponentProvider.remoteStore);\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(() => {\n if (this.gcScheduler && !this.gcScheduler.started) {\n this.gcScheduler.start();\n }\n if (\n this.indexBackfillerScheduler &&\n !this.indexBackfillerScheduler.started\n ) {\n this.indexBackfillerScheduler.start();\n }\n return Promise.resolve();\n });\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const indexBackfiller = new IndexBackfiller(localStore, this.persistence);\n return new IndexBackfillerScheduler(cfg.asyncQueue, indexBackfiller);\n }\n\n createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence {\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n\n return new IndexedDbPersistence(\n this.synchronizeTabs,\n persistenceKey,\n cfg.clientId,\n lruParams,\n cfg.asyncQueue,\n getWindow(),\n getDocument(),\n this.serializer,\n this.sharedClientState,\n !!this.forceOwnership\n );\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */\nexport class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider {\n synchronizeTabs = true;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined\n ) {\n super(onlineComponentProvider, cacheSizeBytes, /* forceOwnership= */ false);\n }\n\n async initialize(cfg: ComponentConfiguration): Promise {\n await super.initialize(cfg);\n\n const syncEngine = this.onlineComponentProvider.syncEngine;\n\n if (this.sharedClientState instanceof WebStorageSharedClientState) {\n this.sharedClientState.syncEngine = {\n applyBatchState: syncEngineApplyBatchState.bind(null, syncEngine),\n applyTargetState: syncEngineApplyTargetState.bind(null, syncEngine),\n applyActiveTargetsChange: syncEngineApplyActiveTargetsChange.bind(\n null,\n syncEngine\n ),\n getActiveClients: syncEngineGetActiveClients.bind(null, syncEngine),\n synchronizeWithChangedDocuments:\n syncEngineSynchronizeWithChangedDocuments.bind(null, syncEngine)\n };\n await this.sharedClientState.start();\n }\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(async isPrimary => {\n await syncEngineApplyPrimaryState(\n this.onlineComponentProvider.syncEngine,\n isPrimary\n );\n if (this.gcScheduler) {\n if (isPrimary && !this.gcScheduler.started) {\n this.gcScheduler.start();\n } else if (!isPrimary) {\n this.gcScheduler.stop();\n }\n }\n if (this.indexBackfillerScheduler) {\n if (isPrimary && !this.indexBackfillerScheduler.started) {\n this.indexBackfillerScheduler.start();\n } else if (!isPrimary) {\n this.indexBackfillerScheduler.stop();\n }\n }\n });\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n const window = getWindow();\n if (!WebStorageSharedClientState.isAvailable(window)) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n return new WebStorageSharedClientState(\n window,\n cfg.asyncQueue,\n persistenceKey,\n cfg.clientId,\n cfg.initialUser\n );\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */\nexport class OnlineComponentProvider {\n protected localStore!: LocalStore;\n protected sharedClientState!: SharedClientState;\n datastore!: Datastore;\n eventManager!: EventManager;\n remoteStore!: RemoteStore;\n syncEngine!: SyncEngine;\n\n async initialize(\n offlineComponentProvider: OfflineComponentProvider,\n cfg: ComponentConfiguration\n ): Promise {\n if (this.localStore) {\n // OnlineComponentProvider may get initialized multiple times if\n // multi-tab persistence is used.\n return;\n }\n\n this.localStore = offlineComponentProvider.localStore;\n this.sharedClientState = offlineComponentProvider.sharedClientState;\n this.datastore = this.createDatastore(cfg);\n this.remoteStore = this.createRemoteStore(cfg);\n this.eventManager = this.createEventManager(cfg);\n this.syncEngine = this.createSyncEngine(\n cfg,\n /* startAsPrimary=*/ !offlineComponentProvider.synchronizeTabs\n );\n\n this.sharedClientState.onlineStateHandler = onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.SharedClientState\n );\n\n this.remoteStore.remoteSyncer.handleCredentialChange =\n syncEngineHandleCredentialChange.bind(null, this.syncEngine);\n\n await remoteStoreApplyPrimaryState(\n this.remoteStore,\n this.syncEngine.isPrimaryClient\n );\n }\n\n createEventManager(cfg: ComponentConfiguration): EventManager {\n return newEventManager();\n }\n\n createDatastore(cfg: ComponentConfiguration): Datastore {\n const serializer = newSerializer(cfg.databaseInfo.databaseId);\n const connection = newConnection(cfg.databaseInfo);\n return newDatastore(\n cfg.authCredentials,\n cfg.appCheckCredentials,\n connection,\n serializer\n );\n }\n\n createRemoteStore(cfg: ComponentConfiguration): RemoteStore {\n return newRemoteStore(\n this.localStore,\n this.datastore,\n cfg.asyncQueue,\n onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.RemoteStore\n ),\n newConnectivityMonitor()\n );\n }\n\n createSyncEngine(\n cfg: ComponentConfiguration,\n startAsPrimary: boolean\n ): SyncEngine {\n return newSyncEngine(\n this.localStore,\n this.remoteStore,\n this.eventManager,\n this.sharedClientState,\n cfg.initialUser,\n cfg.maxConcurrentLimboResolutions,\n startAsPrimary\n );\n }\n\n async terminate(): Promise {\n await remoteStoreShutdown(this.remoteStore);\n this.datastore?.terminate();\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 { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\nimport { ConnectivityMonitor } from '../../remote/connectivity_monitor';\nimport { NoopConnectivityMonitor } from '../../remote/connectivity_monitor_noop';\n\nimport { BrowserConnectivityMonitor } from './connectivity_monitor';\nimport { WebChannelConnection } from './webchannel_connection';\n\n/** Initializes the WebChannelConnection for the browser. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new WebChannelConnection(databaseInfo);\n}\n\n/** Return the Platform-specific connectivity monitor. */\nexport function newConnectivityMonitor(): ConnectivityMonitor {\n if (BrowserConnectivityMonitor.isAvailable()) {\n return new BrowserConnectivityMonitor();\n } else {\n return new NoopConnectivityMonitor();\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 { debugAssert } from './assert';\n\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\nexport const DEFAULT_BYTES_PER_READ = 10240;\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nexport function toByteStreamReaderHelper(\n source: Uint8Array,\n bytesPerRead: number = DEFAULT_BYTES_PER_READ\n): ReadableStreamReader {\n debugAssert(\n bytesPerRead > 0,\n `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n );\n let readFrom = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reader: any = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read(): Promise {\n if (readFrom < source.byteLength) {\n const result = {\n value: source.slice(readFrom, readFrom + bytesPerRead),\n done: false\n } as const;\n readFrom += bytesPerRead;\n return result;\n }\n\n return { done: true };\n },\n async cancel(): Promise {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n return reader;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Observer } from '../core/event_manager';\n\nimport { FirestoreError } from './error';\nimport { logError } from './log';\nimport { EventHandler } from './misc';\n\n/*\n * A wrapper implementation of Observer that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nexport class AsyncObserver implements Observer {\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n private muted = false;\n\n constructor(private observer: Partial>) {}\n\n next(value: T): void {\n if (this.observer.next) {\n this.scheduleEvent(this.observer.next, value);\n }\n }\n\n error(error: FirestoreError): void {\n if (this.observer.error) {\n this.scheduleEvent(this.observer.error, error);\n } else {\n logError('Uncaught Error in snapshot listener:', error.toString());\n }\n }\n\n mute(): void {\n this.muted = true;\n }\n\n private scheduleEvent(eventHandler: EventHandler, event: E): void {\n if (!this.muted) {\n setTimeout(() => {\n if (!this.muted) {\n eventHandler(event);\n }\n }, 0);\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 { newTextDecoder } from '../platform/text_serializer';\nimport { BundleMetadata } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\nimport { debugAssert } from './assert';\nimport { BundleReader, SizedBundleElement } from './bundle_reader';\nimport { Deferred } from './promise';\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nclass BundleReaderImpl implements BundleReader {\n /** Cached bundle metadata. */\n private metadata: Deferred = new Deferred();\n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n private buffer: Uint8Array = new Uint8Array();\n /** The decoder used to parse binary data into strings. */\n private textDecoder: TextDecoder;\n\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n private reader: ReadableStreamReader,\n readonly serializer: JsonProtoSerializer\n ) {\n this.textDecoder = newTextDecoder();\n // Read the metadata (which is the first element).\n this.nextElementImpl().then(\n element => {\n if (element && element.isBundleMetadata()) {\n this.metadata.resolve(element.payload.metadata!);\n } else {\n this.metadata.reject(\n new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(element?.payload)}`)\n );\n }\n },\n error => this.metadata.reject(error)\n );\n }\n\n close(): Promise {\n return this.reader.cancel();\n }\n\n async getMetadata(): Promise {\n return this.metadata.promise;\n }\n\n async nextElement(): Promise {\n // Makes sure metadata is read before proceeding.\n await this.getMetadata();\n return this.nextElementImpl();\n }\n\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */\n private async nextElementImpl(): Promise {\n const lengthBuffer = await this.readLength();\n if (lengthBuffer === null) {\n return null;\n }\n\n const lengthString = this.textDecoder.decode(lengthBuffer);\n const length = Number(lengthString);\n if (isNaN(length)) {\n this.raiseError(`length string (${lengthString}) is not valid number`);\n }\n\n const jsonString = await this.readJsonString(length);\n\n return new SizedBundleElement(\n JSON.parse(jsonString),\n lengthBuffer.length + length\n );\n }\n\n /** First index of '{' from the underlying buffer. */\n private indexOfOpenBracket(): number {\n return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n }\n\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */\n private async readLength(): Promise {\n while (this.indexOfOpenBracket() < 0) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n break;\n }\n }\n\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (this.buffer.length === 0) {\n return null;\n }\n\n const position = this.indexOfOpenBracket();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n if (position < 0) {\n this.raiseError(\n 'Reached the end of bundle when a length string is expected.'\n );\n }\n\n const result = this.buffer.slice(0, position);\n // Update the internal buffer to drop the read length.\n this.buffer = this.buffer.slice(position);\n return result;\n }\n\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */\n private async readJsonString(length: number): Promise {\n while (this.buffer.length < length) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n this.raiseError('Reached the end of bundle when more is expected.');\n }\n }\n\n const result = this.textDecoder.decode(this.buffer.slice(0, length));\n // Update the internal buffer to drop the read json string.\n this.buffer = this.buffer.slice(length);\n return result;\n }\n\n private raiseError(message: string): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.reader.cancel();\n throw new Error(`Invalid bundle format: ${message}`);\n }\n\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */\n private async pullMoreDataToBuffer(): Promise {\n const result = await this.reader.read();\n if (!result.done) {\n debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n const newBuffer = new Uint8Array(\n this.buffer.length + result.value!.length\n );\n newBuffer.set(this.buffer);\n newBuffer.set(result.value!, this.buffer.length);\n this.buffer = newBuffer;\n }\n return result.done;\n }\n}\n\nexport function newBundleReader(\n reader: ReadableStreamReader,\n serializer: JsonProtoSerializer\n): BundleReader {\n return new BundleReaderImpl(reader, serializer);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail('Document in a transaction was a ' + doc.constructor.name);\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\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\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error): boolean {\n if (error.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport { Deferred } from '../util/promise';\n\nimport { Aggregate } from './aggregate';\nimport { NamedQuery } from './bundle';\nimport {\n ComponentConfiguration,\n MemoryOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from './component_provider';\nimport { DatabaseId, DatabaseInfo } from './database_info';\nimport {\n addSnapshotsInSyncListener,\n EventManager,\n eventManagerListen,\n eventManagerUnlisten,\n ListenOptions,\n Observer,\n QueryListener,\n removeSnapshotsInSyncListener\n} from './event_manager';\nimport { newQueryForPath, Query } from './query';\nimport { SyncEngine } from './sync_engine';\nimport {\n syncEngineListen,\n syncEngineLoadBundle,\n syncEngineRegisterPendingWritesCallback,\n syncEngineUnlisten,\n syncEngineWrite,\n triggerRemoteStoreListen,\n triggerRemoteStoreUnlisten\n} from './sync_engine_impl';\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\nimport { TransactionRunner } from './transaction_runner';\nimport { View } from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'FirestoreClient';\nexport const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100;\n\n/** DOMException error code constants. */\nconst DOM_EXCEPTION_INVALID_STATE = 11;\nconst DOM_EXCEPTION_ABORTED = 20;\nconst DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\n\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the //\n * pieces of the client SDK architecture. It is responsible for creating the //\n * async queue that is shared by all of the other components in the system. //\n */\nexport class FirestoreClient {\n private user = User.UNAUTHENTICATED;\n private readonly clientId = AutoId.newId();\n private authCredentialListener: CredentialChangeListener = () =>\n Promise.resolve();\n private appCheckCredentialListener: (\n appCheckToken: string,\n user: User\n ) => Promise = () => Promise.resolve();\n _uninitializedComponentsProvider?: {\n _offline: OfflineComponentProvider;\n _offlineKind: 'memory' | 'persistent';\n _online: OnlineComponentProvider;\n };\n\n _offlineComponents?: OfflineComponentProvider;\n _onlineComponents?: OnlineComponentProvider;\n\n constructor(\n private authCredentials: CredentialsProvider,\n private appCheckCredentials: CredentialsProvider,\n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n public asyncQueue: AsyncQueue,\n private databaseInfo: DatabaseInfo\n ) {\n this.authCredentials.start(asyncQueue, async user => {\n logDebug(LOG_TAG, 'Received user=', user.uid);\n await this.authCredentialListener(user);\n this.user = user;\n });\n this.appCheckCredentials.start(asyncQueue, newAppCheckToken => {\n logDebug(LOG_TAG, 'Received new app check token=', newAppCheckToken);\n return this.appCheckCredentialListener(newAppCheckToken, this.user);\n });\n }\n\n get configuration(): ComponentConfiguration {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: MAX_CONCURRENT_LIMBO_RESOLUTIONS\n };\n }\n\n setCredentialChangeListener(listener: (user: User) => Promise): void {\n this.authCredentialListener = listener;\n }\n\n setAppCheckTokenChangeListener(\n listener: (appCheckToken: string, user: User) => Promise\n ): void {\n this.appCheckCredentialListener = listener;\n }\n\n /**\n * Checks that the client has not been terminated. Ensures that other methods on //\n * this class cannot be called after the client is terminated. //\n */\n verifyNotTerminated(): void {\n if (this.asyncQueue.isShuttingDown) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n terminate(): Promise {\n this.asyncQueue.enterRestrictedMode();\n const deferred = new Deferred();\n this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n if (this._onlineComponents) {\n await this._onlineComponents.terminate();\n }\n if (this._offlineComponents) {\n await this._offlineComponents.terminate();\n }\n\n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown();\n this.appCheckCredentials.shutdown();\n deferred.resolve();\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to shutdown persistence`\n );\n deferred.reject(firestoreError);\n }\n });\n return deferred.promise;\n }\n}\n\nexport async function setOfflineComponentProvider(\n client: FirestoreClient,\n offlineComponentProvider: OfflineComponentProvider\n): Promise {\n client.asyncQueue.verifyOperationInProgress();\n\n logDebug(LOG_TAG, 'Initializing OfflineComponentProvider');\n const configuration = client.configuration;\n await offlineComponentProvider.initialize(configuration);\n\n let currentUser = configuration.initialUser;\n client.setCredentialChangeListener(async user => {\n if (!currentUser.isEqual(user)) {\n await localStoreHandleUserChange(\n offlineComponentProvider.localStore,\n user\n );\n currentUser = user;\n }\n });\n\n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n offlineComponentProvider.persistence.setDatabaseDeletedListener(() =>\n client.terminate()\n );\n\n client._offlineComponents = offlineComponentProvider;\n}\n\nexport async function setOnlineComponentProvider(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider\n): Promise {\n client.asyncQueue.verifyOperationInProgress();\n\n const offlineComponentProvider = await ensureOfflineComponents(client);\n\n logDebug(LOG_TAG, 'Initializing OnlineComponentProvider');\n await onlineComponentProvider.initialize(\n offlineComponentProvider,\n client.configuration\n );\n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n client.setCredentialChangeListener(user =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client.setAppCheckTokenChangeListener((_, user) =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client._onlineComponents = onlineComponentProvider;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\nexport function canFallbackFromIndexedDbError(\n error: FirestoreError | DOMException\n): boolean {\n if (error.name === 'FirebaseError') {\n return (\n error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED\n );\n } else if (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException\n ) {\n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n return (\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n error.code === DOM_EXCEPTION_QUOTA_EXCEEDED ||\n error.code === DOM_EXCEPTION_ABORTED ||\n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n error.code === DOM_EXCEPTION_INVALID_STATE\n );\n }\n\n return true;\n}\n\nasync function ensureOfflineComponents(\n client: FirestoreClient\n): Promise {\n if (!client._offlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OfflineComponentProvider');\n try {\n await setOfflineComponentProvider(\n client,\n client._uninitializedComponentsProvider._offline\n );\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error using user provided cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n } else {\n logDebug(LOG_TAG, 'Using default OfflineComponentProvider');\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nasync function ensureOnlineComponents(\n client: FirestoreClient\n): Promise {\n if (!client._onlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OnlineComponentProvider');\n await setOnlineComponentProvider(\n client,\n client._uninitializedComponentsProvider._online\n );\n } else {\n logDebug(LOG_TAG, 'Using default OnlineComponentProvider');\n await setOnlineComponentProvider(client, new OnlineComponentProvider());\n }\n }\n\n return client._onlineComponents!;\n}\n\nfunction getPersistence(client: FirestoreClient): Promise {\n return ensureOfflineComponents(client).then(c => c.persistence);\n}\n\nexport function getLocalStore(client: FirestoreClient): Promise {\n return ensureOfflineComponents(client).then(c => c.localStore);\n}\n\nfunction getRemoteStore(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.remoteStore);\n}\n\nexport function getSyncEngine(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.syncEngine);\n}\n\nfunction getDatastore(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.datastore);\n}\n\nexport async function getEventManager(\n client: FirestoreClient\n): Promise {\n const onlineComponentProvider = await ensureOnlineComponents(client);\n const eventManager = onlineComponentProvider.eventManager;\n eventManager.onListen = syncEngineListen.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onUnlisten = syncEngineUnlisten.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onFirstRemoteStoreListen = triggerRemoteStoreListen.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onLastRemoteStoreUnlisten = triggerRemoteStoreUnlisten.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n return eventManager;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */\nexport function firestoreClientEnableNetwork(\n client: FirestoreClient\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(true);\n return remoteStoreEnableNetwork(remoteStore);\n });\n}\n\n/** Disables the network connection. Pending operations will not complete. */\nexport function firestoreClientDisableNetwork(\n client: FirestoreClient\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(false);\n return remoteStoreDisableNetwork(remoteStore);\n });\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */\nexport function firestoreClientWaitForPendingWrites(\n client: FirestoreClient\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineRegisterPendingWritesCallback(syncEngine, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientListen(\n client: FirestoreClient,\n query: Query,\n options: ListenOptions,\n observer: Partial>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n const listener = new QueryListener(query, wrappedObserver, options);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerListen(eventManager, listener);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerUnlisten(eventManager, listener);\n });\n };\n}\n\nexport function firestoreClientGetDocumentFromLocalCache(\n client: FirestoreClient,\n docKey: DocumentKey\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return readDocumentFromCache(localStore, docKey, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentViaSnapshotListener(\n client: FirestoreClient,\n key: DocumentKey,\n options: GetOptions = {}\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return readDocumentViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n key,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsFromLocalCache(\n client: FirestoreClient,\n query: Query\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return executeQueryFromCache(localStore, query, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsViaSnapshotListener(\n client: FirestoreClient,\n query: Query,\n options: GetOptions = {}\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return executeQueryViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n query,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientRunAggregateQuery(\n client: FirestoreClient,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const deferred = new Deferred>();\n\n client.asyncQueue.enqueueAndForget(async () => {\n // Implement and call executeAggregateQueryViaSnapshotListener, similar\n // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n // above\n try {\n // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n const datastore = await getDatastore(client);\n deferred.resolve(\n invokeRunAggregationQueryRpc(datastore, query, aggregates)\n );\n } catch (e) {\n deferred.reject(e as Error);\n }\n });\n return deferred.promise;\n}\n\nexport function firestoreClientWrite(\n client: FirestoreClient,\n mutations: Mutation[]\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineWrite(syncEngine, mutations, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientAddSnapshotsInSyncListener(\n client: FirestoreClient,\n observer: Partial>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return addSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return removeSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */\nexport function firestoreClientTransaction(\n client: FirestoreClient,\n updateFunction: (transaction: Transaction) => Promise,\n options: TransactionOptions\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const datastore = await getDatastore(client);\n new TransactionRunner(\n client.asyncQueue,\n datastore,\n options,\n updateFunction,\n deferred\n ).run();\n });\n return deferred.promise;\n}\n\nasync function readDocumentFromCache(\n localStore: LocalStore,\n docKey: DocumentKey,\n result: Deferred\n): Promise {\n try {\n const document = await localStoreReadDocument(localStore, docKey);\n if (document.isFoundDocument()) {\n result.resolve(document);\n } else if (document.isNoDocument()) {\n result.resolve(null);\n } else {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from cache. (However, this document may ' +\n \"exist on the server. Run again without setting 'source' in \" +\n 'the GetOptions to attempt to retrieve the document from the ' +\n 'server.)'\n )\n );\n }\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to get document '${docKey} from cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */\nfunction readDocumentViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n key: DocumentKey,\n options: GetOptions,\n result: Deferred\n): Promise {\n const wrappedObserver = new AsyncObserver({\n next: (snap: ViewSnapshot) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n const exists = snap.docs.has(key);\n if (!exists && snap.fromCache) {\n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document because the client is offline.'\n )\n );\n } else if (\n exists &&\n snap.fromCache &&\n options &&\n options.source === 'server'\n ) {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from server. (However, this ' +\n 'document does exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached document.)'\n )\n );\n } else {\n debugAssert(\n snap.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n result.resolve(snap);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(\n newQueryForPath(key.path),\n wrappedObserver,\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n }\n );\n return eventManagerListen(eventManager, listener);\n}\n\nasync function executeQueryFromCache(\n localStore: LocalStore,\n query: Query,\n result: Deferred\n): Promise {\n try {\n const queryResult = await localStoreExecuteQuery(\n localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ false\n );\n result.resolve(viewChange.snapshot!);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to execute query '${query} against cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */\nfunction executeQueryViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n query: Query,\n options: GetOptions,\n result: Deferred\n): Promise {\n const wrappedObserver = new AsyncObserver({\n next: snapshot => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n if (snapshot.fromCache && options.source === 'server') {\n result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get documents from server. (However, these ' +\n 'documents may exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached documents.)'\n )\n );\n } else {\n result.resolve(snapshot);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(query, wrappedObserver, {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n });\n return eventManagerListen(eventManager, listener);\n}\n\nexport function firestoreClientLoadBundle(\n client: FirestoreClient,\n databaseId: DatabaseId,\n data: ReadableStream | ArrayBuffer | string,\n resultTask: LoadBundleTask\n): void {\n const reader = createBundleReader(data, newSerializer(databaseId));\n client.asyncQueue.enqueueAndForget(async () => {\n syncEngineLoadBundle(await getSyncEngine(client), reader, resultTask);\n });\n}\n\nexport function firestoreClientGetNamedQuery(\n client: FirestoreClient,\n queryName: string\n): Promise {\n return client.asyncQueue.enqueue(async () =>\n localStoreGetNamedQuery(await getLocalStore(client), queryName)\n );\n}\n\nfunction createBundleReader(\n data: ReadableStream | ArrayBuffer | string,\n serializer: JsonProtoSerializer\n): BundleReader {\n let content: ReadableStream | ArrayBuffer;\n if (typeof data === 'string') {\n content = newTextEncoder().encode(data);\n } else {\n content = data;\n }\n return newBundleReader(toByteStreamReader(content), serializer);\n}\n\nexport function firestoreClientSetIndexConfiguration(\n client: FirestoreClient,\n indexes: FieldIndex[]\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n return localStoreConfigureFieldIndexes(\n await getLocalStore(client),\n indexes\n );\n });\n}\n\nexport function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n client: FirestoreClient,\n isEnabled: boolean\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n return localStoreSetIndexAutoCreationEnabled(\n await getLocalStore(client),\n isEnabled\n );\n });\n}\n\nexport function firestoreClientDeleteAllFieldIndexes(\n client: FirestoreClient\n): Promise {\n return client.asyncQueue.enqueue(async () => {\n return localStoreDeleteAllFieldIndexes(await getLocalStore(client));\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 { BundleSource } from '../../util/bundle_reader';\nimport { toByteStreamReaderHelper } from '../../util/byte_stream';\n\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\nexport function toByteStreamReader(\n source: BundleSource,\n bytesPerRead: number\n): ReadableStreamReader {\n if (source instanceof Uint8Array) {\n return toByteStreamReaderHelper(source, bytesPerRead);\n }\n if (source instanceof ArrayBuffer) {\n return toByteStreamReaderHelper(new Uint8Array(source), bytesPerRead);\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n throw new Error(\n 'Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream'\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 true iff the array contains the value using strong equality.\n */\nexport function includes(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value mathching the predicate\n */\nexport function some(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffArrays(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\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/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\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// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider;\n _appCheckCredentials: CredentialsProvider;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams\n );\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${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\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\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// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down.\n private _terminateTask?: Promise;\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== undefined;\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise {\n if (!this._terminateTask) {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const settings = firestore._getSettings();\n const newHostSetting = `${host}:${port}`;\n\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n\n firestore._setSettings({\n ...settings,\n host: newHostSetting,\n ssl: false\n });\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\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 } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to Typescript's `Partial`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference {\n return new CollectionReference(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\n this.firestore,\n converter,\n this._key\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-genrated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual(\n left: Query,\n right: Query\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\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 { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise = Promise.resolve();\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor() {\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred();\n return this.enqueueInternal(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal(op: () => Promise): Promise {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overriden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + getMessageOrStack(this.failure));\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver(obj: unknown): obj is PartialObserver {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as JsonObject;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\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 { PartialObserver } from '../api/observer';\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\n\n/**\n * Represents the state of bundle loading tasks.\n *\n * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will\n * be no more updates after they are reported.\n */\nexport type TaskState = 'Error' | 'Running' | 'Success';\n\n/**\n * Represents a progress update or a final state from loading bundles.\n */\nexport interface LoadBundleTaskProgress {\n /** How many documents have been loaded. */\n documentsLoaded: number;\n /** How many documents are in the bundle being loaded. */\n totalDocuments: number;\n /** How many bytes have been loaded. */\n bytesLoaded: number;\n /** How many bytes are in the bundle being loaded. */\n totalBytes: number;\n /** Current task state. */\n taskState: TaskState;\n}\n\n/**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */\nexport class LoadBundleTask implements PromiseLike {\n private _progressObserver: PartialObserver = {};\n private _taskCompletionResolver = new Deferred();\n\n private _lastProgress: LoadBundleTaskProgress = {\n taskState: 'Running',\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */\n onProgress(\n next?: (progress: LoadBundleTaskProgress) => unknown,\n error?: (err: Error) => unknown,\n complete?: () => void\n ): void {\n this._progressObserver = {\n next,\n error,\n complete\n };\n }\n\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n catch(\n onRejected: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.catch(onRejected);\n }\n\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n then(\n onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike,\n onRejected?: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n }\n\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */\n _completeWith(progress: LoadBundleTaskProgress): void {\n debugAssert(\n progress.taskState === 'Success',\n 'Task is not completed with Success.'\n );\n this._updateProgress(progress);\n if (this._progressObserver.complete) {\n this._progressObserver.complete();\n }\n\n this._taskCompletionResolver.resolve(progress);\n }\n\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */\n _failWith(error: FirestoreError): void {\n this._lastProgress.taskState = 'Error';\n\n if (this._progressObserver.next) {\n this._progressObserver.next(this._lastProgress);\n }\n\n if (this._progressObserver.error) {\n this._progressObserver.error(error);\n }\n\n this._taskCompletionResolver.reject(error);\n }\n\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */\n _updateProgress(progress: LoadBundleTaskProgress): void {\n debugAssert(\n this._lastProgress.taskState === 'Running',\n 'Cannot update progress on a completed or failed task'\n );\n\n this._lastProgress = progress;\n if (this._progressObserver.next) {\n this._progressObserver.next(progress);\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 {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { deepEqual, getDefaultEmulatorHostnameAndPort } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport {\n IndexedDbOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from '../core/component_provider';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport {\n canFallbackFromIndexedDbError,\n FirestoreClient,\n firestoreClientDisableNetwork,\n firestoreClientEnableNetwork,\n firestoreClientGetNamedQuery,\n firestoreClientLoadBundle,\n firestoreClientWaitForPendingWrites,\n setOfflineComponentProvider,\n setOnlineComponentProvider\n} from '../core/firestore_client';\nimport { makeDatabaseInfo } from '../lite-api/components';\nimport {\n Firestore as LiteFirestore,\n connectFirestoreEmulator\n} from '../lite-api/database';\nimport { Query } from '../lite-api/reference';\nimport {\n indexedDbClearPersistence,\n indexedDbStoragePrefix\n} from '../local/indexeddb_persistence';\nimport { LRU_COLLECTION_DISABLED } from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { LoadBundleTask } from './bundle';\nimport { CredentialsProvider } from './credentials';\nimport { PersistenceSettings, FirestoreSettings } from './settings';\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\n }\n}\n\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * {@link Firestore} instance.\n */\nexport const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore extends LiteFirestore {\n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore';\n\n readonly _queue: AsyncQueue = newAsyncQueue();\n readonly _persistenceKey: string;\n\n _firestoreClient: FirestoreClient | undefined;\n\n /** @hideconstructor */\n constructor(\n authCredentialsProvider: CredentialsProvider,\n appCheckCredentialsProvider: CredentialsProvider,\n databaseId: DatabaseId,\n app?: FirebaseApp\n ) {\n super(\n authCredentialsProvider,\n appCheckCredentialsProvider,\n databaseId,\n app\n );\n this._persistenceKey = app?.name || '[DEFAULT]';\n }\n\n _terminate(): Promise {\n if (!this._firestoreClient) {\n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n configureFirestore(this);\n }\n return this._firestoreClient!.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore');\n\n if (provider.isInitialized(databaseId)) {\n const existingInstance = provider.getImmediate({\n identifier: databaseId\n });\n const initialSettings = provider.getOptions(\n databaseId\n ) as FirestoreSettings;\n if (deepEqual(initialSettings, settings)) {\n return existingInstance;\n } else {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'initializeFirestore() has already been called with ' +\n 'different options. To avoid this error, call initializeFirestore() with the ' +\n 'same options as when it was originally called, or call getFirestore() to return the' +\n ' already initialized instance.'\n );\n }\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.localCache !== undefined\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes will` +\n `be deprecated. Instead, specify the cache size in the cache object`\n );\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The default {@link Firestore} instance of the default app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The default {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the default app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || DEFAULT_DATABASE_NAME;\n const db = _getProvider(app, 'firestore').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * @internal\n */\nexport function ensureFirestoreConfigured(\n firestore: Firestore\n): FirestoreClient {\n if (!firestore._firestoreClient) {\n configureFirestore(firestore);\n }\n firestore._firestoreClient!.verifyNotTerminated();\n return firestore._firestoreClient as FirestoreClient;\n}\n\nexport function configureFirestore(firestore: Firestore): void {\n const settings = firestore._freezeSettings();\n debugAssert(!!settings.host, 'FirestoreSettings.host is not set');\n debugAssert(\n !firestore._firestoreClient,\n 'configureFirestore() called multiple times'\n );\n\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore._app?.options.appId || '',\n firestore._persistenceKey,\n settings\n );\n firestore._firestoreClient = new FirestoreClient(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n firestore._queue,\n databaseInfo\n );\n if (\n settings.localCache?._offlineComponentProvider &&\n settings.localCache?._onlineComponentProvider\n ) {\n firestore._firestoreClient._uninitializedComponentsProvider = {\n _offlineKind: settings.localCache.kind,\n _offline: settings.localCache._offlineComponentProvider,\n _online: settings.localCache._onlineComponentProvider\n };\n }\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * On failure, `enableIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * Note: `enableIndexedDbPersistence()` must be called before any other functions\n * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableIndexedDbPersistence(\n firestore: Firestore,\n persistenceSettings?: PersistenceSettings\n): Promise {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new IndexedDbOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes,\n persistenceSettings?.forceOwnership\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableMultiTabIndexedDbPersistence(\n firestore: Firestore\n): Promise {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableMultiTabIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new MultiTabOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */\nfunction setPersistenceProviders(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider,\n offlineComponentProvider: OfflineComponentProvider\n): Promise {\n const persistenceResult = new Deferred();\n return client.asyncQueue\n .enqueue(async () => {\n try {\n await setOfflineComponentProvider(client, offlineComponentProvider);\n await setOnlineComponentProvider(client, onlineComponentProvider);\n persistenceResult.resolve();\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error enabling indexeddb cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n persistenceResult.reject(error);\n }\n })\n .then(() => persistenceResult.promise);\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */\nexport function clearIndexedDbPersistence(firestore: Firestore): Promise {\n if (firestore._initialized && !firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Persistence can only be cleared before a Firestore instance is ' +\n 'initialized or after it is terminated.'\n );\n }\n\n const deferred = new Deferred();\n firestore._queue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n await indexedDbClearPersistence(\n indexedDbStoragePrefix(firestore._databaseId, firestore._persistenceKey)\n );\n deferred.resolve();\n } catch (e) {\n deferred.reject(e as Error | undefined);\n }\n });\n return deferred.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */\nexport function waitForPendingWrites(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWaitForPendingWrites(client);\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */\nexport function enableNetwork(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientEnableNetwork(client);\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */\nexport function disableNetwork(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientDisableNetwork(client);\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n _removeServiceInstance(\n firestore.app,\n 'firestore',\n firestore._databaseId.database\n );\n return firestore._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise`.\n */\nexport function loadBundle(\n firestore: Firestore,\n bundleData: ReadableStream | ArrayBuffer | string\n): LoadBundleTask {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const resultTask = new LoadBundleTask();\n firestoreClientLoadBundle(\n client,\n firestore._databaseId,\n bundleData,\n resultTask\n );\n return resultTask;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */\nexport function namedQuery(\n firestore: Firestore,\n name: string\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientGetNamedQuery(client, name).then(namedQuery => {\n if (!namedQuery) {\n return null;\n }\n\n return new Query(firestore, null, namedQuery.query);\n });\n}\n\nfunction verifyNotInitialized(firestore: Firestore): void {\n if (firestore._initialized || firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and persistence can no longer be ' +\n 'enabled. You can only enable persistence before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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 { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\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 {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\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 { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | 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 { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /** Returns a JSON-serializable representation of this GeoPoint. */\n toJSON(): { latitude: number; longitude: number } {\n return { latitude: this._lat, longitude: this._long };\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\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 DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nfunction parseObject(\n obj: Dict,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\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 { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference {\n return new DocumentReference(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\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 } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\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 compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link 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\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply(\n query: Query\n ): Query {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse(\n query: Query\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse(\n query: Query\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply(\n query: Query\n ): Query {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply(\n query: Query\n ): Query {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply(\n query: Query\n ): Query {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n methodName: string,\n docOrFields: Array>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\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 { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 'ReferenceValue is not valid ' + name\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\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 {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(result.length === 1, 'Expected a single document result');\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\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 { newQueryComparator } from '../core/query';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { FieldPath } from '../lite-api/field_path';\nimport {\n DocumentData,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from '../lite-api/reference';\nimport {\n DocumentSnapshot as LiteDocumentSnapshot,\n fieldPathFromArgument,\n FirestoreDataConverter as LiteFirestoreDataConverter\n} from '../lite-api/snapshot';\nimport { UntypedFirestoreDataConverter } from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> extends LiteFirestoreDataConverter {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. To use `set()`\n * with `merge` and `mergeFields`, `toFirestore()` must be defined with\n * `PartialWithFieldValue`.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and\n * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data(options)`.\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.\n * @param options - The `SnapshotOptions` from the initial call to `data()`.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot,\n options?: SnapshotOptions\n ): AppModelType;\n}\n\n/**\n * Options that configure how data is retrieved from a `DocumentSnapshot` (for\n * example the desired behavior for server timestamps that have not yet been set\n * to their final value).\n */\nexport interface SnapshotOptions {\n /**\n * If set, controls the return value for server timestamps that have not yet\n * been set to their final value.\n *\n * By specifying 'estimate', pending server timestamps return an estimate\n * based on the local clock. This estimate will differ from the final value\n * and cause these values to change once the server result becomes available.\n *\n * By specifying 'previous', pending timestamps will be ignored and return\n * their previous value instead.\n *\n * If omitted or set to 'none', `null` will be returned by default until the\n * server value becomes available.\n */\n readonly serverTimestamps?: 'estimate' | 'previous' | 'none';\n}\n\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */\nexport class SnapshotMetadata {\n /**\n * True if the snapshot contains the result of local writes (for example\n * `set()` or `update()` calls) that have not yet been committed to the\n * backend. If your listener has opted into metadata updates (via\n * `SnapshotListenOptions`) you will receive another snapshot with\n * `hasPendingWrites` equal to false once the writes have been committed to\n * the backend.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * True if the snapshot was created from cached data rather than guaranteed\n * up-to-date server data. If your listener has opted into metadata updates\n * (via `SnapshotListenOptions`) you will receive another snapshot with\n * `fromCache` set to false once the client has received up-to-date data from\n * the backend.\n */\n readonly fromCache: boolean;\n\n /** @hideconstructor */\n constructor(hasPendingWrites: boolean, fromCache: boolean) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */\n isEqual(other: SnapshotMetadata): boolean {\n return (\n this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache\n );\n }\n}\n\n/**\n * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.\n */\nexport type DocumentChangeType = 'added' | 'removed' | 'modified';\n\n/**\n * A `DocumentChange` represents a change to the documents matching a query.\n * It contains the document affected and the type of change that occurred.\n */\nexport interface DocumentChange<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of change ('added', 'modified', or 'removed'). */\n readonly type: DocumentChangeType;\n\n /** The document affected by this change. */\n readonly doc: QueryDocumentSnapshot;\n\n /**\n * The index of the changed document in the result set immediately prior to\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects\n * have been applied). Is `-1` for 'added' events.\n */\n readonly oldIndex: number;\n\n /**\n * The index of the changed document in the result set immediately after\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`\n * objects and the current `DocumentChange` object have been applied).\n * Is -1 for 'removed' events.\n */\n readonly newIndex: number;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends LiteDocumentSnapshot {\n private readonly _firestoreImpl: Firestore;\n\n /**\n * Metadata about the `DocumentSnapshot`, including information about its\n * source and local modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /** @hideconstructor protected */\n constructor(\n readonly _firestore: Firestore,\n userDataWriter: AbstractUserDataWriter,\n key: DocumentKey,\n document: Document | null,\n metadata: SnapshotMetadata,\n converter: UntypedFirestoreDataConverter | null\n ) {\n super(_firestore, userDataWriter, key, document, converter);\n this._firestoreImpl = _firestore;\n this.metadata = metadata;\n }\n\n /**\n * Returns whether or not the data exists. True if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return super.exists();\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */\n data(options: SnapshotOptions = {}): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n this.metadata,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot, options);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value,\n options.serverTimestamps\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath, options: SnapshotOptions = {}): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(\n value,\n options.serverTimestamps\n );\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(options: SnapshotOptions = {}): AppModelType {\n return super.data(options) as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Metadata about this snapshot, concerning its source and if it has local\n * modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /**\n * The query on which you called `get` or `onSnapshot` in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n private _cachedChanges?: Array>;\n private _cachedChangesIncludeMetadataChanges?: boolean;\n\n /** @hideconstructor */\n constructor(\n readonly _firestore: Firestore,\n readonly _userDataWriter: AbstractUserDataWriter,\n query: Query,\n readonly _snapshot: ViewSnapshot\n ) {\n this.metadata = new SnapshotMetadata(\n _snapshot.hasPendingWrites,\n _snapshot.fromCache\n );\n this.query = query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n const result: Array> = [];\n this.forEach(doc => result.push(doc));\n return result;\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this._snapshot.docs.size;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._snapshot.docs.forEach(doc => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n doc.key,\n doc,\n new SnapshotMetadata(\n this._snapshot.mutatedKeys.has(doc.key),\n this._snapshot.fromCache\n ),\n this.query.converter\n )\n );\n });\n }\n\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */\n docChanges(\n options: SnapshotListenOptions = {}\n ): Array> {\n const includeMetadataChanges = !!options.includeMetadataChanges;\n\n if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'To include metadata changes with your document changes, you must ' +\n 'also pass { includeMetadataChanges:true } to onSnapshot().'\n );\n }\n\n if (\n !this._cachedChanges ||\n this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges\n ) {\n this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges);\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n }\n\n return this._cachedChanges;\n }\n}\n\n/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\nexport function changesFromSnapshot<\n AppModelType,\n DbModelType extends DocumentData\n>(\n querySnapshot: QuerySnapshot,\n includeMetadataChanges: boolean\n): Array> {\n if (querySnapshot._snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n let lastDoc: Document;\n let index = 0;\n return querySnapshot._snapshot.docChanges.map(change => {\n debugAssert(\n change.type === ChangeType.Added,\n 'Invalid event type for first snapshot'\n );\n debugAssert(\n !lastDoc ||\n newQueryComparator(querySnapshot._snapshot.query)(\n lastDoc,\n change.doc\n ) < 0,\n 'Got added events in wrong order'\n );\n const doc = new QueryDocumentSnapshot(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n lastDoc = change.doc;\n return {\n type: 'added' as DocumentChangeType,\n doc,\n oldIndex: -1,\n newIndex: index++\n };\n });\n } else {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let indexTracker = querySnapshot._snapshot.oldDocs;\n return querySnapshot._snapshot.docChanges\n .filter(\n change => includeMetadataChanges || change.type !== ChangeType.Metadata\n )\n .map(change => {\n const doc = new QueryDocumentSnapshot(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n let oldIndex = -1;\n let newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker.indexOf(change.doc.key);\n debugAssert(oldIndex >= 0, 'Index for document not found');\n indexTracker = indexTracker.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker = indexTracker.add(change.doc);\n newIndex = indexTracker.indexOf(change.doc.key);\n }\n return {\n type: resultChangeType(change.type),\n doc,\n oldIndex,\n newIndex\n };\n });\n }\n}\n\nexport function resultChangeType(type: ChangeType): DocumentChangeType {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n left._firestore === right._firestore &&\n queryEqual(left.query, right.query) &&\n left.metadata.isEqual(right.metadata) &&\n left._snapshot.isEqual(right._snapshot)\n );\n }\n\n return false;\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 } from '@firebase/util';\n\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver\n} from '../api/observer';\nimport { ListenerDataSource } from '../core/event_manager';\nimport {\n firestoreClientAddSnapshotsInSyncListener,\n firestoreClientGetDocumentFromLocalCache,\n firestoreClientGetDocumentsFromLocalCache,\n firestoreClientGetDocumentsViaSnapshotListener,\n firestoreClientGetDocumentViaSnapshotListener,\n firestoreClientListen,\n firestoreClientWrite\n} from '../core/firestore_client';\nimport { newQueryForPath, Query as InternalQuery } from '../core/query';\nimport { ViewSnapshot } from '../core/view_snapshot';\nimport { Bytes } from '../lite-api/bytes';\nimport { FieldPath } from '../lite-api/field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from '../lite-api/query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from '../lite-api/reference';\nimport { applyFirestoreDataConverter } from '../lite-api/reference_impl';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs\n} from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { DocumentSnapshot, QuerySnapshot, SnapshotMetadata } from './snapshot';\n\n/**\n * An options object that can be passed to {@link (onSnapshot:1)} and {@link\n * QuerySnapshot.docChanges} to control which types of changes to include in the\n * result set.\n */\nexport interface SnapshotListenOptions {\n /**\n * Include a change even if only the metadata of the query or of a document\n * changed. Default is false.\n */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Set the source the query listens to. Default to \"default\", which\n * listens to both cache and server.\n */\n readonly source?: ListenSource;\n}\n\n/**\n * Describe the source a query listens to.\n *\n * Set to `default` to listen to both cache and server changes. Set to `cache`\n * to listen to changes in cache only.\n */\nexport type ListenSource = 'default' | 'cache';\n\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(\n client,\n reference._key\n ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\nexport class ExpUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromCache(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(\n doc =>\n new DocumentSnapshot(\n firestore,\n userDataWriter,\n reference._key,\n doc,\n new SnapshotMetadata(\n doc !== null && doc.hasLocalMutations,\n /* fromCache= */ true\n ),\n reference.converter\n )\n );\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, {\n source: 'server'\n }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n validateHasExplicitOrderByForLimitToLast(query._query);\n return firestoreClientGetDocumentsViaSnapshotListener(\n client,\n query._query\n ).then(\n snapshot =>\n new QuerySnapshot(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromCache<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsFromLocalCache(client, query._query).then(\n snapshot =>\n new QuerySnapshot(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, {\n source: 'server'\n }).then(\n snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n}\n\n/**\n * Writes to the document referred to by this `DocumentReference`. If the\n * document does not yet exist, it will be created.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @returns A Promise resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as WithFieldValue,\n options\n );\n const dataReader = newUserDataReader(firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const mutation = parsed.toMutation(reference._key, Precondition.none());\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const dataReader = newUserDataReader(firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const mutation = parsed.toMutation(reference._key, Precondition.exists(true));\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n const firestore = cast(reference.firestore, Firestore);\n const mutations = [new DeleteMutation(reference._key, Precondition.none())];\n return executeWrite(firestore, mutations);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n const firestore = cast(reference.firestore, Firestore);\n\n const docRef = doc(reference);\n const convertedValue = applyFirestoreDataConverter(reference.converter, data);\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n reference.converter !== null,\n {}\n );\n\n const mutation = parsed.toMutation(docRef._key, Precondition.exists(false));\n return executeWrite(firestore, [mutation]).then(() => docRef);\n}\n\n/**\n * A function returned by `onSnapshot()` that removes the listener when invoked.\n */\nexport interface Unsubscribe {\n /** Removes the listener when invoked. */\n (): void;\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n reference: DocumentReference,\n observer: {\n next?: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n reference: DocumentReference,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n reference: DocumentReference,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n reference: DocumentReference,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n query: Query,\n observer: {\n next?: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n query: Query,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n query: Query,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot(\n query: Query,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\nexport function onSnapshot(\n reference:\n | Query\n | DocumentReference,\n ...args: unknown[]\n): Unsubscribe {\n reference = getModularInstance(reference);\n\n let options: SnapshotListenOptions = {\n includeMetadataChanges: false,\n source: 'default'\n };\n let currArg = 0;\n if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) {\n options = args[currArg] as SnapshotListenOptions;\n currArg++;\n }\n\n const internalOptions = {\n includeMetadataChanges: options.includeMetadataChanges,\n source: options.source as ListenerDataSource\n };\n\n if (isPartialObserver(args[currArg])) {\n const userObserver = args[currArg] as PartialObserver<\n QuerySnapshot\n >;\n args[currArg] = userObserver.next?.bind(userObserver);\n args[currArg + 1] = userObserver.error?.bind(userObserver);\n args[currArg + 2] = userObserver.complete?.bind(userObserver);\n }\n\n let observer: PartialObserver;\n let firestore: Firestore;\n let internalQuery: InternalQuery;\n\n if (reference instanceof DocumentReference) {\n firestore = cast(reference.firestore, Firestore);\n internalQuery = newQueryForPath(reference._key.path);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (\n args[currArg] as NextFn>\n )(\n convertToDocSnapshot(\n firestore,\n reference as DocumentReference,\n snapshot\n )\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n } else {\n const query = cast>(reference, Query);\n firestore = cast(query.firestore, Firestore);\n internalQuery = query._query;\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (args[currArg] as NextFn>)(\n new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n\n validateHasExplicitOrderByForLimitToLast(reference._query);\n }\n\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientListen(\n client,\n internalQuery,\n internalOptions,\n observer\n );\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use SnapshotMetadata in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The instance of Firestore for synchronizing snapshots.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n observer: {\n next?: (value: void) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use `SnapshotMetadata` in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The `Firestore` instance for synchronizing snapshots.\n * @param onSync - A callback to be called every time all snapshot listeners are\n * in sync with each other.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n onSync: () => void\n): Unsubscribe;\nexport function onSnapshotsInSync(\n firestore: Firestore,\n arg: unknown\n): Unsubscribe {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const observer = isPartialObserver(arg)\n ? (arg as PartialObserver)\n : {\n next: arg as () => void\n };\n\n return firestoreClientAddSnapshotsInSyncListener(client, observer);\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */\nexport function executeWrite(\n firestore: Firestore,\n mutations: Mutation[]\n): Promise {\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWrite(client, mutations);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */\nfunction convertToDocSnapshot(\n firestore: Firestore,\n ref: DocumentReference,\n snapshot: ViewSnapshot\n): DocumentSnapshot {\n debugAssert(\n snapshot.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n const doc = snapshot.docs.get(ref._key);\n\n const userDataWriter = new ExpUserDataWriter(firestore);\n return new DocumentSnapshot(\n firestore,\n userDataWriter,\n ref._key,\n doc,\n new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache),\n ref.converter\n );\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 { AggregateField, AggregateSpec, DocumentData, Query } from '../api';\nimport { AggregateImpl } from '../core/aggregate';\nimport { firestoreClientRunAggregateQuery } from '../core/firestore_client';\nimport { count } from '../lite-api/aggregate';\nimport { AggregateQuerySnapshot } from '../lite-api/aggregate_types';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\n\nexport {\n aggregateQuerySnapshotEqual,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../lite-api/aggregate';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCountFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregateFromServer(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregateFromServer<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return firestoreClientRunAggregateQuery(\n client,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\n/**\n * Converts the core aggregration result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new ExpUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\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 IndexedDbOfflineComponentProvider,\n LruGcMemoryOfflineComponentProvider,\n MemoryOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from '../core/component_provider';\n\n/* eslint @typescript-eslint/consistent-type-definitions: [\"error\", \"type\"] */\n/**\n * Provides an in-memory cache to the SDK. This is the default cache unless explicitly\n * configured otherwise.\n *\n * To use, create an instance using the factory function {@link memoryLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type MemoryLocalCache = {\n kind: 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n};\n\nclass MemoryLocalCacheImpl implements MemoryLocalCache {\n kind: 'memory' = 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n\n constructor(settings?: MemoryCacheSettings) {\n this._onlineComponentProvider = new OnlineComponentProvider();\n if (settings?.garbageCollector) {\n this._offlineComponentProvider =\n settings.garbageCollector._offlineComponentProvider;\n } else {\n this._offlineComponentProvider = new MemoryOfflineComponentProvider();\n }\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Provides a persistent cache backed by IndexedDb to the SDK.\n *\n * To use, create an instance using the factory function {@link persistentLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type PersistentLocalCache = {\n kind: 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProvider;\n};\n\nclass PersistentLocalCacheImpl implements PersistentLocalCache {\n kind: 'persistent' = 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProvider;\n\n constructor(settings: PersistentCacheSettings | undefined) {\n let tabManager: PersistentTabManager;\n if (settings?.tabManager) {\n settings.tabManager._initialize(settings);\n tabManager = settings.tabManager;\n } else {\n tabManager = persistentSingleTabManager(undefined);\n tabManager._initialize(settings);\n }\n this._onlineComponentProvider = tabManager._onlineComponentProvider!;\n this._offlineComponentProvider = tabManager._offlineComponentProvider!;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Union type from all supported SDK cache layer.\n */\nexport type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;\n\n/**\n * Union type from all support gabage collectors for memory local cache.\n */\nexport type MemoryGarbageCollector =\n | MemoryEagerGarbageCollector\n | MemoryLruGarbageCollector;\n\n/**\n * A garbage collector deletes documents whenever they are not part of any\n * active queries, and have no local mutations attached to them.\n *\n * This collector tries to ensure lowest memory footprints from the SDK,\n * at the risk of documents not being cached for offline queries or for\n * direct queries to the cache.\n *\n * Use factory function {@link memoryEagerGarbageCollector()} to create an\n * instance of this collector.\n */\nexport type MemoryEagerGarbageCollector = {\n kind: 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n};\n\n/**\n * A garbage collector deletes Least-Recently-Used documents in multiple\n * batches.\n *\n * This collector is configured with a target size, and will only perform\n * collection when the cached documents exceed the target size. It avoids\n * querying backend repeated for the same query or document, at the risk\n * of having a larger memory footprint.\n *\n * Use factory function {@link memoryLruGarbageCollector()} to create a\n * instance of this collector.\n */\nexport type MemoryLruGarbageCollector = {\n kind: 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n};\n\nclass MemoryEagerGabageCollectorImpl implements MemoryEagerGarbageCollector {\n kind: 'memoryEager' = 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n\n constructor() {\n this._offlineComponentProvider = new MemoryOfflineComponentProvider();\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\nclass MemoryLruGabageCollectorImpl implements MemoryLruGarbageCollector {\n kind: 'memoryLru' = 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: MemoryOfflineComponentProvider;\n\n constructor(cacheSize?: number) {\n this._offlineComponentProvider = new LruGcMemoryOfflineComponentProvider(\n cacheSize\n );\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */\nexport function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector {\n return new MemoryEagerGabageCollectorImpl();\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */\nexport function memoryLruGarbageCollector(settings?: {\n cacheSizeBytes?: number;\n}): MemoryLruGarbageCollector {\n return new MemoryLruGabageCollectorImpl(settings?.cacheSizeBytes);\n}\n\n/**\n * An settings object to configure an `MemoryLocalCache` instance.\n */\nexport type MemoryCacheSettings = {\n /**\n * The garbage collector to use, for the memory cache layer.\n * A `MemoryEagerGarbageCollector` is used when this is undefined.\n */\n garbageCollector?: MemoryGarbageCollector;\n};\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */\nexport function memoryLocalCache(\n settings?: MemoryCacheSettings\n): MemoryLocalCache {\n return new MemoryLocalCacheImpl(settings);\n}\n\n/**\n * An settings object to configure an `PersistentLocalCache` instance.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport type PersistentCacheSettings = {\n /**\n * An approximate cache size threshold for the on-disk data. If the cache\n * grows beyond this size, Firestore will start removing data that hasn't been\n * recently used. The SDK does not guarantee that the cache will stay below\n * that size, only that if the cache exceeds the given size, cleanup will be\n * attempted.\n *\n * The default value is 40 MB. The threshold must be set to at least 1 MB, and\n * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.\n */\n cacheSizeBytes?: number;\n\n /**\n * Specifies how multiple tabs/windows will be managed by the SDK.\n */\n tabManager?: PersistentTabManager;\n};\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport function persistentLocalCache(\n settings?: PersistentCacheSettings\n): PersistentLocalCache {\n return new PersistentLocalCacheImpl(settings);\n}\n\n/**\n * A tab manager supportting only one tab, no synchronization will be\n * performed across tabs.\n */\nexport type PersistentSingleTabManager = {\n kind: 'persistentSingleTab';\n /**\n * @internal\n */\n _initialize: (\n settings: Omit | undefined\n ) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProvider;\n};\n\nclass SingleTabManagerImpl implements PersistentSingleTabManager {\n kind: 'persistentSingleTab' = 'persistentSingleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProvider;\n\n constructor(private forceOwnership?: boolean) {}\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = new OnlineComponentProvider();\n this._offlineComponentProvider = new IndexedDbOfflineComponentProvider(\n this._onlineComponentProvider,\n settings?.cacheSizeBytes,\n this.forceOwnership\n );\n }\n}\n\n/**\n * A tab manager supporting multiple tabs. SDK will synchronize queries and\n * mutations done across all tabs using the SDK.\n */\nexport type PersistentMultipleTabManager = {\n kind: 'PersistentMultipleTab';\n /**\n * @internal\n */\n _initialize: (settings: Omit) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProvider;\n /**\n * @internal\n */\n\n _offlineComponentProvider?: OfflineComponentProvider;\n};\n\nclass MultiTabManagerImpl implements PersistentMultipleTabManager {\n kind: 'PersistentMultipleTab' = 'PersistentMultipleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProvider;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProvider;\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = new OnlineComponentProvider();\n this._offlineComponentProvider = new MultiTabOfflineComponentProvider(\n this._onlineComponentProvider,\n settings?.cacheSizeBytes\n );\n }\n}\n\n/**\n * A union of all available tab managers.\n */\nexport type PersistentTabManager =\n | PersistentSingleTabManager\n | PersistentMultipleTabManager;\n\n/**\n * Type to configure an `PersistentSingleTabManager` instance.\n */\nexport type PersistentSingleTabManagerSettings = {\n /**\n * Whether to force-enable persistent (IndexedDB) cache for the client. This\n * cannot be used with multi-tab synchronization and is primarily intended for\n * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause\n * other tabs using IndexedDB cache to fail.\n */\n forceOwnership?: boolean;\n};\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */\nexport function persistentSingleTabManager(\n settings: PersistentSingleTabManagerSettings | undefined\n): PersistentSingleTabManager {\n return new SingleTabManagerImpl(settings?.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */\nexport function persistentMultipleTabManager(): PersistentMultipleTabManager {\n return new MultiTabManagerImpl();\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 { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\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 { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\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 { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n TransactionOptions as TranasactionOptionsInternal,\n DEFAULT_TRANSACTION_OPTIONS,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n _transaction: InternalTransaction\n ) {\n super(_firestore, _transaction);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new ExpUserDataWriter(this._firestore);\n return super\n .get(documentRef)\n .then(\n liteDocumentSnapshot =>\n new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n liteDocumentSnapshot._document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n ref.converter\n )\n );\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const optionsWithDefaults: TranasactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientTransaction(\n client,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n optionsWithDefaults\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 } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TranasactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n `BatchGetDocumentsRequest returned unexpected document: ${doc}`\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TranasactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\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 { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', 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 { WriteBatch } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { executeWrite } from './reference_impl';\n\nexport { WriteBatch };\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n ensureFirestoreConfigured(firestore);\n return new WriteBatch(firestore, mutations =>\n executeWrite(firestore, mutations)\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 { firestoreClientSetIndexConfiguration } from '../core/firestore_client';\nimport { fieldPathFromDotSeparatedString } from '../lite-api/user_data_reader';\nimport {\n FieldIndex,\n IndexKind,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\n/**\n * A single field element in an index configuration.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexField {\n /** The field path to index. */\n readonly fieldPath: string;\n /**\n * What type of array index to create. Set to `CONTAINS` for `array-contains`\n * and `array-contains-any` indexes.\n *\n * Only one of `arrayConfig` or `order` should be set;\n */\n readonly arrayConfig?: 'CONTAINS';\n /**\n * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for\n * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.\n *\n * Only one of `arrayConfig` or `order` should be set.\n */\n readonly order?: 'ASCENDING' | 'DESCENDING';\n\n [key: string]: unknown;\n}\n\n/**\n * The SDK definition of a Firestore index.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface Index {\n /** The ID of the collection to index. */\n readonly collectionGroup: string;\n /** A list of fields to index. */\n readonly fields?: IndexField[];\n\n [key: string]: unknown;\n}\n\n/**\n * A list of Firestore indexes to speed up local query execution.\n *\n * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}\n * for a description of the format of the index definition.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexConfiguration {\n /** A list of all Firestore indexes. */\n readonly indexes?: Index[];\n\n [key: string]: unknown;\n}\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. If IndexedDb is not\n * enabled, any index configuration is ignored.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param configuration -The index definition.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n configuration: IndexConfiguration\n): Promise;\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. Invoke either\n * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`\n * before setting an index configuration. If IndexedDb is not enabled, any\n * index configuration is ignored.\n *\n * The method accepts the JSON format exported by the Firebase CLI (`firebase\n * firestore:indexes`). If the JSON format is invalid, this method throws an\n * error.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param json -The JSON format exported by the Firebase CLI.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n json: string\n): Promise;\n\nexport function setIndexConfiguration(\n firestore: Firestore,\n jsonOrConfiguration: string | IndexConfiguration\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n if (\n !client._uninitializedComponentsProvider ||\n client._uninitializedComponentsProvider?._offlineKind === 'memory'\n ) {\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n logWarn('Cannot enable indexes when persistence is disabled');\n return Promise.resolve();\n }\n const parsedIndexes = parseIndexes(jsonOrConfiguration);\n return firestoreClientSetIndexConfiguration(client, parsedIndexes);\n}\n\nexport function parseIndexes(\n jsonOrConfiguration: string | IndexConfiguration\n): FieldIndex[] {\n const indexConfiguration =\n typeof jsonOrConfiguration === 'string'\n ? (tryParseJson(jsonOrConfiguration) as IndexConfiguration)\n : jsonOrConfiguration;\n const parsedIndexes: FieldIndex[] = [];\n\n if (Array.isArray(indexConfiguration.indexes)) {\n for (const index of indexConfiguration.indexes) {\n const collectionGroup = tryGetString(index, 'collectionGroup');\n\n const segments: IndexSegment[] = [];\n if (Array.isArray(index.fields)) {\n for (const field of index.fields) {\n const fieldPathString = tryGetString(field, 'fieldPath');\n const fieldPath = fieldPathFromDotSeparatedString(\n 'setIndexConfiguration',\n fieldPathString\n );\n\n if (field.arrayConfig === 'CONTAINS') {\n segments.push(new IndexSegment(fieldPath, IndexKind.CONTAINS));\n } else if (field.order === 'ASCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.ASCENDING));\n } else if (field.order === 'DESCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.DESCENDING));\n }\n }\n }\n\n parsedIndexes.push(\n new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n collectionGroup,\n segments,\n IndexState.empty()\n )\n );\n }\n }\n return parsedIndexes;\n}\n\nfunction tryParseJson(json: string): Record {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to parse JSON: ' + (e as Error)?.message\n );\n }\n}\n\nfunction tryGetString(data: Record, property: string): string {\n if (typeof data[property] !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Missing string value for: ' + property\n );\n }\n return data[property] as string;\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 firestoreClientDeleteAllFieldIndexes,\n firestoreClientSetPersistentCacheIndexAutoCreationEnabled,\n FirestoreClient\n} from '../core/firestore_client';\nimport { cast } from '../util/input_validation';\nimport { logDebug, logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\n/**\n * A `PersistentCacheIndexManager` for configuring persistent cache indexes used\n * for local query execution.\n *\n * To use, call `getPersistentCacheIndexManager()` to get an instance.\n */\nexport class PersistentCacheIndexManager {\n /** A type string to uniquely identify instances of this class. */\n readonly type: 'PersistentCacheIndexManager' = 'PersistentCacheIndexManager';\n\n /** @hideconstructor */\n constructor(readonly _client: FirestoreClient) {}\n}\n\n/**\n * Returns the PersistentCache Index Manager used by the given `Firestore`\n * object.\n *\n * @return The `PersistentCacheIndexManager` instance, or `null` if local\n * persistent storage is not in use.\n */\nexport function getPersistentCacheIndexManager(\n firestore: Firestore\n): PersistentCacheIndexManager | null {\n firestore = cast(firestore, Firestore);\n\n const cachedInstance = persistentCacheIndexManagerByFirestore.get(firestore);\n if (cachedInstance) {\n return cachedInstance;\n }\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider?._offlineKind !== 'persistent') {\n return null;\n }\n\n const instance = new PersistentCacheIndexManager(client);\n persistentCacheIndexManagerByFirestore.set(firestore, instance);\n return instance;\n}\n\n/**\n * Enables the SDK to create persistent cache indexes automatically for local\n * query execution when the SDK believes cache indexes can help improve\n * performance.\n *\n * This feature is disabled by default.\n */\nexport function enablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, true);\n}\n\n/**\n * Stops creating persistent cache indexes automatically for local query\n * execution. The indexes which have been created by calling\n * `enablePersistentCacheIndexAutoCreation()` still take effect.\n */\nexport function disablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, false);\n}\n\n/**\n * Removes all persistent cache indexes.\n *\n * Please note this function will also deletes indexes generated by\n * `setIndexConfiguration()`, which is deprecated.\n */\nexport function deleteAllPersistentCacheIndexes(\n indexManager: PersistentCacheIndexManager\n): void {\n indexManager._client.verifyNotTerminated();\n\n const promise = firestoreClientDeleteAllFieldIndexes(indexManager._client);\n\n promise\n .then(_ => logDebug('deleting all persistent cache indexes succeeded'))\n .catch(error =>\n logWarn('deleting all persistent cache indexes failed', error)\n );\n}\n\nfunction setPersistentCacheIndexAutoCreationEnabled(\n indexManager: PersistentCacheIndexManager,\n isEnabled: boolean\n): void {\n indexManager._client.verifyNotTerminated();\n\n const promise = firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n indexManager._client,\n isEnabled\n );\n\n promise\n .then(_ =>\n logDebug(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} succeeded`\n )\n )\n .catch(error =>\n logWarn(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} failed`,\n error\n )\n );\n}\n\n/**\n * Maps `Firestore` instances to their corresponding\n * `PersistentCacheIndexManager` instances.\n *\n * Use a `WeakMap` so that the mapping will be automatically dropped when the\n * `Firestore` instance is garbage collected. This emulates a private member\n * as described in https://goo.gle/454yvug.\n */\nconst persistentCacheIndexManagerByFirestore = new WeakMap<\n Firestore,\n PersistentCacheIndexManager\n>();\n", "/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ensureFirestoreConfigured, Firestore } from '../api/database';\nimport { AggregateImpl } from '../core/aggregate';\nimport { queryToAggregateTarget, queryToTarget } from '../core/query';\nimport { AggregateSpec } from '../lite-api/aggregate_types';\nimport { Query } from '../lite-api/reference';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { toQueryTarget, toRunAggregationQueryRequest } from './serializer';\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `QueryTarget` representation of the given query. Returns `null`\n * if the Firestore client associated with the given query has not been\n * initialized or has been terminated.\n *\n * @param query - The Query to convert to proto representation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _internalQueryToProtoQueryTarget(query: Query): any {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n return toQueryTarget(serializer!, queryToTarget(query._query)).queryTarget;\n}\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns `RunAggregationQueryRequest` which contains the proto representation\n * of the given aggregation query request. Returns null if the Firestore client\n * associated with the given query has not been initialized or has been\n * terminated.\n *\n * @param query - The Query to convert to proto representation.\n * @param aggregateSpec - The set of aggregations and their aliases.\n */\nexport function _internalAggregationQueryToProtoRunAggregationQueryRequest<\n AggregateSpecType extends AggregateSpec\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n>(query: Query, aggregateSpec: AggregateSpecType): any {\n const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n\n return toRunAggregationQueryRequest(\n serializer!,\n queryToAggregateTarget(query._query),\n aggregates,\n /* skipAliasing= */ true\n ).request;\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 { Unsubscribe } from '../api/reference_impl';\n\nimport {\n setTestingHooksSpi,\n ExistenceFilterMismatchInfo,\n TestingHooksSpi\n} from './testing_hooks_spi';\n\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('instances of this class should not be created');\n }\n\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */\n static onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback);\n }\n}\n\n/**\n * The signature of callbacks registered with\n * `TestingUtils.onExistenceFilterMismatch()`.\n *\n * The return value, if any, is ignored.\n *\n * @internal\n */\nexport type ExistenceFilterMismatchCallback = (\n info: ExistenceFilterMismatchInfo\n) => unknown;\n\n/**\n * The implementation of `TestingHooksSpi`.\n */\nclass TestingHooksSpiImpl implements TestingHooksSpi {\n private readonly existenceFilterMismatchCallbacksById = new Map<\n Symbol,\n ExistenceFilterMismatchCallback\n >();\n\n private constructor() {}\n\n static get instance(): TestingHooksSpiImpl {\n if (!testingHooksSpiImplInstance) {\n testingHooksSpiImplInstance = new TestingHooksSpiImpl();\n setTestingHooksSpi(testingHooksSpiImplInstance);\n }\n return testingHooksSpiImplInstance;\n }\n\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void {\n this.existenceFilterMismatchCallbacksById.forEach(callback =>\n callback(info)\n );\n }\n\n onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n const id = Symbol();\n const callbacks = this.existenceFilterMismatchCallbacksById;\n callbacks.set(id, callback);\n return () => callbacks.delete(id);\n }\n}\n\nlet testingHooksSpiImplInstance: TestingHooksSpiImpl | null = null;\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 {\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 {\n FirebaseAppCheckTokenProvider,\n FirebaseAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { Firestore } from './api/database';\nimport { databaseIdFromApp } from './core/database_info';\n\nexport function registerFirestore(\n variant?: string,\n useFetchStreams = true\n): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'firestore',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new FirebaseAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new FirebaseAppCheckTokenProvider(\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n settings = { useFetchStreams, ...settings };\n firestoreInstance._setSettings(settings);\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n", "/**\n * Cloud Firestore\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 { Firestore } from './api/database';\nimport { registerFirestore } from './register';\n\nregisterFirestore();\n\nexport * from './api';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\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 */\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nregisterVersion(name, version, 'app');\nexport * from '@firebase/app';\n", "// Add your own firebase credentials here.\nexport default {};\n", "import { initializeApp } from 'firebase/app';\nimport config from '../config/firebase.js';\n\nconst init = function () {\n if (!config.apiKey) {\n throw Error('Firebase config is not setup.');\n }\n initializeApp(config);\n};\n\nexport {\n init\n};\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\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;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\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: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n 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]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\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; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\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);\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); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\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\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\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\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof 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\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\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/**\n * An enum of factors that may be used for multifactor authentication.\n *\n * @public\n */\nexport const FactorId = {\n /** Phone as second factor */\n PHONE: 'phone',\n TOTP: 'totp'\n} as const;\n\n/**\n * Enumeration of supported providers.\n *\n * @public\n */\nexport const ProviderId = {\n /** Facebook provider ID */\n FACEBOOK: 'facebook.com',\n /** GitHub provider ID */\n GITHUB: 'github.com',\n /** Google provider ID */\n GOOGLE: 'google.com',\n /** Password provider */\n PASSWORD: 'password',\n /** Phone provider */\n PHONE: 'phone',\n /** Twitter provider ID */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported sign-in methods.\n *\n * @public\n */\nexport const SignInMethod = {\n /** Email link sign in method */\n EMAIL_LINK: 'emailLink',\n /** Email/password sign in method */\n EMAIL_PASSWORD: 'password',\n /** Facebook sign in method */\n FACEBOOK: 'facebook.com',\n /** GitHub sign in method */\n GITHUB: 'github.com',\n /** Google sign in method */\n GOOGLE: 'google.com',\n /** Phone sign in method */\n PHONE: 'phone',\n /** Twitter sign in method */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported operation types.\n *\n * @public\n */\nexport const OperationType = {\n /** Operation involving linking an additional provider to an already signed-in user. */\n LINK: 'link',\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\n REAUTHENTICATE: 'reauthenticate',\n /** Operation involving signing in a user. */\n SIGN_IN: 'signIn'\n} as const;\n\n/**\n * An enumeration of the possible email action types.\n *\n * @public\n */\nexport const ActionCodeOperation = {\n /** The email link sign-in action. */\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n /** The password reset action. */\n PASSWORD_RESET: 'PASSWORD_RESET',\n /** The email revocation action. */\n RECOVER_EMAIL: 'RECOVER_EMAIL',\n /** The revert second factor addition email action. */\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\n /** The revert second factor addition email action. */\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n /** The email verification action. */\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n} as const;\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 { AuthErrorMap, User } from '../model/public_types';\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { AppName } from '../model/auth';\nimport { AuthCredential } from './credentials';\n\n/**\n * Enumeration of Firebase Auth error codes.\n *\n * @internal\n */\nexport const enum AuthErrorCode {\n ADMIN_ONLY_OPERATION = 'admin-restricted-operation',\n ARGUMENT_ERROR = 'argument-error',\n APP_NOT_AUTHORIZED = 'app-not-authorized',\n APP_NOT_INSTALLED = 'app-not-installed',\n CAPTCHA_CHECK_FAILED = 'captcha-check-failed',\n CODE_EXPIRED = 'code-expired',\n CORDOVA_NOT_READY = 'cordova-not-ready',\n CORS_UNSUPPORTED = 'cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE = 'credential-already-in-use',\n CREDENTIAL_MISMATCH = 'custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH = 'dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',\n EMAIL_EXISTS = 'email-already-in-use',\n EMULATOR_CONFIG_FAILED = 'emulator-config-failed',\n EXPIRED_OOB_CODE = 'expired-action-code',\n EXPIRED_POPUP_REQUEST = 'cancelled-popup-request',\n INTERNAL_ERROR = 'internal-error',\n INVALID_API_KEY = 'invalid-api-key',\n INVALID_APP_CREDENTIAL = 'invalid-app-credential',\n INVALID_APP_ID = 'invalid-app-id',\n INVALID_AUTH = 'invalid-user-token',\n INVALID_AUTH_EVENT = 'invalid-auth-event',\n INVALID_CERT_HASH = 'invalid-cert-hash',\n INVALID_CODE = 'invalid-verification-code',\n INVALID_CONTINUE_URI = 'invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION = 'invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN = 'invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN = 'invalid-dynamic-link-domain',\n INVALID_EMAIL = 'invalid-email',\n INVALID_EMULATOR_SCHEME = 'invalid-emulator-scheme',\n INVALID_CREDENTIAL = 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD = 'invalid-message-payload',\n INVALID_MFA_SESSION = 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID = 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER = 'invalid-oauth-provider',\n INVALID_OOB_CODE = 'invalid-action-code',\n INVALID_ORIGIN = 'unauthorized-domain',\n INVALID_PASSWORD = 'wrong-password',\n INVALID_PERSISTENCE = 'invalid-persistence-type',\n INVALID_PHONE_NUMBER = 'invalid-phone-number',\n INVALID_PROVIDER_ID = 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL = 'invalid-recipient-email',\n INVALID_SENDER = 'invalid-sender',\n INVALID_SESSION_INFO = 'invalid-verification-id',\n INVALID_TENANT_ID = 'invalid-tenant-id',\n LOGIN_BLOCKED = 'login-blocked',\n MFA_INFO_NOT_FOUND = 'multi-factor-info-not-found',\n MFA_REQUIRED = 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME = 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL = 'missing-app-credential',\n MISSING_AUTH_DOMAIN = 'auth-domain-config-required',\n MISSING_CODE = 'missing-verification-code',\n MISSING_CONTINUE_URI = 'missing-continue-uri',\n MISSING_IFRAME_START = 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID = 'missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE = 'missing-or-invalid-nonce',\n MISSING_MFA_INFO = 'missing-multi-factor-info',\n MISSING_MFA_SESSION = 'missing-multi-factor-session',\n MISSING_PHONE_NUMBER = 'missing-phone-number',\n MISSING_PASSWORD = 'missing-password',\n MISSING_SESSION_INFO = 'missing-verification-id',\n MODULE_DESTROYED = 'app-deleted',\n NEED_CONFIRMATION = 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED = 'network-request-failed',\n NULL_USER = 'null-user',\n NO_AUTH_EVENT = 'no-auth-event',\n NO_SUCH_PROVIDER = 'no-such-provider',\n OPERATION_NOT_ALLOWED = 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED = 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED = 'popup-blocked',\n POPUP_CLOSED_BY_USER = 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED = 'provider-already-linked',\n QUOTA_EXCEEDED = 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER = 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING = 'redirect-operation-pending',\n REJECTED_CREDENTIAL = 'rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED = 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH = 'tenant-id-mismatch',\n TIMEOUT = 'timeout',\n TOKEN_EXPIRED = 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'too-many-requests',\n UNAUTHORIZED_DOMAIN = 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR = 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE = 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION = 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL = 'unverified-email',\n USER_CANCELLED = 'user-cancelled',\n USER_DELETED = 'user-not-found',\n USER_DISABLED = 'user-disabled',\n USER_MISMATCH = 'user-mismatch',\n USER_SIGNED_OUT = 'user-signed-out',\n WEAK_PASSWORD = 'weak-password',\n WEB_STORAGE_UNSUPPORTED = 'web-storage-unsupported',\n ALREADY_INITIALIZED = 'already-initialized',\n RECAPTCHA_NOT_ENABLED = 'recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN = 'missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN = 'invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION = 'invalid-recaptcha-action',\n MISSING_CLIENT_TYPE = 'missing-client-type',\n MISSING_RECAPTCHA_VERSION = 'missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION = 'invalid-recaptcha-version',\n INVALID_REQ_TYPE = 'invalid-req-type',\n UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION = 'unsupported-password-policy-schema-version',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'password-does-not-meet-requirements'\n}\n\nfunction _debugErrorMap(): ErrorMap {\n return {\n [AuthErrorCode.ADMIN_ONLY_OPERATION]:\n 'This operation is restricted to administrators only.',\n [AuthErrorCode.ARGUMENT_ERROR]: '',\n [AuthErrorCode.APP_NOT_AUTHORIZED]:\n \"This app, identified by the domain where it's hosted, is not \" +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.',\n [AuthErrorCode.APP_NOT_INSTALLED]:\n 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.',\n [AuthErrorCode.CAPTCHA_CHECK_FAILED]:\n 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.',\n [AuthErrorCode.CODE_EXPIRED]:\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [AuthErrorCode.CORDOVA_NOT_READY]: 'Cordova framework is not ready.',\n [AuthErrorCode.CORS_UNSUPPORTED]: 'This browser is not supported.',\n [AuthErrorCode.CREDENTIAL_ALREADY_IN_USE]:\n 'This credential is already associated with a different user account.',\n [AuthErrorCode.CREDENTIAL_MISMATCH]:\n 'The custom token corresponds to a different audience.',\n [AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED]:\n 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION]:\n 'Multi-factor users must always have a verified email.',\n [AuthErrorCode.EMAIL_EXISTS]:\n 'The email address is already in use by another account.',\n [AuthErrorCode.EMULATOR_CONFIG_FAILED]:\n 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',\n [AuthErrorCode.EXPIRED_POPUP_REQUEST]:\n 'This operation has been cancelled due to another conflicting popup being opened.',\n [AuthErrorCode.INTERNAL_ERROR]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_APP_CREDENTIAL]:\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [AuthErrorCode.INVALID_APP_ID]:\n 'The mobile app identifier is not registed for the current project.',\n [AuthErrorCode.INVALID_AUTH]:\n \"This user's credential isn't valid for this project. This can happen \" +\n \"if the user's token has been tampered with, or if the user isn't for \" +\n 'the project associated with this API key.',\n [AuthErrorCode.INVALID_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_CODE]:\n 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure to use the ' +\n 'verification code provided by the user.',\n [AuthErrorCode.INVALID_CONTINUE_URI]:\n 'The continue URL provided in the request is invalid.',\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]:\n 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.',\n [AuthErrorCode.INVALID_CUSTOM_TOKEN]:\n 'The custom token format is incorrect. Please check the documentation.',\n [AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN]:\n 'The provided dynamic link domain is not configured or authorized for the current project.',\n [AuthErrorCode.INVALID_EMAIL]: 'The email address is badly formatted.',\n [AuthErrorCode.INVALID_EMULATOR_SCHEME]:\n 'Emulator URL must start with a valid scheme (http:// or https://).',\n [AuthErrorCode.INVALID_API_KEY]:\n 'Your API key is invalid, please check you have copied it correctly.',\n [AuthErrorCode.INVALID_CERT_HASH]:\n 'The SHA-1 certificate hash provided is invalid.',\n [AuthErrorCode.INVALID_CREDENTIAL]:\n 'The supplied auth credential is incorrect, malformed or has expired.',\n [AuthErrorCode.INVALID_MESSAGE_PAYLOAD]:\n 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_MFA_SESSION]:\n 'The request does not contain a valid proof of first factor successful sign-in.',\n [AuthErrorCode.INVALID_OAUTH_PROVIDER]:\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [AuthErrorCode.INVALID_OAUTH_CLIENT_ID]:\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [AuthErrorCode.INVALID_ORIGIN]:\n 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.',\n [AuthErrorCode.INVALID_OOB_CODE]:\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [AuthErrorCode.INVALID_PASSWORD]:\n 'The password is invalid or the user does not have a password.',\n [AuthErrorCode.INVALID_PERSISTENCE]:\n 'The specified persistence type is invalid. It can only be local, session or none.',\n [AuthErrorCode.INVALID_PHONE_NUMBER]:\n 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].',\n [AuthErrorCode.INVALID_PROVIDER_ID]:\n 'The specified provider ID is invalid.',\n [AuthErrorCode.INVALID_RECIPIENT_EMAIL]:\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [AuthErrorCode.INVALID_SENDER]:\n 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_SESSION_INFO]:\n 'The verification ID used to create the phone auth credential is invalid.',\n [AuthErrorCode.INVALID_TENANT_ID]:\n \"The Auth instance's tenant ID is invalid.\",\n [AuthErrorCode.LOGIN_BLOCKED]:\n 'Login blocked by user-provided method: {$originalMessage}',\n [AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME]:\n 'An Android Package Name must be provided if the Android App is required to be installed.',\n [AuthErrorCode.MISSING_AUTH_DOMAIN]:\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [AuthErrorCode.MISSING_APP_CREDENTIAL]:\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [AuthErrorCode.MISSING_CODE]:\n 'The phone auth credential was created with an empty SMS verification code.',\n [AuthErrorCode.MISSING_CONTINUE_URI]:\n 'A continue URL must be provided in the request.',\n [AuthErrorCode.MISSING_IFRAME_START]: 'An internal AuthError has occurred.',\n [AuthErrorCode.MISSING_IOS_BUNDLE_ID]:\n 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [AuthErrorCode.MISSING_OR_INVALID_NONCE]:\n 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.',\n [AuthErrorCode.MISSING_PASSWORD]: 'A non-empty password must be provided',\n [AuthErrorCode.MISSING_MFA_INFO]:\n 'No second factor identifier is provided.',\n [AuthErrorCode.MISSING_MFA_SESSION]:\n 'The request is missing proof of first factor successful sign-in.',\n [AuthErrorCode.MISSING_PHONE_NUMBER]:\n 'To send verification codes, provide a phone number for the recipient.',\n [AuthErrorCode.MISSING_SESSION_INFO]:\n 'The phone auth credential was created with an empty verification ID.',\n [AuthErrorCode.MODULE_DESTROYED]:\n 'This instance of FirebaseApp has been deleted.',\n [AuthErrorCode.MFA_INFO_NOT_FOUND]:\n 'The user does not have a second factor matching the identifier provided.',\n [AuthErrorCode.MFA_REQUIRED]:\n 'Proof of ownership of a second factor is required to complete sign-in.',\n [AuthErrorCode.NEED_CONFIRMATION]:\n 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.',\n [AuthErrorCode.NETWORK_REQUEST_FAILED]:\n 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [AuthErrorCode.NO_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.NO_SUCH_PROVIDER]:\n 'User was not linked to an account with the given provider.',\n [AuthErrorCode.NULL_USER]:\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [AuthErrorCode.OPERATION_NOT_ALLOWED]:\n 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.',\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]:\n 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.',\n [AuthErrorCode.POPUP_BLOCKED]:\n 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [AuthErrorCode.POPUP_CLOSED_BY_USER]:\n 'The popup has been closed by the user before finalizing the operation.',\n [AuthErrorCode.PROVIDER_ALREADY_LINKED]:\n 'User can only be linked to one identity for the given provider.',\n [AuthErrorCode.QUOTA_EXCEEDED]:\n \"The project's quota for this operation has been exceeded.\",\n [AuthErrorCode.REDIRECT_CANCELLED_BY_USER]:\n 'The redirect operation has been cancelled by the user before finalizing.',\n [AuthErrorCode.REDIRECT_OPERATION_PENDING]:\n 'A redirect sign-in operation is already pending.',\n [AuthErrorCode.REJECTED_CREDENTIAL]:\n 'The request contains malformed or mismatching credentials.',\n [AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED]:\n 'The second factor is already enrolled on this account.',\n [AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED]:\n 'The maximum allowed number of second factors on a user has been exceeded.',\n [AuthErrorCode.TENANT_ID_MISMATCH]:\n \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [AuthErrorCode.TIMEOUT]: 'The operation has timed out.',\n [AuthErrorCode.TOKEN_EXPIRED]:\n \"The user's credential is no longer valid. The user must sign in again.\",\n [AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER]:\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [AuthErrorCode.UNAUTHORIZED_DOMAIN]:\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\n [AuthErrorCode.UNSUPPORTED_FIRST_FACTOR]:\n 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\n [AuthErrorCode.UNSUPPORTED_PERSISTENCE]:\n 'The current environment does not support the specified persistence type.',\n [AuthErrorCode.UNSUPPORTED_TENANT_OPERATION]:\n 'This operation is not supported in a multi-tenant context.',\n [AuthErrorCode.UNVERIFIED_EMAIL]:\n 'The operation requires a verified email.',\n [AuthErrorCode.USER_CANCELLED]:\n 'The user did not grant your application the permissions it requested.',\n [AuthErrorCode.USER_DELETED]:\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [AuthErrorCode.USER_DISABLED]:\n 'The user account has been disabled by an administrator.',\n [AuthErrorCode.USER_MISMATCH]:\n 'The supplied credentials do not correspond to the previously signed in user.',\n [AuthErrorCode.USER_SIGNED_OUT]: '',\n [AuthErrorCode.WEAK_PASSWORD]:\n 'The password must be 6 characters long or more.',\n [AuthErrorCode.WEB_STORAGE_UNSUPPORTED]:\n 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [AuthErrorCode.ALREADY_INITIALIZED]:\n 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.',\n [AuthErrorCode.MISSING_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is invalid when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_ACTION]:\n 'The reCAPTCHA action is invalid when sending request to the backend.',\n [AuthErrorCode.RECAPTCHA_NOT_ENABLED]:\n 'reCAPTCHA Enterprise integration is not enabled for this project.',\n [AuthErrorCode.MISSING_CLIENT_TYPE]:\n 'The reCAPTCHA client type is missing when sending request to the backend.',\n [AuthErrorCode.MISSING_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_REQ_TYPE]: 'Invalid request parameters.',\n [AuthErrorCode.INVALID_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is invalid when sending request to the backend.',\n [AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION]:\n 'The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.',\n [AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n 'The password does not meet the requirements.'\n };\n}\n\nexport interface ErrorMapRetriever extends AuthErrorMap {\n (): ErrorMap;\n}\n\nfunction _prodErrorMap(): ErrorMap {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n } as ErrorMap;\n}\n\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const debugErrorMap: AuthErrorMap = _debugErrorMap;\n\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const prodErrorMap: AuthErrorMap = _prodErrorMap;\n\nexport interface NamedErrorParams {\n appName: AppName;\n credential?: AuthCredential;\n email?: string;\n phoneNumber?: string;\n tenantId?: string;\n user?: User;\n _serverResponse?: object;\n}\n\n/**\n * @internal\n */\ntype GenericAuthErrorParams = {\n [key in Exclude<\n AuthErrorCode,\n | AuthErrorCode.ARGUMENT_ERROR\n | AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n | AuthErrorCode.INTERNAL_ERROR\n | AuthErrorCode.MFA_REQUIRED\n | AuthErrorCode.NO_AUTH_EVENT\n | AuthErrorCode.OPERATION_NOT_SUPPORTED\n >]: {\n appName?: AppName;\n email?: string;\n phoneNumber?: string;\n message?: string;\n };\n};\n\n/**\n * @internal\n */\nexport interface AuthErrorParams extends GenericAuthErrorParams {\n [AuthErrorCode.ARGUMENT_ERROR]: { appName?: AppName };\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]: { appName?: AppName };\n [AuthErrorCode.INTERNAL_ERROR]: { appName?: AppName };\n [AuthErrorCode.LOGIN_BLOCKED]: {\n appName?: AppName;\n originalMessage?: string;\n };\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]: { appName?: AppName };\n [AuthErrorCode.NO_AUTH_EVENT]: { appName?: AppName };\n [AuthErrorCode.MFA_REQUIRED]: {\n appName: AppName;\n _serverResponse: IdTokenMfaResponse;\n };\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]: {\n appName: AppName;\n missingPlugin?: string;\n };\n}\n\nexport const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory<\n AuthErrorCode,\n AuthErrorParams\n>('auth', 'Firebase', _prodErrorMap());\n\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nexport const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_LOGIN_CREDENTIALS: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized',\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\n} as const;\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 { Logger, LogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '@firebase/app';\n\nexport { LogLevel };\n\nconst logClient = new Logger('@firebase/auth');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function _getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\nexport function _setLogLevel(newLevel: LogLevel): void {\n logClient.logLevel = newLevel;\n}\n\nexport function _logDebug(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n logClient.debug(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logWarn(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logError(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\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 { Auth } from '../../model/public_types';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../../model/auth';\nimport {\n _DEFAULT_AUTH_ERROR_FACTORY,\n AuthErrorCode,\n AuthErrorParams,\n prodErrorMap,\n ErrorMapRetriever\n} from '../errors';\nimport { _logError } from './log';\n\ntype AuthErrorListParams = K extends keyof AuthErrorParams\n ? [AuthErrorParams[K]]\n : [];\ntype LessAppName = Omit;\n\n/**\n * Unconditionally fails, throwing a developer facing INTERNAL_ERROR\n *\n * @example\n * ```javascript\n * fail(auth, AuthErrorCode.MFA_REQUIRED); // Error: the MFA_REQUIRED error needs more params than appName\n * fail(auth, AuthErrorCode.MFA_REQUIRED, {serverResponse}); // Compiles\n * fail(AuthErrorCode.INTERNAL_ERROR); // Compiles; internal error does not need appName\n * fail(AuthErrorCode.USER_DELETED); // Error: USER_DELETED requires app name\n * fail(auth, AuthErrorCode.USER_DELETED); // Compiles; USER_DELETED _only_ needs app name\n * ```\n *\n * @param appName App name for tagging the error\n * @throws FirebaseError\n */\nexport function _fail(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): never;\nexport function _fail(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): never;\nexport function _fail(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): never {\n throw createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _createError(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): FirebaseError;\nexport function _createError(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): FirebaseError;\nexport function _createError(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n return createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _errorWithCustomMessage(\n auth: Auth,\n code: AuthErrorCode,\n message: string\n): FirebaseError {\n const errorMap = {\n ...(prodErrorMap as ErrorMapRetriever)(),\n [code]: message\n };\n const factory = new ErrorFactory(\n 'auth',\n 'Firebase',\n errorMap\n );\n return factory.create(code, {\n appName: auth.name\n });\n}\n\nexport function _serverAppCurrentUserOperationNotSupportedError(\n auth: Auth\n): FirebaseError {\n return _errorWithCustomMessage(\n auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED,\n 'Operations that alter the current user are not supported in conjunction with FirebaseServerApp'\n );\n}\n\nexport function _assertInstanceOf(\n auth: Auth,\n object: object,\n instance: unknown\n): void {\n const constructorInstance = instance as { new (...args: unknown[]): unknown };\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, AuthErrorCode.ARGUMENT_ERROR);\n }\n\n throw _errorWithCustomMessage(\n auth,\n AuthErrorCode.ARGUMENT_ERROR,\n `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`\n );\n }\n}\n\nfunction createErrorInternal(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n if (typeof authOrCode !== 'string') {\n const code = rest[0] as K;\n const fullParams = [...rest.slice(1)] as AuthErrorListParams;\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n\n return (authOrCode as AuthInternal)._errorFactory.create(\n code,\n ...fullParams\n );\n }\n\n return _DEFAULT_AUTH_ERROR_FACTORY.create(\n authOrCode,\n ...(rest as AuthErrorListParams)\n );\n}\n\nexport function _assert(\n assertion: unknown,\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): asserts assertion;\nexport function _assert(\n assertion: unknown,\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): asserts assertion;\nexport function _assert(\n assertion: unknown,\n authOrCode: Auth | K,\n ...rest: unknown[]\n): asserts assertion {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n\n// We really do want to accept literally any function type here\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype TypeExpectation = Function | string | MapType;\n\ninterface MapType extends Record {}\n\nclass Optional {\n constructor(readonly type: TypeExpectation) {}\n}\n\nexport function opt(type: TypeExpectation): Optional {\n return new Optional(type);\n}\n\n/**\n * Asserts the runtime types of arguments. The 'expected' field can be one of\n * a class, a string (representing a \"typeof\" call), or a record map of name\n * to type. Furthermore, the opt() function can be used to mark a field as\n * optional. For example:\n *\n * function foo(auth: Auth, profile: {displayName?: string}, update = false) {\n * assertTypes(arguments, [AuthImpl, {displayName: opt('string')}, opt('boolean')]);\n * }\n *\n * opt() can be used for any type:\n * function foo(auth?: Auth) {\n * assertTypes(arguments, [opt(AuthImpl)]);\n * }\n *\n * The string types can be or'd together, and you can use \"null\" as well (note\n * that typeof null === 'object'; this is an edge case). For example:\n *\n * function foo(profile: {displayName?: string | null}) {\n * assertTypes(arguments, [{displayName: opt('string|null')}]);\n * }\n *\n * @param args\n * @param expected\n */\nexport function assertTypes(\n args: Omit,\n ...expected: Array\n): void {\n if (args.length > expected.length) {\n _fail(AuthErrorCode.ARGUMENT_ERROR, {});\n }\n\n for (let i = 0; i < expected.length; i++) {\n let expect = expected[i];\n const arg = args[i];\n\n if (expect instanceof Optional) {\n // If the arg is undefined, then it matches \"optional\" and we can move to\n // the next arg\n if (typeof arg === 'undefined') {\n continue;\n }\n expect = expect.type;\n }\n\n if (typeof expect === 'string') {\n // Handle the edge case for null because typeof null === 'object'\n if (expect.includes('null') && arg === null) {\n continue;\n }\n\n const required = expect.split('|');\n _assert(required.includes(typeof arg), AuthErrorCode.ARGUMENT_ERROR, {});\n } else if (typeof expect === 'object') {\n // Recursively check record arguments\n const record = arg as Record;\n const map = expect as MapType;\n const keys = Object.keys(expect);\n\n assertTypes(\n keys.map(k => record[k]),\n ...keys.map(k => map[k])\n );\n } else {\n _assert(arg instanceof expect, AuthErrorCode.ARGUMENT_ERROR, {});\n }\n }\n}\n\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nexport function debugFail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n\n // NOTE: We don't use FirebaseError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * @param assertion\n * @param message\n */\nexport function debugAssert(\n assertion: unknown,\n message: string\n): asserts assertion {\n if (!assertion) {\n debugFail(message);\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\nexport function _getCurrentUrl(): string {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\n\nexport function _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\nexport function _getCurrentScheme(): string | null {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\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 { isBrowserExtension } from '@firebase/util';\nimport { _isHttpOrHttps } from './location';\n\n/**\n * Determine whether the browser is working online\n */\nexport function _isOnline(): boolean {\n if (\n typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in navigator &&\n typeof navigator.onLine === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)\n ) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\n\nexport function _getUserLanguage(): string | null {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage: NavigatorLanguage = navigator;\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language ||\n // Couldn't determine language.\n null\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 { isMobileCordova, isReactNative } from '@firebase/util';\nimport { _isOnline } from './navigator';\nimport { debugAssert } from './assert';\n\nexport const enum DelayMin {\n OFFLINE = 5000\n}\n\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n */\nexport class Delay {\n // The default value for the offline delay timeout in ms.\n\n private readonly isMobile: boolean;\n constructor(\n private readonly shortDelay: number,\n private readonly longDelay: number\n ) {\n // Internal error when improperly initialized.\n debugAssert(\n longDelay > shortDelay,\n 'Short delay should be less than long delay!'\n );\n this.isMobile = isMobileCordova() || isReactNative();\n }\n\n get(): number {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(DelayMin.OFFLINE, this.shortDelay);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile ? this.longDelay : this.shortDelay;\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 { ConfigInternal } from '../../model/auth';\nimport { debugAssert } from './assert';\n\nexport function _emulatorUrl(config: ConfigInternal, path?: string): string {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n\n if (!path) {\n return url;\n }\n\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\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 { debugFail } from './assert';\n\nexport class FetchProvider {\n private static fetchImpl: typeof fetch | null;\n private static headersImpl: typeof Headers | null;\n private static responseImpl: typeof Response | null;\n\n static initialize(\n fetchImpl: typeof fetch,\n headersImpl?: typeof Headers,\n responseImpl?: typeof Response\n ): void {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n\n static fetch(): typeof fetch {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\n return globalThis.fetch;\n }\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n debugFail(\n 'Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static headers(): typeof Headers {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\n return globalThis.Headers;\n }\n if (typeof Headers !== 'undefined') {\n return Headers;\n }\n debugFail(\n 'Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static response(): typeof Response {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\n return globalThis.Response;\n }\n if (typeof Response !== 'undefined') {\n return Response;\n }\n debugFail(\n 'Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\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 { AuthErrorCode } from '../core/errors';\n\n/**\n * Errors that can be returned by the backend\n */\nexport const enum ServerError {\n ADMIN_ONLY_OPERATION = 'ADMIN_ONLY_OPERATION',\n BLOCKING_FUNCTION_ERROR_RESPONSE = 'BLOCKING_FUNCTION_ERROR_RESPONSE',\n CAPTCHA_CHECK_FAILED = 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED = 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH = 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED = 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS = 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND = 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE = 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED = 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL = 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID = 'INVALID_APP_ID',\n INVALID_CERT_HASH = 'INVALID_CERT_HASH',\n INVALID_CODE = 'INVALID_CODE',\n INVALID_CONTINUE_URI = 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN = 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN = 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL = 'INVALID_EMAIL',\n INVALID_ID_TOKEN = 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE = 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER = 'INVALID_IDENTIFIER',\n INVALID_LOGIN_CREDENTIALS = 'INVALID_LOGIN_CREDENTIALS',\n INVALID_MESSAGE_PAYLOAD = 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL = 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID = 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE = 'INVALID_OOB_CODE',\n INVALID_PASSWORD = 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN = 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER = 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID = 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL = 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER = 'INVALID_SENDER',\n INVALID_SESSION_INFO = 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF = 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID = 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND = 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME = 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL = 'MISSING_APP_CREDENTIAL',\n MISSING_CODE = 'MISSING_CODE',\n MISSING_CONTINUE_URI = 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN = 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID = 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID = 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL = 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE = 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE = 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD = 'MISSING_PASSWORD',\n MISSING_REQ_TYPE = 'MISSING_REQ_TYPE',\n MISSING_PHONE_NUMBER = 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO = 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT = 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL = 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS = 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH = 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR = 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION = 'UNSUPPORTED_TENANT_OPERATION',\n UNAUTHORIZED_DOMAIN = 'UNAUTHORIZED_DOMAIN',\n UNVERIFIED_EMAIL = 'UNVERIFIED_EMAIL',\n USER_CANCELLED = 'USER_CANCELLED',\n USER_DISABLED = 'USER_DISABLED',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n RECAPTCHA_NOT_ENABLED = 'RECAPTCHA_NOT_ENABLED',\n MISSING_RECAPTCHA_TOKEN = 'MISSING_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_TOKEN = 'INVALID_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_ACTION = 'INVALID_RECAPTCHA_ACTION',\n MISSING_CLIENT_TYPE = 'MISSING_CLIENT_TYPE',\n MISSING_RECAPTCHA_VERSION = 'MISSING_RECAPTCHA_VERSION',\n INVALID_RECAPTCHA_VERSION = 'INVALID_RECAPTCHA_VERSION',\n INVALID_REQ_TYPE = 'INVALID_REQ_TYPE',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'PASSWORD_DOES_NOT_MEET_REQUIREMENTS'\n}\n\n/**\n * API Response in the event of an error\n */\nexport interface JsonError {\n error: {\n code: number;\n message: string;\n errors?: [\n {\n message: ServerError;\n domain: string;\n reason: string;\n }\n ];\n };\n}\n\n/**\n * Type definition for a map from server errors to developer visible errors\n */\nexport declare type ServerErrorMap = {\n readonly [K in ApiError]: AuthErrorCode;\n};\n\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nexport const SERVER_ERROR_MAP: Partial> = {\n // Custom token errors.\n [ServerError.CREDENTIAL_MISMATCH]: AuthErrorCode.CREDENTIAL_MISMATCH,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CUSTOM_TOKEN]: AuthErrorCode.INTERNAL_ERROR,\n\n // Create Auth URI errors.\n [ServerError.INVALID_IDENTIFIER]: AuthErrorCode.INVALID_EMAIL,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CONTINUE_URI]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign in with email and password errors (some apply to sign up too).\n [ServerError.INVALID_PASSWORD]: AuthErrorCode.INVALID_PASSWORD,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_PASSWORD]: AuthErrorCode.MISSING_PASSWORD,\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\n // invalid.\n [ServerError.INVALID_LOGIN_CREDENTIALS]: AuthErrorCode.INVALID_CREDENTIAL,\n\n // Sign up with email and password errors.\n [ServerError.EMAIL_EXISTS]: AuthErrorCode.EMAIL_EXISTS,\n [ServerError.PASSWORD_LOGIN_DISABLED]: AuthErrorCode.OPERATION_NOT_ALLOWED,\n\n // Verify assertion for sign in with credential errors:\n [ServerError.INVALID_IDP_RESPONSE]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.INVALID_PENDING_TOKEN]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.FEDERATED_USER_ID_ALREADY_LINKED]:\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_REQ_TYPE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Send Password reset email errors:\n [ServerError.EMAIL_NOT_FOUND]: AuthErrorCode.USER_DELETED,\n [ServerError.RESET_PASSWORD_EXCEED_LIMIT]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n [ServerError.EXPIRED_OOB_CODE]: AuthErrorCode.EXPIRED_OOB_CODE,\n [ServerError.INVALID_OOB_CODE]: AuthErrorCode.INVALID_OOB_CODE,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_OOB_CODE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Operations that require ID token in request:\n [ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,\n [ServerError.INVALID_ID_TOKEN]: AuthErrorCode.INVALID_AUTH,\n [ServerError.TOKEN_EXPIRED]: AuthErrorCode.TOKEN_EXPIRED,\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.TOKEN_EXPIRED,\n\n // Other errors.\n [ServerError.TOO_MANY_ATTEMPTS_TRY_LATER]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n [ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS,\n\n // Phone Auth related errors.\n [ServerError.INVALID_CODE]: AuthErrorCode.INVALID_CODE,\n [ServerError.INVALID_SESSION_INFO]: AuthErrorCode.INVALID_SESSION_INFO,\n [ServerError.INVALID_TEMPORARY_PROOF]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.MISSING_SESSION_INFO]: AuthErrorCode.MISSING_SESSION_INFO,\n [ServerError.SESSION_EXPIRED]: AuthErrorCode.CODE_EXPIRED,\n\n // Other action code errors when additional settings passed.\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n [ServerError.MISSING_ANDROID_PACKAGE_NAME]:\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME,\n [ServerError.UNAUTHORIZED_DOMAIN]: AuthErrorCode.UNAUTHORIZED_DOMAIN,\n\n // getProjectConfig errors when clientId is passed.\n [ServerError.INVALID_OAUTH_CLIENT_ID]: AuthErrorCode.INVALID_OAUTH_CLIENT_ID,\n\n // User actions (sign-up or deletion) disabled errors.\n [ServerError.ADMIN_ONLY_OPERATION]: AuthErrorCode.ADMIN_ONLY_OPERATION,\n\n // Multi factor related errors.\n [ServerError.INVALID_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.INVALID_MFA_SESSION,\n [ServerError.MFA_ENROLLMENT_NOT_FOUND]: AuthErrorCode.MFA_INFO_NOT_FOUND,\n [ServerError.MISSING_MFA_ENROLLMENT_ID]: AuthErrorCode.MISSING_MFA_INFO,\n [ServerError.MISSING_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.MISSING_MFA_SESSION,\n [ServerError.SECOND_FACTOR_EXISTS]:\n AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED,\n [ServerError.SECOND_FACTOR_LIMIT_EXCEEDED]:\n AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED,\n\n // Blocking functions related errors.\n [ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Recaptcha related errors.\n [ServerError.RECAPTCHA_NOT_ENABLED]: AuthErrorCode.RECAPTCHA_NOT_ENABLED,\n [ServerError.MISSING_RECAPTCHA_TOKEN]: AuthErrorCode.MISSING_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_TOKEN]: AuthErrorCode.INVALID_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_ACTION]:\n AuthErrorCode.INVALID_RECAPTCHA_ACTION,\n [ServerError.MISSING_CLIENT_TYPE]: AuthErrorCode.MISSING_CLIENT_TYPE,\n [ServerError.MISSING_RECAPTCHA_VERSION]:\n AuthErrorCode.MISSING_RECAPTCHA_VERSION,\n [ServerError.INVALID_RECAPTCHA_VERSION]:\n AuthErrorCode.INVALID_RECAPTCHA_VERSION,\n [ServerError.INVALID_REQ_TYPE]: AuthErrorCode.INVALID_REQ_TYPE\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 { FirebaseError, querystring } from '@firebase/util';\n\nimport { AuthErrorCode, NamedErrorParams } from '../core/errors';\nimport {\n _createError,\n _errorWithCustomMessage,\n _fail\n} from '../core/util/assert';\nimport { Delay } from '../core/util/delay';\nimport { _emulatorUrl } from '../core/util/emulator';\nimport { FetchProvider } from '../core/util/fetch_provider';\nimport { Auth } from '../model/public_types';\nimport { AuthInternal, ConfigInternal } from '../model/auth';\nimport { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';\nimport { IdTokenMfaResponse } from './authentication/mfa';\nimport { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';\n\nexport const enum HttpMethod {\n POST = 'POST',\n GET = 'GET'\n}\n\nexport const enum HttpHeader {\n CONTENT_TYPE = 'Content-Type',\n X_FIREBASE_LOCALE = 'X-Firebase-Locale',\n X_CLIENT_VERSION = 'X-Client-Version',\n X_FIREBASE_GMPID = 'X-Firebase-gmpid',\n X_FIREBASE_CLIENT = 'X-Firebase-Client',\n X_FIREBASE_APP_CHECK = 'X-Firebase-AppCheck'\n}\n\nexport const enum Endpoint {\n CREATE_AUTH_URI = '/v1/accounts:createAuthUri',\n DELETE_ACCOUNT = '/v1/accounts:delete',\n RESET_PASSWORD = '/v1/accounts:resetPassword',\n SIGN_UP = '/v1/accounts:signUp',\n SIGN_IN_WITH_CUSTOM_TOKEN = '/v1/accounts:signInWithCustomToken',\n SIGN_IN_WITH_EMAIL_LINK = '/v1/accounts:signInWithEmailLink',\n SIGN_IN_WITH_IDP = '/v1/accounts:signInWithIdp',\n SIGN_IN_WITH_PASSWORD = '/v1/accounts:signInWithPassword',\n SIGN_IN_WITH_PHONE_NUMBER = '/v1/accounts:signInWithPhoneNumber',\n SEND_VERIFICATION_CODE = '/v1/accounts:sendVerificationCode',\n SEND_OOB_CODE = '/v1/accounts:sendOobCode',\n SET_ACCOUNT_INFO = '/v1/accounts:update',\n GET_ACCOUNT_INFO = '/v1/accounts:lookup',\n GET_RECAPTCHA_PARAM = '/v1/recaptchaParams',\n START_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:start',\n FINALIZE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',\n START_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',\n FINALIZE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',\n WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',\n GET_PROJECT_CONFIG = '/v1/projects',\n GET_RECAPTCHA_CONFIG = '/v2/recaptchaConfig',\n GET_PASSWORD_POLICY = '/v2/passwordPolicy',\n TOKEN = '/v1/token',\n REVOKE_TOKEN = '/v2/accounts:revokeToken'\n}\n\nexport const enum RecaptchaClientType {\n WEB = 'CLIENT_TYPE_WEB',\n ANDROID = 'CLIENT_TYPE_ANDROID',\n IOS = 'CLIENT_TYPE_IOS'\n}\n\nexport const enum RecaptchaVersion {\n ENTERPRISE = 'RECAPTCHA_ENTERPRISE'\n}\n\nexport const enum RecaptchaActionName {\n SIGN_IN_WITH_PASSWORD = 'signInWithPassword',\n GET_OOB_CODE = 'getOobCode',\n SIGN_UP_PASSWORD = 'signUpPassword'\n}\n\nexport const enum EnforcementState {\n ENFORCE = 'ENFORCE',\n AUDIT = 'AUDIT',\n OFF = 'OFF',\n ENFORCEMENT_STATE_UNSPECIFIED = 'ENFORCEMENT_STATE_UNSPECIFIED'\n}\n\n// Providers that have reCAPTCHA Enterprise support.\nexport const enum RecaptchaProvider {\n EMAIL_PASSWORD_PROVIDER = 'EMAIL_PASSWORD_PROVIDER'\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);\n\nexport function _addTidIfNecessary(\n auth: Auth,\n request: T\n): T {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\n\nexport async function _performApiRequest(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial> = {}\n): Promise {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === HttpMethod.GET) {\n params = request;\n } else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n\n const query = querystring({\n key: auth.config.apiKey,\n ...params\n }).slice(1);\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/json';\n\n if (auth.languageCode) {\n headers[HttpHeader.X_FIREBASE_LOCALE] = auth.languageCode;\n }\n\n return FetchProvider.fetch()(\n _getFinalTarget(auth, auth.config.apiHost, path, query),\n {\n method,\n headers,\n referrerPolicy: 'no-referrer',\n ...body\n }\n );\n });\n}\n\nexport async function _performFetchWithErrorHandling(\n auth: Auth,\n customErrorMap: Partial>,\n fetchFn: () => Promise\n): Promise {\n (auth as AuthInternal)._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout(auth);\n const response: Response = await Promise.race>([\n fetchFn(),\n networkTimeout.promise\n ]);\n\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, json);\n }\n\n if (response.ok && !('errorMessage' in json)) {\n return json;\n } else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n throw _makeTaggedError(\n auth,\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n json\n );\n } else if (serverErrorCode === ServerError.EMAIL_EXISTS) {\n throw _makeTaggedError(auth, AuthErrorCode.EMAIL_EXISTS, json);\n } else if (serverErrorCode === ServerError.USER_DISABLED) {\n throw _makeTaggedError(auth, AuthErrorCode.USER_DISABLED, json);\n }\n const authError =\n errorMap[serverErrorCode as ServerError] ||\n (serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-') as unknown as AuthErrorCode);\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n } else {\n _fail(auth, authError);\n }\n }\n } catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n // Changing this to a different error code will log user out when there is a network error\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\n _fail(auth, AuthErrorCode.NETWORK_REQUEST_FAILED, { 'message': String(e) });\n }\n}\n\nexport async function _performSignInRequest(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial> = {}\n): Promise {\n const serverResponse = (await _performApiRequest(\n auth,\n method,\n path,\n request,\n customErrorMap\n )) as V;\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, AuthErrorCode.MFA_REQUIRED, {\n _serverResponse: serverResponse\n });\n }\n\n return serverResponse;\n}\n\nexport function _getFinalTarget(\n auth: Auth,\n host: string,\n path: string,\n query: string\n): string {\n const base = `${host}${path}?${query}`;\n\n if (!(auth as AuthInternal).config.emulator) {\n return `${auth.config.apiScheme}://${base}`;\n }\n\n return _emulatorUrl(auth.config as ConfigInternal, base);\n}\n\nexport function _parseEnforcementState(\n enforcementStateStr: string\n): EnforcementState {\n switch (enforcementStateStr) {\n case 'ENFORCE':\n return EnforcementState.ENFORCE;\n case 'AUDIT':\n return EnforcementState.AUDIT;\n case 'OFF':\n return EnforcementState.OFF;\n default:\n return EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED;\n }\n}\n\nclass NetworkTimeout {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timer: any | null = null;\n readonly promise = new Promise((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(\n _createError(this.auth, AuthErrorCode.NETWORK_REQUEST_FAILED)\n );\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n\n clearNetworkTimeout(): void {\n clearTimeout(this.timer);\n }\n\n constructor(private readonly auth: Auth) {}\n}\n\ninterface PotentialResponse extends IdTokenResponse {\n email?: string;\n phoneNumber?: string;\n}\n\nexport function _makeTaggedError(\n auth: Auth,\n code: AuthErrorCode,\n response: PotentialResponse\n): FirebaseError {\n const errorParams: NamedErrorParams = {\n appName: auth.name\n };\n\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n\n const error = _createError(auth, code, errorParams);\n\n // We know customData is defined on error because errorParams is defined\n (error.customData! as TaggedWithTokenResponse)._tokenResponse = response;\n return error;\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 { RecaptchaParameters } from '../../model/public_types';\nimport {\n GetRecaptchaConfigResponse,\n RecaptchaEnforcementProviderState\n} from '../../api/authentication/recaptcha';\nimport { EnforcementState, _parseEnforcementState } from '../../api/index';\n\n// reCAPTCHA v2 interface\nexport interface Recaptcha {\n render: (container: HTMLElement, parameters: RecaptchaParameters) => number;\n getResponse: (id: number) => string;\n execute: (id: number) => unknown;\n reset: (id: number) => unknown;\n}\n\nexport function isV2(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is Recaptcha {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as Recaptcha).getResponse !== undefined\n );\n}\n\n// reCAPTCHA Enterprise & v3 shared interface\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\n// reCAPTCHA Enterprise interface\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n}\n\nexport function isEnterprise(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is GreCAPTCHATopLevel {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as GreCAPTCHATopLevel).enterprise !== undefined\n );\n}\n\n// TODO(chuanr): Replace this with the AuthWindow after resolving the dependency issue in Node.js env.\ndeclare global {\n interface Window {\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n }\n}\n\nexport class RecaptchaConfig {\n /**\n * The reCAPTCHA site key.\n */\n siteKey: string = '';\n\n /**\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\n */\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[] = [];\n\n constructor(response: GetRecaptchaConfigResponse) {\n if (response.recaptchaKey === undefined) {\n throw new Error('recaptchaKey undefined');\n }\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\n this.siteKey = response.recaptchaKey.split('/')[3];\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\n }\n\n /**\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\n *\n * @param providerStr - The provider whose enforcement state is to be returned.\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\n */\n getProviderEnforcementState(providerStr: string): EnforcementState | null {\n if (\n !this.recaptchaEnforcementState ||\n this.recaptchaEnforcementState.length === 0\n ) {\n return null;\n }\n\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\n if (\n recaptchaEnforcementState.provider &&\n recaptchaEnforcementState.provider === providerStr\n ) {\n return _parseEnforcementState(\n recaptchaEnforcementState.enforcementState\n );\n }\n }\n return null;\n }\n\n /**\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\n *\n * @param providerStr - The provider whose enablement state is to be returned.\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\n */\n isProviderEnabled(providerStr: string): boolean {\n return (\n this.getProviderEnforcementState(providerStr) ===\n EnforcementState.ENFORCE ||\n this.getProviderEnforcementState(providerStr) === EnforcementState.AUDIT\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 {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _performApiRequest,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\ninterface GetRecaptchaParamResponse {\n recaptchaSiteKey?: string;\n}\n\nexport async function getRecaptchaParams(auth: Auth): Promise {\n return (\n (\n await _performApiRequest(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_PARAM\n )\n ).recaptchaSiteKey || ''\n );\n}\n\n// The following functions are for reCAPTCHA enterprise integration.\ninterface GetRecaptchaConfigRequest {\n tenantId?: string;\n clientType?: RecaptchaClientType;\n version?: RecaptchaVersion;\n}\n\nexport interface RecaptchaEnforcementProviderState {\n provider: string;\n enforcementState: string;\n}\n\nexport interface GetRecaptchaConfigResponse {\n recaptchaKey: string;\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[];\n}\n\nexport async function getRecaptchaConfig(\n auth: Auth,\n request: GetRecaptchaConfigRequest\n): Promise {\n return _performApiRequest<\n GetRecaptchaConfigRequest,\n GetRecaptchaConfigResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_CONFIG,\n _addTidIfNecessary(auth, request)\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 { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { MfaEnrollment } from './mfa';\nimport { Auth } from '../../model/public_types';\n\nexport interface DeleteAccountRequest {\n idToken: string;\n}\n\nexport async function deleteAccount(\n auth: Auth,\n request: DeleteAccountRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.DELETE_ACCOUNT,\n request\n );\n}\n\nexport interface ProviderUserInfo {\n providerId: string;\n rawId?: string;\n email?: string;\n displayName?: string;\n photoUrl?: string;\n phoneNumber?: string;\n}\n\nexport interface DeleteLinkedAccountsRequest {\n idToken: string;\n deleteProvider: string[];\n}\n\nexport interface DeleteLinkedAccountsResponse {\n providerUserInfo: ProviderUserInfo[];\n}\n\nexport async function deleteLinkedAccounts(\n auth: Auth,\n request: DeleteLinkedAccountsRequest\n): Promise {\n return _performApiRequest<\n DeleteLinkedAccountsRequest,\n DeleteLinkedAccountsResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface APIUserInfo {\n localId?: string;\n displayName?: string;\n photoUrl?: string;\n email?: string;\n emailVerified?: boolean;\n phoneNumber?: string;\n lastLoginAt?: number;\n createdAt?: number;\n tenantId?: string;\n passwordHash?: string;\n providerUserInfo?: ProviderUserInfo[];\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface GetAccountInfoRequest {\n idToken: string;\n}\n\nexport interface GetAccountInfoResponse {\n users: APIUserInfo[];\n}\n\nexport async function getAccountInfo(\n auth: Auth,\n request: GetAccountInfoRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.GET_ACCOUNT_INFO,\n request\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\nexport function utcTimestampToDateString(\n utcTimestamp?: string | number\n): string | undefined {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\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 { IdTokenResult, ParsedToken, User } from '../../model/public_types';\nimport { base64Decode, getModularInstance } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { _logError } from '../util/log';\nimport { utcTimestampToDateString } from '../util/time';\nimport { AuthErrorCode } from '../errors';\n\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport function getIdToken(user: User, forceRefresh = false): Promise {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getIdTokenResult(\n user: User,\n forceRefresh = false\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n\n _assert(\n claims && claims.exp && claims.auth_time && claims.iat,\n userInternal.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const firebase =\n typeof claims.firebase === 'object' ? claims.firebase : undefined;\n\n const signInProvider: string | undefined = firebase?.['sign_in_provider'];\n\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.auth_time)\n )!,\n issuedAtTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.iat)\n )!,\n expirationTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.exp)\n )!,\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\n\nfunction secondsStringToMilliseconds(seconds: string): number {\n return Number(seconds) * 1000;\n}\n\nexport function _parseToken(token: string): ParsedToken | null {\n const [algorithm, payload, signature] = token.split('.');\n if (\n algorithm === undefined ||\n payload === undefined ||\n signature === undefined\n ) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n } catch (e) {\n _logError(\n 'Caught error parsing JWT payload as JSON',\n (e as Error)?.toString()\n );\n return null;\n }\n}\n\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nexport function _tokenExpiresIn(token: string): number {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.exp !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.iat !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\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 { FirebaseError } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\nexport async function _logoutIfInvalidated(\n user: UserInternal,\n promise: Promise,\n bypassAuthState = false\n): Promise {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n } catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n\n throw e;\n }\n}\n\nfunction isUserInvalidated({ code }: FirebaseError): boolean {\n return (\n code === `auth/${AuthErrorCode.USER_DISABLED}` ||\n code === `auth/${AuthErrorCode.TOKEN_EXPIRED}`\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 { FirebaseError } from '@firebase/util';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\n// Refresh the token five minutes before expiration\nexport const enum Duration {\n OFFSET = 5 * 1000 * 60,\n RETRY_BACKOFF_MIN = 30 * 1000,\n RETRY_BACKOFF_MAX = 16 * 60 * 1000\n}\n\nexport class ProactiveRefresh {\n private isRunning = false;\n\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timerId: any | null = null;\n private errorBackoff = Duration.RETRY_BACKOFF_MIN;\n\n constructor(private readonly user: UserInternal) {}\n\n _start(): void {\n if (this.isRunning) {\n return;\n }\n\n this.isRunning = true;\n this.schedule();\n }\n\n _stop(): void {\n if (!this.isRunning) {\n return;\n }\n\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n\n private getInterval(wasError: boolean): number {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(\n this.errorBackoff * 2,\n Duration.RETRY_BACKOFF_MAX\n );\n return interval;\n } else {\n // Reset the error backoff\n this.errorBackoff = Duration.RETRY_BACKOFF_MIN;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - Duration.OFFSET;\n\n return Math.max(0, interval);\n }\n }\n\n private schedule(wasError = false): void {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n\n private async iteration(): Promise {\n try {\n await this.user.getIdToken(true);\n } catch (e) {\n // Only retry on network errors\n if (\n (e as FirebaseError)?.code ===\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n this.schedule(/* wasError */ true);\n }\n\n return;\n }\n this.schedule();\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 { UserMetadata as UserMetadataType } from '../../model/public_types';\n\nimport { utcTimestampToDateString } from '../util/time';\n\nexport class UserMetadata implements UserMetadataType {\n creationTime?: string;\n lastSignInTime?: string;\n\n constructor(\n private createdAt?: string | number,\n private lastLoginAt?: string | number\n ) {\n this._initializeTime();\n }\n\n private _initializeTime(): void {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n\n _copy(metadata: UserMetadata): void {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n\n toJSON(): object {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\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\nimport { User, UserInfo } from '../../model/public_types';\n\nimport {\n getAccountInfo,\n ProviderUserInfo\n} from '../../api/account_management/account';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserMetadata } from './user_metadata';\nimport { getModularInstance } from '@firebase/util';\n\nexport async function _reloadWithoutSaving(user: UserInternal): Promise {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(\n user,\n getAccountInfo(auth, { idToken })\n );\n\n _assert(response?.users.length, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const coreAccount = response.users[0];\n\n user._notifyReloadListener(coreAccount);\n\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const providerData = mergeProviderData(user.providerData, newProviderData);\n\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous =\n !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n\n const updates: Partial = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n\n Object.assign(user, updates);\n}\n\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function reload(user: User): Promise {\n const userInternal: UserInternal = getModularInstance(user) as UserInternal;\n await _reloadWithoutSaving(userInternal);\n\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\n\nfunction mergeProviderData(\n original: UserInfo[],\n newData: UserInfo[]\n): UserInfo[] {\n const deduped = original.filter(\n o => !newData.some(n => n.providerId === o.providerId)\n );\n return [...deduped, ...newData];\n}\n\nexport function extractProviderData(providers: ProviderUserInfo[]): UserInfo[] {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\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/* eslint-disable camelcase */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n _getFinalTarget,\n _performFetchWithErrorHandling,\n _performApiRequest,\n _addTidIfNecessary,\n HttpMethod,\n HttpHeader,\n Endpoint\n} from '../index';\nimport { FetchProvider } from '../../core/util/fetch_provider';\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\n\nexport const enum TokenType {\n REFRESH_TOKEN = 'REFRESH_TOKEN',\n ACCESS_TOKEN = 'ACCESS_TOKEN'\n}\n\n/** The server responses with snake_case; we convert to camelCase */\ninterface RequestStsTokenServerResponse {\n access_token: string;\n expires_in: string;\n refresh_token: string;\n}\n\nexport interface RequestStsTokenResponse {\n accessToken: string;\n expiresIn: string;\n refreshToken: string;\n}\n\nexport interface RevokeTokenRequest {\n providerId: string;\n tokenType: TokenType;\n token: string;\n idToken: string;\n tenantId?: string;\n}\n\nexport interface RevokeTokenResponse {}\n\nexport async function requestStsToken(\n auth: Auth,\n refreshToken: string\n): Promise {\n const response =\n await _performFetchWithErrorHandling(\n auth,\n {},\n async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = _getFinalTarget(\n auth,\n tokenApiHost,\n Endpoint.TOKEN,\n `key=${apiKey}`\n );\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/x-www-form-urlencoded';\n\n return FetchProvider.fetch()(url, {\n method: HttpMethod.POST,\n headers,\n body\n });\n }\n );\n\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\n\nexport async function revokeToken(\n auth: Auth,\n request: RevokeTokenRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.REVOKE_TOKEN,\n _addTidIfNecessary(auth, request)\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 { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { requestStsToken } from '../../api/authentication/token';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert, debugFail } from '../util/assert';\nimport { _tokenExpiresIn } from './id_token_result';\n\n/**\n * The number of milliseconds before the official expiration time of a token\n * to refresh that token, to provide a buffer for RPCs to complete.\n */\nexport const enum Buffer {\n TOKEN_REFRESH = 30_000\n}\n\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport class StsTokenManager {\n refreshToken: string | null = null;\n accessToken: string | null = null;\n expirationTime: number | null = null;\n\n get isExpired(): boolean {\n return (\n !this.expirationTime ||\n Date.now() > this.expirationTime - Buffer.TOKEN_REFRESH\n );\n }\n\n updateFromServerResponse(\n response: IdTokenResponse | FinalizeMfaResponse\n ): void {\n _assert(response.idToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(\n typeof response.idToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof response.refreshToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const expiresIn =\n 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(\n response.idToken,\n response.refreshToken,\n expiresIn\n );\n }\n\n updateFromIdToken(idToken: string): void {\n _assert(idToken.length !== 0, AuthErrorCode.INTERNAL_ERROR);\n const expiresIn = _tokenExpiresIn(idToken);\n this.updateTokensAndExpiration(idToken, null, expiresIn);\n }\n\n async getToken(\n auth: AuthInternal,\n forceRefresh = false\n ): Promise {\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n\n _assert(this.refreshToken, auth, AuthErrorCode.TOKEN_EXPIRED);\n\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken!);\n return this.accessToken;\n }\n\n return null;\n }\n\n clearRefreshToken(): void {\n this.refreshToken = null;\n }\n\n private async refresh(auth: AuthInternal, oldToken: string): Promise {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(\n auth,\n oldToken\n );\n this.updateTokensAndExpiration(\n accessToken,\n refreshToken,\n Number(expiresIn)\n );\n }\n\n private updateTokensAndExpiration(\n accessToken: string,\n refreshToken: string | null,\n expiresInSec: number\n ): void {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n\n static fromJSON(appName: string, object: PersistedBlob): StsTokenManager {\n const { refreshToken, accessToken, expirationTime } = object;\n\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(\n typeof expirationTime === 'number',\n AuthErrorCode.INTERNAL_ERROR,\n {\n appName\n }\n );\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n\n toJSON(): object {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n\n _assign(stsTokenManager: StsTokenManager): void {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n\n _clone(): StsTokenManager {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n\n _performRefresh(): never {\n return debugFail('not implemented');\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 { IdTokenResult, UserInfo } from '../../model/public_types';\nimport { NextFn } from '@firebase/util';\nimport {\n APIUserInfo,\n GetAccountInfoResponse,\n deleteAccount\n} from '../../api/account_management/account';\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport {\n MutableUserInfo,\n UserInternal,\n UserParameters\n} from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport {\n _assert,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../util/assert';\nimport { getIdTokenResult } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { ProactiveRefresh } from './proactive_refresh';\nimport { extractProviderData, _reloadWithoutSaving, reload } from './reload';\nimport { StsTokenManager } from './token_manager';\nimport { UserMetadata } from './user_metadata';\nimport { ProviderId } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\nfunction assertStringOrUndefined(\n assertion: unknown,\n appName: string\n): asserts assertion is string | undefined {\n _assert(\n typeof assertion === 'string' || typeof assertion === 'undefined',\n AuthErrorCode.INTERNAL_ERROR,\n { appName }\n );\n}\n\nexport class UserImpl implements UserInternal {\n // For the user object, provider is always Firebase.\n readonly providerId = ProviderId.FIREBASE;\n stsTokenManager: StsTokenManager;\n // Last known accessToken so we know when it changes\n private accessToken: string | null;\n\n uid: string;\n auth: AuthInternal;\n emailVerified: boolean;\n isAnonymous: boolean;\n tenantId: string | null;\n readonly metadata: UserMetadata;\n providerData: MutableUserInfo[];\n\n // Optional fields from UserInfo\n displayName: string | null;\n email: string | null;\n phoneNumber: string | null;\n photoURL: string | null;\n\n _redirectEventId?: string;\n private readonly proactiveRefresh = new ProactiveRefresh(this);\n\n constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) {\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(\n opt.createdAt || undefined,\n opt.lastLoginAt || undefined\n );\n }\n\n async getIdToken(forceRefresh?: boolean): Promise {\n const accessToken = await _logoutIfInvalidated(\n this,\n this.stsTokenManager.getToken(this.auth, forceRefresh)\n );\n _assert(accessToken, this.auth, AuthErrorCode.INTERNAL_ERROR);\n\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n\n return accessToken;\n }\n\n getIdTokenResult(forceRefresh?: boolean): Promise {\n return getIdTokenResult(this, forceRefresh);\n }\n\n reload(): Promise {\n return reload(this);\n }\n\n private reloadUserInfo: APIUserInfo | null = null;\n private reloadListener: NextFn | null = null;\n\n _assign(user: UserInternal): void {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n\n _clone(auth: AuthInternal): UserInternal {\n const newUser = new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n newUser.metadata._copy(this.metadata);\n return newUser;\n }\n\n _onReload(callback: NextFn): void {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n\n _notifyReloadListener(userInfo: APIUserInfo): void {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n } else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n\n _startProactiveRefresh(): void {\n this.proactiveRefresh._start();\n }\n\n _stopProactiveRefresh(): void {\n this.proactiveRefresh._stop();\n }\n\n async _updateTokensIfNecessary(\n response: IdTokenResponse | FinalizeMfaResponse,\n reload = false\n ): Promise {\n let tokensRefreshed = false;\n if (\n response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken\n ) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n\n async delete(): Promise {\n if (_isFirebaseServerApp(this.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(this.auth)\n );\n }\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n\n return this.auth.signOut();\n }\n\n toJSON(): PersistedBlob {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n\n get refreshToken(): string {\n return this.stsTokenManager.refreshToken || '';\n }\n\n static _fromJSON(auth: AuthInternal, object: PersistedBlob): UserInternal {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const {\n uid,\n emailVerified,\n isAnonymous,\n providerData,\n stsTokenManager: plainObjectTokenManager\n } = object;\n\n _assert(uid && plainObjectTokenManager, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const stsTokenManager = StsTokenManager.fromJSON(\n this.name,\n plainObjectTokenManager as PersistedBlob\n );\n\n _assert(typeof uid === 'string', auth, AuthErrorCode.INTERNAL_ERROR);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(\n typeof emailVerified === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof isAnonymous === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromGetAccountInfoResponse(\n auth: AuthInternal,\n response: GetAccountInfoResponse,\n idToken: string\n ): Promise {\n const coreAccount = response.users[0];\n _assert(coreAccount.localId !== undefined, AuthErrorCode.INTERNAL_ERROR);\n\n const providerData: UserInfo[] =\n coreAccount.providerUserInfo !== undefined\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const isAnonymous =\n !(coreAccount.email && coreAccount.passwordHash) && !providerData?.length;\n\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromIdToken(idToken);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: coreAccount.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // update the user with data from the GetAccountInfo response.\n const updates: Partial = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(\n coreAccount.createdAt,\n coreAccount.lastLoginAt\n ),\n isAnonymous:\n !(coreAccount.email && coreAccount.passwordHash) &&\n !providerData?.length\n };\n\n Object.assign(user, updates);\n return user;\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 { debugAssert } from './assert';\n\n/**\n * Our API has a lot of one-off constants that are used to do things.\n * Unfortunately we can't export these as classes instantiated directly since\n * the constructor may side effect and therefore can't be proven to be safely\n * culled. Instead, we export these classes themselves as a lowerCamelCase\n * constant, and instantiate them under the hood.\n */\nexport interface SingletonInstantiator {\n new (): T;\n}\n\nconst instanceCache: Map = new Map();\n\nexport function _getInstance(cls: unknown): T {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls) as T | undefined;\n\n if (instance) {\n debugAssert(\n instance instanceof cls,\n 'Instance stored in cache mismatched with class'\n );\n return instance;\n }\n\n instance = new (cls as SingletonInstantiator)();\n instanceCache.set(cls, instance);\n return instance;\n}\n\nexport function _clearInstanceMap(): void {\n instanceCache.clear();\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 { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../persistence';\n\nexport class InMemoryPersistence implements PersistenceInternal {\n static type: 'NONE' = 'NONE';\n readonly type = PersistenceType.NONE;\n storage: Record = {};\n\n async _isAvailable(): Promise {\n return true;\n }\n\n async _set(key: string, value: PersistenceValue): Promise {\n this.storage[key] = value;\n }\n\n async _get(key: string): Promise {\n const value = this.storage[key];\n return value === undefined ? null : (value as T);\n }\n\n async _remove(key: string): Promise {\n delete this.storage[key];\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nexport const inMemoryPersistence: Persistence = InMemoryPersistence;\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 { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { PersistedBlob, PersistenceInternal } from '../persistence';\nimport { UserImpl } from '../user/user_impl';\nimport { _getInstance } from '../util/instantiator';\nimport { inMemoryPersistence } from './in_memory';\n\nexport const enum KeyName {\n AUTH_USER = 'authUser',\n AUTH_EVENT = 'authEvent',\n REDIRECT_USER = 'redirectUser',\n PERSISTENCE_USER = 'persistence'\n}\nexport const enum Namespace {\n PERSISTENCE = 'firebase'\n}\n\nexport function _persistenceKeyName(\n key: string,\n apiKey: ApiKey,\n appName: AppName\n): string {\n return `${Namespace.PERSISTENCE}:${key}:${apiKey}:${appName}`;\n}\n\nexport class PersistenceUserManager {\n private readonly fullUserKey: string;\n private readonly fullPersistenceKey: string;\n private readonly boundEventHandler: () => void;\n\n private constructor(\n public persistence: PersistenceInternal,\n private readonly auth: AuthInternal,\n private readonly userKey: string\n ) {\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\n KeyName.PERSISTENCE_USER,\n config.apiKey,\n name\n );\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n\n setCurrentUser(user: UserInternal): Promise {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n\n async getCurrentUser(): Promise {\n const blob = await this.persistence._get(this.fullUserKey);\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\n }\n\n removeCurrentUser(): Promise {\n return this.persistence._remove(this.fullUserKey);\n }\n\n savePersistenceForRedirect(): Promise {\n return this.persistence._set(\n this.fullPersistenceKey,\n this.persistence.type\n );\n }\n\n async setPersistence(newPersistence: PersistenceInternal): Promise {\n if (this.persistence === newPersistence) {\n return;\n }\n\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n\n this.persistence = newPersistence;\n\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n\n delete(): void {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n\n static async create(\n auth: AuthInternal,\n persistenceHierarchy: PersistenceInternal[],\n userKey = KeyName.AUTH_USER\n ): Promise {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(\n _getInstance(inMemoryPersistence),\n auth,\n userKey\n );\n }\n\n // Eliminate any persistences that are not available\n const availablePersistences = (\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n return undefined;\n })\n )\n ).filter(persistence => persistence) as PersistenceInternal[];\n\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence =\n availablePersistences[0] ||\n _getInstance(inMemoryPersistence);\n\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate: UserInternal | null = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get(key);\n if (blob) {\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n } catch {}\n }\n\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(\n p => p._shouldAllowMigration\n );\n\n // If the persistence does _not_ allow migration, just finish off here\n if (\n !selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length\n ) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n } catch {}\n }\n })\n );\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\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 { isIE, getUA } from '@firebase/util';\n\ninterface NavigatorStandalone extends Navigator {\n standalone?: unknown;\n}\n\ninterface Document {\n documentMode?: number;\n}\n\n/**\n * Enums for Browser name.\n */\nexport const enum BrowserName {\n ANDROID = 'Android',\n BLACKBERRY = 'Blackberry',\n EDGE = 'Edge',\n FIREFOX = 'Firefox',\n IE = 'IE',\n IEMOBILE = 'IEMobile',\n OPERA = 'Opera',\n OTHER = 'Other',\n CHROME = 'Chrome',\n SAFARI = 'Safari',\n SILK = 'Silk',\n WEBOS = 'Webos'\n}\n\n/**\n * Determine the browser for the purposes of reporting usage to the API\n */\nexport function _getBrowserName(userAgent: string): BrowserName | string {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return BrowserName.OPERA;\n } else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return BrowserName.IEMOBILE;\n } else if (ua.includes('msie') || ua.includes('trident/')) {\n return BrowserName.IE;\n } else if (ua.includes('edge/')) {\n return BrowserName.EDGE;\n } else if (_isFirefox(ua)) {\n return BrowserName.FIREFOX;\n } else if (ua.includes('silk/')) {\n return BrowserName.SILK;\n } else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return BrowserName.BLACKBERRY;\n } else if (_isWebOS(ua)) {\n // WebOS default browser.\n return BrowserName.WEBOS;\n } else if (_isSafari(ua)) {\n return BrowserName.SAFARI;\n } else if (\n (ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')\n ) {\n return BrowserName.CHROME;\n } else if (_isAndroid(ua)) {\n // Android stock browser.\n return BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return BrowserName.OTHER;\n}\n\nexport function _isFirefox(ua = getUA()): boolean {\n return /firefox\\//i.test(ua);\n}\n\nexport function _isSafari(userAgent = getUA()): boolean {\n const ua = userAgent.toLowerCase();\n return (\n ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android')\n );\n}\n\nexport function _isChromeIOS(ua = getUA()): boolean {\n return /crios\\//i.test(ua);\n}\n\nexport function _isIEMobile(ua = getUA()): boolean {\n return /iemobile/i.test(ua);\n}\n\nexport function _isAndroid(ua = getUA()): boolean {\n return /android/i.test(ua);\n}\n\nexport function _isBlackBerry(ua = getUA()): boolean {\n return /blackberry/i.test(ua);\n}\n\nexport function _isWebOS(ua = getUA()): boolean {\n return /webos/i.test(ua);\n}\n\nexport function _isIOS(ua = getUA()): boolean {\n return (\n /iphone|ipad|ipod/i.test(ua) ||\n (/macintosh/i.test(ua) && /mobile/i.test(ua))\n );\n}\n\nexport function _isIOS7Or8(ua = getUA()): boolean {\n return (\n /(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua)\n );\n}\n\nexport function _isIOSStandalone(ua = getUA()): boolean {\n return _isIOS(ua) && !!(window.navigator as NavigatorStandalone)?.standalone;\n}\n\nexport function _isIE10(): boolean {\n return isIE() && (document as Document).documentMode === 10;\n}\n\nexport function _isMobileBrowser(ua: string = getUA()): boolean {\n // TODO: implement getBrowserName equivalent for OS.\n return (\n _isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua)\n );\n}\n\nexport function _isIframe(): boolean {\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(window && window !== window.top);\n } catch (e) {\n return false;\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 { SDK_VERSION } from '@firebase/app';\nimport { _getBrowserName } from './browser';\nimport { getUA } from '@firebase/util';\n\nexport const enum ClientImplementation {\n CORE = 'JsCore'\n}\n\n/**\n * @internal\n */\nexport const enum ClientPlatform {\n BROWSER = 'Browser',\n NODE = 'Node',\n REACT_NATIVE = 'ReactNative',\n CORDOVA = 'Cordova',\n WORKER = 'Worker',\n WEB_EXTENSION = 'WebExtension'\n}\n\n/*\n * Determine the SDK version string\n */\nexport function _getClientVersion(\n clientPlatform: ClientPlatform,\n frameworks: readonly string[] = []\n): string {\n let reportedPlatform: string;\n switch (clientPlatform) {\n case ClientPlatform.BROWSER:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case ClientPlatform.WORKER:\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${ClientImplementation.CORE}/${SDK_VERSION}/${reportedFrameworks}`;\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 { AuthInternal } from '../../model/auth';\nimport { Unsubscribe, User } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\n\ninterface MiddlewareEntry {\n (user: User | null): Promise;\n onAbort?: () => void;\n}\n\nexport class AuthMiddlewareQueue {\n private readonly queue: MiddlewareEntry[] = [];\n\n constructor(private readonly auth: AuthInternal) {}\n\n pushCallback(\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n ): Unsubscribe {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback: MiddlewareEntry = (\n user: User | null\n ): Promise =>\n new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n } catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n\n async runMiddleware(nextUser: User | null): Promise {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n\n const onAbortStack: Array<() => void> = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n } catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n } catch (_) {\n /* swallow error */\n }\n }\n\n throw this.auth._errorFactory.create(AuthErrorCode.LOGIN_BLOCKED, {\n originalMessage: (e as Error)?.message\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\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\n/**\n * Request object for fetching the password policy.\n */\nexport interface GetPasswordPolicyRequest {\n tenantId?: string;\n}\n\n/**\n * Response object for fetching the password policy.\n */\nexport interface GetPasswordPolicyResponse {\n customStrengthOptions: {\n minPasswordLength?: number;\n maxPasswordLength?: number;\n containsLowercaseCharacter?: boolean;\n containsUppercaseCharacter?: boolean;\n containsNumericCharacter?: boolean;\n containsNonAlphanumericCharacter?: boolean;\n };\n allowedNonAlphanumericCharacters?: string[];\n enforcementState: string;\n forceUpgradeOnSignin?: boolean;\n schemaVersion: number;\n}\n\n/**\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\n *\n * @param auth Auth object.\n * @param request Password policy request.\n * @returns Password policy response.\n */\nexport async function _getPasswordPolicy(\n auth: Auth,\n request: GetPasswordPolicyRequest = {}\n): Promise {\n return _performApiRequest<\n GetPasswordPolicyRequest,\n GetPasswordPolicyResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PASSWORD_POLICY,\n _addTidIfNecessary(auth, request)\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\nimport { GetPasswordPolicyResponse } from '../../api/password_policy/get_password_policy';\nimport {\n PasswordPolicyCustomStrengthOptions,\n PasswordPolicyInternal,\n PasswordValidationStatusInternal\n} from '../../model/password_policy';\nimport { PasswordValidationStatus } from '../../model/public_types';\n\n// Minimum min password length enforced by the backend, even if no minimum length is set.\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\n\n/**\n * Stores password policy requirements and provides password validation against the policy.\n *\n * @internal\n */\nexport class PasswordPolicyImpl implements PasswordPolicyInternal {\n readonly customStrengthOptions: PasswordPolicyCustomStrengthOptions;\n readonly allowedNonAlphanumericCharacters: string;\n readonly enforcementState: string;\n readonly forceUpgradeOnSignin: boolean;\n readonly schemaVersion: number;\n\n constructor(response: GetPasswordPolicyResponse) {\n // Only include custom strength options defined in the response.\n const responseOptions = response.customStrengthOptions;\n this.customStrengthOptions = {};\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\n this.customStrengthOptions.minPasswordLength =\n responseOptions.minPasswordLength ?? MINIMUM_MIN_PASSWORD_LENGTH;\n if (responseOptions.maxPasswordLength) {\n this.customStrengthOptions.maxPasswordLength =\n responseOptions.maxPasswordLength;\n }\n if (responseOptions.containsLowercaseCharacter !== undefined) {\n this.customStrengthOptions.containsLowercaseLetter =\n responseOptions.containsLowercaseCharacter;\n }\n if (responseOptions.containsUppercaseCharacter !== undefined) {\n this.customStrengthOptions.containsUppercaseLetter =\n responseOptions.containsUppercaseCharacter;\n }\n if (responseOptions.containsNumericCharacter !== undefined) {\n this.customStrengthOptions.containsNumericCharacter =\n responseOptions.containsNumericCharacter;\n }\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\n this.customStrengthOptions.containsNonAlphanumericCharacter =\n responseOptions.containsNonAlphanumericCharacter;\n }\n\n this.enforcementState = response.enforcementState;\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\n this.enforcementState = 'OFF';\n }\n\n // Use an empty string if no non-alphanumeric characters are specified in the response.\n this.allowedNonAlphanumericCharacters =\n response.allowedNonAlphanumericCharacters?.join('') ?? '';\n\n this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ?? false;\n this.schemaVersion = response.schemaVersion;\n }\n\n validatePassword(password: string): PasswordValidationStatus {\n const status: PasswordValidationStatusInternal = {\n isValid: true,\n passwordPolicy: this\n };\n\n // Check the password length and character options.\n this.validatePasswordLengthOptions(password, status);\n this.validatePasswordCharacterOptions(password, status);\n\n // Combine the status into single isValid property.\n status.isValid &&= status.meetsMinPasswordLength ?? true;\n status.isValid &&= status.meetsMaxPasswordLength ?? true;\n status.isValid &&= status.containsLowercaseLetter ?? true;\n status.isValid &&= status.containsUppercaseLetter ?? true;\n status.isValid &&= status.containsNumericCharacter ?? true;\n status.isValid &&= status.containsNonAlphanumericCharacter ?? true;\n\n return status;\n }\n\n /**\n * Validates that the password meets the length options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordLengthOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\n if (minPasswordLength) {\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\n }\n if (maxPasswordLength) {\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\n }\n }\n\n /**\n * Validates that the password meets the character options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordCharacterOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n // Assign statuses for requirements even if the password is an empty string.\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ false,\n /* containsUppercaseCharacter= */ false,\n /* containsNumericCharacter= */ false,\n /* containsNonAlphanumericCharacter= */ false\n );\n\n let passwordChar;\n for (let i = 0; i < password.length; i++) {\n passwordChar = password.charAt(i);\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\n passwordChar <= 'z',\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\n passwordChar <= 'Z',\n /* containsNumericCharacter= */ passwordChar >= '0' &&\n passwordChar <= '9',\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(\n passwordChar\n )\n );\n }\n }\n\n /**\n * Updates the running validation status with the statuses for the character options.\n * Expected to be called each time a character is processed to update each option status\n * based on the current character.\n *\n * @param status Validation status.\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\n * @param containsNumericCharacter Whether the character is a numeric character.\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\n */\n private updatePasswordCharacterOptionsStatuses(\n status: PasswordValidationStatusInternal,\n containsLowercaseCharacter: boolean,\n containsUppercaseCharacter: boolean,\n containsNumericCharacter: boolean,\n containsNonAlphanumericCharacter: boolean\n ): void {\n if (this.customStrengthOptions.containsLowercaseLetter) {\n status.containsLowercaseLetter ||= containsLowercaseCharacter;\n }\n if (this.customStrengthOptions.containsUppercaseLetter) {\n status.containsUppercaseLetter ||= containsUppercaseCharacter;\n }\n if (this.customStrengthOptions.containsNumericCharacter) {\n status.containsNumericCharacter ||= containsNumericCharacter;\n }\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\n status.containsNonAlphanumericCharacter ||=\n containsNonAlphanumericCharacter;\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 {\n _isFirebaseServerApp,\n _FirebaseService,\n FirebaseApp\n} from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport {\n Auth,\n AuthErrorMap,\n AuthSettings,\n EmulatorConfig,\n NextOrObserver,\n Persistence,\n PopupRedirectResolver,\n User,\n UserCredential,\n CompleteFn,\n ErrorFn,\n NextFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../../model/public_types';\nimport {\n createSubscribe,\n ErrorFactory,\n FirebaseError,\n getModularInstance,\n Observer,\n Subscribe\n} from '@firebase/util';\n\nimport { AuthInternal, ConfigInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport {\n AuthErrorCode,\n AuthErrorParams,\n ErrorMapRetriever,\n _DEFAULT_AUTH_ERROR_FACTORY\n} from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport {\n KeyName,\n PersistenceUserManager\n} from '../persistence/persistence_user_manager';\nimport { _reloadWithoutSaving } from '../user/reload';\nimport {\n _assert,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { _getUserLanguage } from '../util/navigator';\nimport { _getClientVersion } from '../util/version';\nimport { HttpHeader } from '../../api';\nimport {\n RevokeTokenRequest,\n TokenType,\n revokeToken\n} from '../../api/authentication/token';\nimport { AuthMiddlewareQueue } from './middleware';\nimport { RecaptchaConfig } from '../../platform_browser/recaptcha/recaptcha';\nimport { _logWarn } from '../util/log';\nimport { _getPasswordPolicy } from '../../api/password_policy/get_password_policy';\nimport { PasswordPolicyInternal } from '../../model/password_policy';\nimport { PasswordPolicyImpl } from './password_policy_impl';\nimport { getAccountInfo } from '../../api/account_management/account';\nimport { UserImpl } from '../user/user_impl';\n\ninterface AsyncAction {\n (): Promise;\n}\n\nexport const enum DefaultConfig {\n TOKEN_API_HOST = 'securetoken.googleapis.com',\n API_HOST = 'identitytoolkit.googleapis.com',\n API_SCHEME = 'https'\n}\n\nexport class AuthImpl implements AuthInternal, _FirebaseService {\n currentUser: User | null = null;\n emulatorConfig: EmulatorConfig | null = null;\n private operations = Promise.resolve();\n private persistenceManager?: PersistenceUserManager;\n private redirectPersistenceManager?: PersistenceUserManager;\n private authStateSubscription = new Subscription(this);\n private idTokenSubscription = new Subscription(this);\n private readonly beforeStateQueue = new AuthMiddlewareQueue(this);\n private redirectUser: UserInternal | null = null;\n private isProactiveRefreshEnabled = false;\n private readonly EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION: number = 1;\n\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n _canInitEmulator = true;\n _isInitialized = false;\n _deleted = false;\n _initializationPromise: Promise | null = null;\n _popupRedirectResolver: PopupRedirectResolverInternal | null = null;\n _errorFactory: ErrorFactory =\n _DEFAULT_AUTH_ERROR_FACTORY;\n _agentRecaptchaConfig: RecaptchaConfig | null = null;\n _tenantRecaptchaConfigs: Record = {};\n _projectPasswordPolicy: PasswordPolicyInternal | null = null;\n _tenantPasswordPolicies: Record = {};\n readonly name: string;\n\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n private lastNotifiedUid: string | null | undefined = undefined;\n\n languageCode: string | null = null;\n tenantId: string | null = null;\n settings: AuthSettings = { appVerificationDisabledForTesting: false };\n\n constructor(\n public readonly app: FirebaseApp,\n private readonly heartbeatServiceProvider: Provider<'heartbeat'>,\n private readonly appCheckServiceProvider: Provider,\n public readonly config: ConfigInternal\n ) {\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n }\n\n _initializeWithPersistence(\n persistenceHierarchy: PersistenceInternal[],\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n\n this.persistenceManager = await PersistenceUserManager.create(\n this,\n persistenceHierarchy\n );\n\n if (this._deleted) {\n return;\n }\n\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n } catch (e) {\n /* Ignore the error */\n }\n }\n\n await this.initializeCurrentUser(popupRedirectResolver);\n\n this.lastNotifiedUid = this.currentUser?.uid || null;\n\n if (this._deleted) {\n return;\n }\n\n this._isInitialized = true;\n });\n\n return this._initializationPromise;\n }\n\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent(): Promise {\n if (this._deleted) {\n return;\n }\n\n const user = await this.assertedPersistence.getCurrentUser();\n\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n\n private async initializeCurrentUserFromIdToken(\n idToken: string\n ): Promise {\n try {\n const response = await getAccountInfo(this, { idToken });\n const user = await UserImpl._fromGetAccountInfoResponse(\n this,\n response,\n idToken\n );\n await this.directlySetCurrentUser(user);\n } catch (err) {\n console.warn(\n 'FirebaseServerApp could not login user with provided authIdToken: ',\n err\n );\n await this.directlySetCurrentUser(null);\n }\n }\n\n private async initializeCurrentUser(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (_isFirebaseServerApp(this.app)) {\n const idToken = this.app.settings.authIdToken;\n if (idToken) {\n // Start the auth operation in the next tick to allow a moment for the customer's app to\n // attach an emulator, if desired.\n return new Promise(resolve => {\n setTimeout(() =>\n this.initializeCurrentUserFromIdToken(idToken).then(\n resolve,\n resolve\n )\n );\n });\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser =\n (await this.assertedPersistence.getCurrentUser()) as UserInternal | null;\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if (\n (!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user\n ) {\n futureCurrentUser = result.user as UserInternal;\n needsTocheckMiddleware = true;\n }\n }\n\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n } catch (e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver!._overrideRedirectResult(this, () =>\n Promise.reject(e)\n );\n }\n }\n\n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n _assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);\n await this.getOrInitRedirectPersistenceManager();\n\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (\n this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId\n ) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n\n private async tryRedirectSignIn(\n redirectResolver: PopupRedirectResolver\n ): Promise {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n\n let result: UserCredential | null = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver!._completeRedirectFn(\n this,\n redirectResolver,\n true\n );\n } catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n\n return result;\n }\n\n private async reloadAndSetCurrentUserOrClear(\n user: UserInternal\n ): Promise {\n try {\n await _reloadWithoutSaving(user);\n } catch (e) {\n if (\n (e as FirebaseError)?.code !==\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n\n return this.directlySetCurrentUser(user);\n }\n\n useDeviceLanguage(): void {\n this.languageCode = _getUserLanguage();\n }\n\n async _delete(): Promise {\n this._deleted = true;\n }\n\n async updateCurrentUser(userExtern: User | null): Promise {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(this)\n );\n }\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? (getModularInstance(userExtern) as UserInternal)\n : null;\n if (user) {\n _assert(\n user.auth.config.apiKey === this.config.apiKey,\n this,\n AuthErrorCode.INVALID_AUTH\n );\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n\n async _updateCurrentUser(\n user: User | null,\n skipBeforeStateCallbacks: boolean = false\n ): Promise {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(\n this.tenantId === user.tenantId,\n this,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n }\n\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n\n return this.queue(async () => {\n await this.directlySetCurrentUser(user as UserInternal | null);\n this.notifyAuthListeners();\n });\n }\n\n async signOut(): Promise {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(this)\n );\n }\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n\n setPersistence(persistence: Persistence): Promise {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(this)\n );\n }\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n\n _getRecaptchaConfig(): RecaptchaConfig | null {\n if (this.tenantId == null) {\n return this._agentRecaptchaConfig;\n } else {\n return this._tenantRecaptchaConfigs[this.tenantId];\n }\n }\n\n async validatePassword(password: string): Promise {\n if (!this._getPasswordPolicyInternal()) {\n await this._updatePasswordPolicy();\n }\n\n // Password policy will be defined after fetching.\n const passwordPolicy: PasswordPolicyInternal =\n this._getPasswordPolicyInternal()!;\n\n // Check that the policy schema version is supported by the SDK.\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\n if (\n passwordPolicy.schemaVersion !==\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION\n ) {\n return Promise.reject(\n this._errorFactory.create(\n AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION,\n {}\n )\n );\n }\n\n return passwordPolicy.validatePassword(password);\n }\n\n _getPasswordPolicyInternal(): PasswordPolicyInternal | null {\n if (this.tenantId === null) {\n return this._projectPasswordPolicy;\n } else {\n return this._tenantPasswordPolicies[this.tenantId];\n }\n }\n\n async _updatePasswordPolicy(): Promise {\n const response = await _getPasswordPolicy(this);\n\n const passwordPolicy: PasswordPolicyInternal = new PasswordPolicyImpl(\n response\n );\n\n if (this.tenantId === null) {\n this._projectPasswordPolicy = passwordPolicy;\n } else {\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\n }\n }\n\n _getPersistence(): string {\n return this.assertedPersistence.persistence.type;\n }\n\n _updateErrorMap(errorMap: AuthErrorMap): void {\n this._errorFactory = new ErrorFactory(\n 'auth',\n 'Firebase',\n (errorMap as ErrorMapRetriever)()\n );\n }\n\n onAuthStateChanged(\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.authStateSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n beforeAuthStateChanged(\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n ): Unsubscribe {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n\n onIdTokenChanged(\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.idTokenSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n authStateReady(): Promise {\n return new Promise((resolve, reject) => {\n if (this.currentUser) {\n resolve();\n } else {\n const unsubscribe = this.onAuthStateChanged(() => {\n unsubscribe();\n resolve();\n }, reject);\n }\n });\n }\n\n /**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n */\n async revokeAccessToken(token: string): Promise {\n if (this.currentUser) {\n const idToken = await this.currentUser.getIdToken();\n // Generalize this to accept other providers once supported.\n const request: RevokeTokenRequest = {\n providerId: 'apple.com',\n tokenType: TokenType.ACCESS_TOKEN,\n token,\n idToken\n };\n if (this.tenantId != null) {\n request.tenantId = this.tenantId;\n }\n await revokeToken(this, request);\n }\n }\n\n toJSON(): object {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n\n async _setRedirectUser(\n user: UserInternal | null,\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(\n popupRedirectResolver\n );\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n\n private async getOrInitRedirectPersistenceManager(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (!this.redirectPersistenceManager) {\n const resolver: PopupRedirectResolverInternal | null =\n (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);\n this.redirectPersistenceManager = await PersistenceUserManager.create(\n this,\n [_getInstance(resolver._redirectPersistence)],\n KeyName.REDIRECT_USER\n );\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n\n return this.redirectPersistenceManager;\n }\n\n async _redirectUserForId(id: string): Promise {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => {});\n }\n\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n\n return null;\n }\n\n async _persistUserIfCurrent(user: UserInternal): Promise {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user: UserInternal): void {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n\n _key(): string {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n\n _startProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n\n _stopProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n\n /** Returns the current user cast as the internal type */\n get _currentUser(): UserInternal {\n return this.currentUser as UserInternal;\n }\n\n private notifyAuthListeners(): void {\n if (!this._isInitialized) {\n return;\n }\n\n this.idTokenSubscription.next(this.currentUser);\n\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n\n private registerStateListener(\n subscription: Subscription,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n if (this._deleted) {\n return () => {};\n }\n\n const cb =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n\n let isUnsubscribed = false;\n\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, AuthErrorCode.INTERNAL_ERROR);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise.then(() => {\n if (isUnsubscribed) {\n return;\n }\n cb(this.currentUser);\n });\n\n if (typeof nextOrObserver === 'function') {\n const unsubscribe = subscription.addObserver(\n nextOrObserver,\n error,\n completed\n );\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n } else {\n const unsubscribe = subscription.addObserver(nextOrObserver);\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n }\n }\n\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n private async directlySetCurrentUser(\n user: UserInternal | null\n ): Promise {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n }\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n\n this.currentUser = user;\n\n if (user) {\n await this.assertedPersistence.setCurrentUser(user);\n } else {\n await this.assertedPersistence.removeCurrentUser();\n }\n }\n\n private queue(action: AsyncAction): Promise {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n\n private get assertedPersistence(): PersistenceUserManager {\n _assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);\n return this.persistenceManager;\n }\n\n private frameworks: string[] = [];\n private clientVersion: string;\n _logFramework(framework: string): void {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(\n this.config.clientPlatform,\n this._getFrameworks()\n );\n }\n _getFrameworks(): readonly string[] {\n return this.frameworks;\n }\n async _getAdditionalHeaders(): Promise> {\n // Additional headers on every request\n const headers: Record = {\n [HttpHeader.X_CLIENT_VERSION]: this.clientVersion\n };\n\n if (this.app.options.appId) {\n headers[HttpHeader.X_FIREBASE_GMPID] = this.app.options.appId;\n }\n\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider\n .getImmediate({\n optional: true\n })\n ?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[HttpHeader.X_FIREBASE_CLIENT] = heartbeatsHeader;\n }\n\n // If the App Check service exists, add the App Check token in the headers\n const appCheckToken = await this._getAppCheckToken();\n if (appCheckToken) {\n headers[HttpHeader.X_FIREBASE_APP_CHECK] = appCheckToken;\n }\n\n return headers;\n }\n\n async _getAppCheckToken(): Promise {\n const appCheckTokenResult = await this.appCheckServiceProvider\n .getImmediate({ optional: true })\n ?.getToken();\n if (appCheckTokenResult?.error) {\n // Context: appCheck.getToken() will never throw even if an error happened.\n // In the error case, a dummy token will be returned along with an error field describing\n // the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n _logWarn(\n `Error while retrieving App Check token: ${appCheckTokenResult.error}`\n );\n }\n return appCheckTokenResult?.token;\n }\n}\n\n/**\n * Method to be used to cast down to our private implmentation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nexport function _castAuth(auth: Auth): AuthInternal {\n return getModularInstance(auth) as AuthInternal;\n}\n\n/** Helper class to wrap subscriber logic */\nclass Subscription {\n private observer: Observer | null = null;\n readonly addObserver: Subscribe = createSubscribe(\n observer => (this.observer = observer)\n );\n\n constructor(readonly auth: AuthInternal) {}\n\n get next(): NextFn {\n _assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.observer.next.bind(this.observer);\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\ninterface ExternalJSProvider {\n loadJS(url: string): Promise;\n recaptchaV2Script: string;\n recaptchaEnterpriseScript: string;\n gapiScript: string;\n}\n\nlet externalJSProvider: ExternalJSProvider = {\n async loadJS() {\n throw new Error('Unable to load external scripts');\n },\n\n recaptchaV2Script: '',\n recaptchaEnterpriseScript: '',\n gapiScript: ''\n};\n\nexport function _setExternalJSProvider(p: ExternalJSProvider): void {\n externalJSProvider = p;\n}\n\nexport function _loadJS(url: string): Promise {\n return externalJSProvider.loadJS(url);\n}\n\nexport function _recaptchaV2ScriptUrl(): string {\n return externalJSProvider.recaptchaV2Script;\n}\n\nexport function _recaptchaEnterpriseScriptUrl(): string {\n return externalJSProvider.recaptchaEnterpriseScript;\n}\n\nexport function _gapiScriptUrl(): string {\n return externalJSProvider.gapiScript;\n}\n\nexport function _generateCallbackName(prefix: string): string {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n", "/* eslint-disable @typescript-eslint/no-require-imports */\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 { isEnterprise, RecaptchaConfig } from './recaptcha';\nimport { getRecaptchaConfig } from '../../api/authentication/recaptcha';\nimport {\n RecaptchaClientType,\n RecaptchaVersion,\n RecaptchaActionName,\n RecaptchaProvider\n} from '../../api';\n\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport * as jsHelpers from '../load_js';\nimport { AuthErrorCode } from '../../core/errors';\n\nexport const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\nexport const FAKE_TOKEN = 'NO_RECAPTCHA';\n\nexport class RecaptchaEnterpriseVerifier {\n /**\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\n */\n readonly type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\n\n private readonly auth: AuthInternal;\n\n /**\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n */\n constructor(authExtern: Auth) {\n this.auth = _castAuth(authExtern);\n }\n\n /**\n * Executes the verification process.\n *\n * @returns A Promise for a token that can be used to assert the validity of a request.\n */\n async verify(\n action: string = 'verify',\n forceRefresh = false\n ): Promise {\n async function retrieveSiteKey(auth: AuthInternal): Promise {\n if (!forceRefresh) {\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\n return auth._agentRecaptchaConfig.siteKey;\n }\n if (\n auth.tenantId != null &&\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined\n ) {\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\n }\n }\n\n return new Promise(async (resolve, reject) => {\n getRecaptchaConfig(auth, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n })\n .then(response => {\n if (response.recaptchaKey === undefined) {\n reject(new Error('recaptcha Enterprise site key undefined'));\n } else {\n const config = new RecaptchaConfig(response);\n if (auth.tenantId == null) {\n auth._agentRecaptchaConfig = config;\n } else {\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\n }\n return resolve(config.siteKey);\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n\n function retrieveRecaptchaToken(\n siteKey: string,\n resolve: (value: string | PromiseLike) => void,\n reject: (reason?: unknown) => void\n ): void {\n const grecaptcha = window.grecaptcha;\n if (isEnterprise(grecaptcha)) {\n grecaptcha.enterprise.ready(() => {\n grecaptcha.enterprise\n .execute(siteKey, { action })\n .then(token => {\n resolve(token);\n })\n .catch(() => {\n resolve(FAKE_TOKEN);\n });\n });\n } else {\n reject(Error('No reCAPTCHA enterprise script loaded.'));\n }\n }\n\n return new Promise((resolve, reject) => {\n retrieveSiteKey(this.auth)\n .then(siteKey => {\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n } else {\n if (typeof window === 'undefined') {\n reject(\n new Error('RecaptchaVerifier is only supported in browser')\n );\n return;\n }\n let url = jsHelpers._recaptchaEnterpriseScriptUrl();\n if (url.length !== 0) {\n url += siteKey;\n }\n jsHelpers\n ._loadJS(url)\n .then(() => {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n })\n .catch(error => {\n reject(error);\n });\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n}\n\nexport async function injectRecaptchaFields(\n auth: AuthInternal,\n request: T,\n action: RecaptchaActionName,\n captchaResp = false\n): Promise {\n const verifier = new RecaptchaEnterpriseVerifier(auth);\n let captchaResponse;\n try {\n captchaResponse = await verifier.verify(action);\n } catch (error) {\n captchaResponse = await verifier.verify(action, true);\n }\n const newRequest = { ...request };\n if (!captchaResp) {\n Object.assign(newRequest, { captchaResponse });\n } else {\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\n }\n Object.assign(newRequest, { 'clientType': RecaptchaClientType.WEB });\n Object.assign(newRequest, {\n 'recaptchaVersion': RecaptchaVersion.ENTERPRISE\n });\n return newRequest;\n}\n\ntype ActionMethod = (\n auth: Auth,\n request: TRequest\n) => Promise;\n\nexport async function handleRecaptchaFlow(\n authInstance: AuthInternal,\n request: TRequest,\n actionName: RecaptchaActionName,\n actionMethod: ActionMethod\n): Promise {\n if (\n authInstance\n ._getRecaptchaConfig()\n ?.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)\n ) {\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return actionMethod(authInstance, request).catch(async error => {\n if (error.code === `auth/${AuthErrorCode.MISSING_RECAPTCHA_TOKEN}`) {\n console.log(\n `${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`\n );\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return Promise.reject(error);\n }\n });\n }\n}\n\nexport async function _initializeRecaptchaConfig(auth: Auth): Promise {\n const authInternal = _castAuth(auth);\n\n const response = await getRecaptchaConfig(authInternal, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n });\n\n const config = new RecaptchaConfig(response);\n if (authInternal.tenantId == null) {\n authInternal._agentRecaptchaConfig = config;\n } else {\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\n }\n\n if (config.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)) {\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\n void verifier.verify();\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 { _getProvider, FirebaseApp } from '@firebase/app';\nimport { deepEqual } from '@firebase/util';\nimport { Auth, Dependencies } from '../../model/public_types';\n\nimport { AuthErrorCode } from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport { _fail } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { AuthImpl } from './auth_impl';\n\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nexport function initializeAuth(app: FirebaseApp, deps?: Dependencies): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n const auth = provider.getImmediate() as AuthImpl;\n const initialOptions = provider.getOptions() as Dependencies;\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n } else {\n _fail(auth, AuthErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const auth = provider.initialize({ options: deps }) as AuthImpl;\n\n return auth;\n}\n\nexport function _initializeAuthInstance(\n auth: AuthImpl,\n deps?: Dependencies\n): void {\n const persistence = deps?.persistence || [];\n const hierarchy = (\n Array.isArray(persistence) ? persistence : [persistence]\n ).map(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\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 */\nimport { Auth } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _castAuth } from './auth_impl';\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nexport function connectAuthEmulator(\n auth: Auth,\n url: string,\n options?: { disableWarnings: boolean }\n): void {\n const authInternal = _castAuth(auth);\n _assert(\n authInternal._canInitEmulator,\n authInternal,\n AuthErrorCode.EMULATOR_CONFIG_FAILED\n );\n\n _assert(\n /^https?:\\/\\//.test(url),\n authInternal,\n AuthErrorCode.INVALID_EMULATOR_SCHEME\n );\n\n const disableWarnings = !!options?.disableWarnings;\n\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\n authInternal.settings.appVerificationDisabledForTesting = true;\n authInternal.emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n\n if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\n\nfunction extractProtocol(url: string): string {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\n\nfunction extractHostAndPort(url: string): {\n host: string;\n port: number | null;\n} {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n } else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\n\nfunction parsePort(portStr: string): number | null {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\n\nfunction emitEmulatorWarning(): void {\n function attachBanner(): void {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info(\n 'WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.'\n );\n }\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n } else {\n attachBanner();\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 { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { debugFail } from '../util/assert';\n\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class AuthCredential {\n /** @internal */\n protected constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n readonly providerId: string,\n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n readonly signInMethod: string\n ) {}\n\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON(): object {\n return debugFail('not implemented');\n }\n\n /** @internal */\n _getIdTokenResponse(_auth: AuthInternal): Promise {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(\n _auth: AuthInternal,\n _idToken: string\n ): Promise {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth: AuthInternal): Promise {\n return debugFail('not implemented');\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 { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from './mfa';\nimport { SignUpRequest, SignUpResponse } from '../authentication/sign_up';\n\nexport interface ResetPasswordRequest {\n oobCode: string;\n newPassword?: string;\n tenantId?: string;\n}\n\nexport interface ResetPasswordResponse {\n email: string;\n newEmail?: string;\n requestType?: ActionCodeOperation;\n mfaInfo?: MfaEnrollment;\n}\n\nexport async function resetPassword(\n auth: Auth,\n request: ResetPasswordRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.RESET_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface UpdateEmailPasswordRequest {\n idToken: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n}\n\nexport interface UpdateEmailPasswordResponse extends IdTokenResponse {}\n\nexport async function updateEmailPassword(\n auth: Auth,\n request: UpdateEmailPasswordRequest\n): Promise {\n return _performApiRequest<\n UpdateEmailPasswordRequest,\n UpdateEmailPasswordResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\n// format as updateEmailPassword.\nexport async function linkEmailPassword(\n auth: Auth,\n request: SignUpRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n request\n );\n}\n\nexport interface ApplyActionCodeRequest {\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface ApplyActionCodeResponse {}\n\nexport async function applyActionCode(\n auth: Auth,\n request: ApplyActionCodeRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n _addTidIfNecessary(auth, request)\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 { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\n\nexport interface SignInWithPasswordRequest {\n returnSecureToken?: boolean;\n email: string;\n password: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignInWithPasswordResponse extends IdTokenResponse {\n email: string;\n displayName: string;\n}\n\nexport async function signInWithPassword(\n auth: Auth,\n request: SignInWithPasswordRequest\n): Promise {\n return _performSignInRequest<\n SignInWithPasswordRequest,\n SignInWithPasswordResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface GetOobCodeRequest {\n email?: string; // Everything except VERIFY_AND_CHANGE_EMAIL\n continueUrl?: string;\n iOSBundleId?: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n androidInstallApp?: boolean;\n androidMinimumVersionCode?: string;\n canHandleCodeInApp?: boolean;\n dynamicLinkDomain?: string;\n tenantId?: string;\n targetProjectid?: string;\n}\n\nexport interface VerifyEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_EMAIL;\n idToken: IdToken;\n}\n\nexport interface PasswordResetRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.PASSWORD_RESET;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface EmailSignInRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.EMAIL_SIGNIN;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface VerifyAndChangeEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n idToken: IdToken;\n newEmail: string;\n}\n\ninterface GetOobCodeResponse {\n email: string;\n}\n\nexport interface VerifyEmailResponse extends GetOobCodeResponse {}\nexport interface PasswordResetResponse extends GetOobCodeResponse {}\nexport interface EmailSignInResponse extends GetOobCodeResponse {}\nexport interface VerifyAndChangeEmailResponse extends GetOobCodeRequest {}\n\nasync function sendOobCode(\n auth: Auth,\n request: GetOobCodeRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_OOB_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function sendEmailVerification(\n auth: Auth,\n request: VerifyEmailRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function sendPasswordResetEmail(\n auth: Auth,\n request: PasswordResetRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n request: EmailSignInRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function verifyAndChangeEmail(\n auth: Auth,\n request: VerifyAndChangeEmailRequest\n): Promise {\n return sendOobCode(auth, request);\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 {\n _performSignInRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithEmailLinkRequest {\n email: string;\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface SignInWithEmailLinkResponse extends IdTokenResponse {\n email: string;\n isNewUser: boolean;\n}\n\nexport async function signInWithEmailLink(\n auth: Auth,\n request: SignInWithEmailLinkRequest\n): Promise {\n return _performSignInRequest<\n SignInWithEmailLinkRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface SignInWithEmailLinkForLinkingRequest\n extends SignInWithEmailLinkRequest {\n idToken: string;\n}\n\nexport async function signInWithEmailLinkForLinking(\n auth: Auth,\n request: SignInWithEmailLinkForLinkingRequest\n): Promise {\n return _performSignInRequest<\n SignInWithEmailLinkForLinkingRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\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 { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { linkEmailPassword } from '../../api/account_management/email_and_password';\nimport {\n signInWithPassword,\n SignInWithPasswordRequest\n} from '../../api/authentication/email_and_password';\nimport {\n signInWithEmailLink,\n signInWithEmailLinkForLinking\n} from '../../api/authentication/email_link';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { SignUpRequest } from '../../api/authentication/sign_up';\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nexport class EmailAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n /** @internal */\n readonly _email: string,\n /** @internal */\n readonly _password: string,\n signInMethod: SignInMethod,\n /** @internal */\n readonly _tenantId: string | null = null\n ) {\n super(ProviderId.PASSWORD, signInMethod);\n }\n\n /** @internal */\n static _fromEmailAndPassword(\n email: string,\n password: string\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n password,\n SignInMethod.EMAIL_PASSWORD\n );\n }\n\n /** @internal */\n static _fromEmailAndCode(\n email: string,\n oobCode: string,\n tenantId: string | null = null\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n oobCode,\n SignInMethod.EMAIL_LINK,\n tenantId\n );\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: object | string): EmailAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === SignInMethod.EMAIL_PASSWORD) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n } else if (obj.signInMethod === SignInMethod.EMAIL_LINK) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n\n /** @internal */\n async _getIdTokenResponse(auth: AuthInternal): Promise {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignInWithPasswordRequest = {\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_IN_WITH_PASSWORD,\n signInWithPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLink(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n async _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignUpRequest = {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n linkEmailPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return this._getIdTokenResponse(auth);\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithIdpRequest {\n requestUri: string;\n postBody?: string;\n sessionId?: string;\n tenantId?: string;\n returnSecureToken: boolean;\n returnIdpCredential?: boolean;\n idToken?: IdToken;\n autoCreate?: boolean;\n pendingToken?: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithIdpResponse extends IdTokenResponse {\n oauthAccessToken?: string;\n oauthTokenSecret?: string;\n nonce?: string;\n oauthIdToken?: string;\n pendingToken?: string;\n}\n\nexport async function signInWithIdp(\n auth: Auth,\n request: SignInWithIdpRequest\n): Promise {\n return _performSignInRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_IDP,\n _addTidIfNecessary(auth, request)\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 { querystring } from '@firebase/util';\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\nexport interface OAuthCredentialParams {\n // OAuth 2 uses either id token or access token\n idToken?: string | null;\n accessToken?: string | null;\n\n // These fields are used with OAuth 1\n oauthToken?: string;\n secret?: string;\n oauthTokenSecret?: string;\n\n // Nonce is only set if pendingToken is not present\n nonce?: string;\n pendingToken?: string;\n\n // Utilities\n providerId: string;\n signInMethod: string;\n}\n\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class OAuthCredential extends AuthCredential {\n /**\n * The OAuth ID token associated with the credential if it belongs to an OIDC provider,\n * such as `google.com`.\n * @readonly\n */\n idToken?: string;\n /**\n * The OAuth access token associated with the credential if it belongs to an\n * {@link OAuthProvider}, such as `facebook.com`, `twitter.com`, etc.\n * @readonly\n */\n accessToken?: string;\n /**\n * The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0\n * provider, such as `twitter.com`.\n * @readonly\n */\n secret?: string;\n\n private nonce?: string;\n private pendingToken: string | null = null;\n\n /** @internal */\n static _fromParams(params: OAuthCredentialParams): OAuthCredential {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n } else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n } else {\n _fail(AuthErrorCode.ARGUMENT_ERROR);\n }\n\n return cred;\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): OAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest }: OAuthCredentialParams = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true\n };\n\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n } else {\n const postBody: Record = {};\n if (this.idToken) {\n postBody['id_token'] = this.idToken;\n }\n if (this.accessToken) {\n postBody['access_token'] = this.accessToken;\n }\n if (this.secret) {\n postBody['oauth_token_secret'] = this.secret;\n }\n\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n\n request.postBody = querystring(postBody);\n }\n\n return request;\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _makeTaggedError,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { AuthErrorCode } from '../../core/errors';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { ServerError, ServerErrorMap } from '../errors';\nimport { Auth } from '../../model/public_types';\n\nexport interface SendPhoneVerificationCodeRequest {\n phoneNumber: string;\n recaptchaToken: string;\n tenantId?: string;\n}\n\nexport interface SendPhoneVerificationCodeResponse {\n sessionInfo: string;\n}\n\nexport async function sendPhoneVerificationCode(\n auth: Auth,\n request: SendPhoneVerificationCodeRequest\n): Promise {\n return _performApiRequest<\n SendPhoneVerificationCodeRequest,\n SendPhoneVerificationCodeResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_VERIFICATION_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberRequest {\n temporaryProof?: string;\n phoneNumber?: string;\n sessionInfo?: string;\n code?: string;\n tenantId?: string;\n}\n\nexport interface LinkWithPhoneNumberRequest\n extends SignInWithPhoneNumberRequest {\n idToken: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberResponse extends IdTokenResponse {\n temporaryProof?: string;\n phoneNumber?: string;\n}\n\nexport async function signInWithPhoneNumber(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise {\n return _performSignInRequest<\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function linkWithPhoneNumber(\n auth: Auth,\n request: LinkWithPhoneNumberRequest\n): Promise {\n const response = await _performSignInRequest<\n LinkWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, response);\n }\n return response;\n}\n\ninterface VerifyPhoneNumberForExistingRequest\n extends SignInWithPhoneNumberRequest {\n operation: 'REAUTH';\n}\n\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_: Partial<\n ServerErrorMap\n> = {\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.USER_DELETED\n};\n\nexport async function verifyPhoneNumberForExisting(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise {\n const apiRequest: VerifyPhoneNumberForExistingRequest = {\n ...request,\n operation: 'REAUTH'\n };\n return _performSignInRequest<\n VerifyPhoneNumberForExistingRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, apiRequest),\n VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_\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 { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport {\n linkWithPhoneNumber,\n signInWithPhoneNumber,\n SignInWithPhoneNumberRequest,\n verifyPhoneNumberForExisting\n} from '../../api/authentication/sms';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nexport interface PhoneAuthCredentialParameters {\n verificationId?: string;\n verificationCode?: string;\n phoneNumber?: string;\n temporaryProof?: string;\n}\n\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nexport class PhoneAuthCredential extends AuthCredential {\n private constructor(private readonly params: PhoneAuthCredentialParameters) {\n super(ProviderId.PHONE, SignInMethod.PHONE);\n }\n\n /** @internal */\n static _fromVerification(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n\n /** @internal */\n static _fromTokenResponse(\n phoneNumber: string,\n temporaryProof: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n return signInWithPhoneNumber(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n return linkWithPhoneNumber(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _makeVerificationRequest(): SignInWithPhoneNumberRequest {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } =\n this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n const obj: Record = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n\n return obj;\n }\n\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json: object | string): PhoneAuthCredential | null {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n\n const { verificationId, verificationCode, phoneNumber, temporaryProof } =\n json as { [key: string]: string };\n if (\n !verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof\n ) {\n return null;\n }\n\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\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 { extractQuerystring, querystringDecode } from '@firebase/util';\nimport { ActionCodeOperation } from '../model/public_types';\nimport { AuthErrorCode } from './errors';\nimport { _assert } from './util/assert';\n\n/**\n * Enums for fields in URL query string.\n *\n * @enum {string}\n */\nconst enum QueryField {\n API_KEY = 'apiKey',\n CODE = 'oobCode',\n CONTINUE_URL = 'continueUrl',\n LANGUAGE_CODE = 'languageCode',\n MODE = 'mode',\n TENANT_ID = 'tenantId'\n}\n\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode: string | null): ActionCodeOperation | null {\n switch (mode) {\n case 'recoverEmail':\n return ActionCodeOperation.RECOVER_EMAIL;\n case 'resetPassword':\n return ActionCodeOperation.PASSWORD_RESET;\n case 'signIn':\n return ActionCodeOperation.EMAIL_SIGNIN;\n case 'verifyEmail':\n return ActionCodeOperation.VERIFY_EMAIL;\n case 'verifyAndChangeEmail':\n return ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n case 'revertSecondFactorAddition':\n return ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION;\n default:\n return null;\n }\n}\n\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url: string): string {\n const link = querystringDecode(extractQuerystring(url))['link'];\n\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))[\n 'deep_link_id'\n ];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nexport class ActionCodeURL {\n /**\n * The API key of the email action link.\n */\n readonly apiKey: string;\n /**\n * The action code of the email action link.\n */\n readonly code: string;\n /**\n * The continue URL of the email action link. Null if not provided.\n */\n readonly continueUrl: string | null;\n /**\n * The language code of the email action link. Null if not provided.\n */\n readonly languageCode: string | null;\n /**\n * The action performed by the email action link. It returns from one of the types from\n * {@link ActionCodeInfo}\n */\n readonly operation: string;\n /**\n * The tenant ID of the email action link. Null if the email action is from the parent project.\n */\n readonly tenantId: string | null;\n\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink: string) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[QueryField.API_KEY] ?? null;\n const code = searchParams[QueryField.CODE] ?? null;\n const operation = parseMode(searchParams[QueryField.MODE] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, AuthErrorCode.ARGUMENT_ERROR);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[QueryField.CONTINUE_URL] ?? null;\n this.languageCode = searchParams[QueryField.LANGUAGE_CODE] ?? null;\n this.tenantId = searchParams[QueryField.TENANT_ID] ?? null;\n }\n\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link: string): ActionCodeURL | null {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nexport function parseActionCodeURL(link: string): ActionCodeURL | null {\n return ActionCodeURL.parseLink(link);\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 { ProviderId, SignInMethod } from '../../model/enums';\nimport { AuthProvider } from '../../model/public_types';\n\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthCredential } from '../credentials/email';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nexport class EmailAuthProvider implements AuthProvider {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n static readonly PROVIDER_ID: 'password' = ProviderId.PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\n static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password' =\n SignInMethod.EMAIL_PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\n static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink' =\n SignInMethod.EMAIL_LINK;\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n readonly providerId = EmailAuthProvider.PROVIDER_ID;\n\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email: string, password: string): EmailAuthCredential {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(\n email: string,\n emailLink: string\n ): EmailAuthCredential {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, AuthErrorCode.ARGUMENT_ERROR);\n\n return EmailAuthCredential._fromEmailAndCode(\n email,\n actionCodeUrl.code,\n actionCodeUrl.tenantId\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 { AuthProvider } from '../../model/public_types';\n\n/**\n * Map of OAuth Custom Parameters.\n *\n * @public\n */\nexport type CustomParameters = Record;\n\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nexport abstract class FederatedAuthProvider implements AuthProvider {\n /** @internal */\n defaultLanguageCode: string | null = null;\n /** @internal */\n private customParameters: CustomParameters = {};\n\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(readonly providerId: string) {}\n\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode: string | null): void {\n this.defaultLanguageCode = languageCode;\n }\n\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider {\n this.customParameters = customOAuthParameters;\n return this;\n }\n\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters(): CustomParameters {\n return this.customParameters;\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\nimport { AuthProvider, UserCredential } from '../../model/public_types';\n\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\nimport { OAuthCredential, OAuthCredentialParams } from '../credentials/oauth';\nimport { UserCredentialInternal } from '../../model/user';\nimport { FirebaseError } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { SignInWithIdpResponse } from '../../../internal';\nimport { FederatedAuthProvider } from './federated';\n\n/**\n * Defines the options for initializing an {@link OAuthCredential}.\n *\n * @remarks\n * For ID tokens with nonce claim, the raw nonce has to also be provided.\n *\n * @public\n */\nexport interface OAuthCredentialOptions {\n /**\n * The OAuth ID token used to initialize the {@link OAuthCredential}.\n */\n idToken?: string;\n /**\n * The OAuth access token used to initialize the {@link OAuthCredential}.\n */\n accessToken?: string;\n /**\n * The raw nonce associated with the ID token.\n *\n * @remarks\n * It is required when an ID token with a nonce field is provided. The SHA-256 hash of the\n * raw nonce must match the nonce field in the ID token.\n */\n rawNonce?: string;\n}\n\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nexport abstract class BaseOAuthProvider\n extends FederatedAuthProvider\n implements AuthProvider\n{\n /** @internal */\n private scopes: string[] = [];\n\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope: string): AuthProvider {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes(): string[] {\n return [...this.scopes];\n }\n}\n\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: object | string): OAuthCredential {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert(\n 'providerId' in obj && 'signInMethod' in obj,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return OAuthCredential._fromParams(obj);\n }\n\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params: OAuthCredentialOptions): OAuthCredential {\n return this._credential({ ...params, nonce: params.rawNonce });\n }\n\n /** An internal credential method that accepts more permissive options */\n private _credential(\n params: Omit\n ): OAuthCredential {\n _assert(params.idToken || params.accessToken, AuthErrorCode.ARGUMENT_ERROR);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static oauthCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce,\n providerId\n } = tokenResponse as SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n\n if (!providerId) {\n return null;\n }\n\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n } catch (e) {\n return null;\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 { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class FacebookAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.FACEBOOK. */\n static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com' =\n SignInMethod.FACEBOOK;\n /** Always set to {@link ProviderId}.FACEBOOK. */\n static readonly PROVIDER_ID: 'facebook.com' = ProviderId.FACEBOOK;\n\n constructor() {\n super(ProviderId.FACEBOOK);\n }\n\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\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 { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class GoogleAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GOOGLE. */\n static readonly GOOGLE_SIGN_IN_METHOD: 'google.com' = SignInMethod.GOOGLE;\n /** Always set to {@link ProviderId}.GOOGLE. */\n static readonly PROVIDER_ID: 'google.com' = ProviderId.GOOGLE;\n\n constructor() {\n super(ProviderId.GOOGLE);\n this.addScope('profile');\n }\n\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(\n idToken?: string | null,\n accessToken?: string | null\n ): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { oauthIdToken, oauthAccessToken } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n } catch {\n return null;\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 { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class GithubAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GITHUB. */\n static readonly GITHUB_SIGN_IN_METHOD: 'github.com' = SignInMethod.GITHUB;\n /** Always set to {@link ProviderId}.GITHUB. */\n static readonly PROVIDER_ID: 'github.com' = ProviderId.GITHUB;\n\n constructor() {\n super(ProviderId.GITHUB);\n }\n\n /**\n * Creates a credential for Github.\n *\n * @param accessToken - Github access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\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/**\n * Represents the SAML credentials returned by an {@link SAMLAuthProvider}.\n *\n * @public\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\n/**\n * @public\n */\nexport class SAMLAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n providerId: string,\n private readonly pendingToken: string\n ) {\n super(providerId, providerId);\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n signInMethod: this.signInMethod,\n providerId: this.providerId,\n pendingToken: this.pendingToken\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): SAMLAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, pendingToken }: Record =\n obj;\n if (\n !providerId ||\n !signInMethod ||\n !pendingToken ||\n providerId !== signInMethod\n ) {\n return null;\n }\n\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n /**\n * Helper static method to avoid exposing the constructor to end users.\n *\n * @internal\n */\n static _create(providerId: string, pendingToken: string): SAMLAuthCredential {\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n return {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true,\n pendingToken: this.pendingToken\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 { FirebaseError } from '@firebase/util';\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredential } from '../../model/public_types';\nimport { UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { SAMLAuthCredential } from '../credentials/saml';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { FederatedAuthProvider } from './federated';\n\nconst SAML_PROVIDER_PREFIX = 'saml.';\n\n/**\n * An {@link AuthProvider} for SAML.\n *\n * @public\n */\nexport class SAMLAuthProvider extends FederatedAuthProvider {\n /**\n * Constructor. The providerId must start with \"saml.\"\n * @param providerId - SAML provider ID.\n */\n constructor(providerId: string) {\n _assert(\n providerId.startsWith(SAML_PROVIDER_PREFIX),\n AuthErrorCode.ARGUMENT_ERROR\n );\n super(providerId);\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\n * successful SAML flow completes.\n *\n * @remarks\n *\n * For example, to get an {@link AuthCredential}, you could write the\n * following code:\n *\n * ```js\n * const userCredential = await signInWithPopup(auth, samlProvider);\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\n * ```\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n /**\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: string | object): AuthCredential {\n const credential = SAMLAuthCredential.fromJSON(json);\n _assert(credential, AuthErrorCode.ARGUMENT_ERROR);\n return credential;\n }\n\n private static samlCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): SAMLAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { pendingToken, providerId } = tokenResponse as SignInWithIdpResponse;\n\n if (!pendingToken || !providerId) {\n return null;\n }\n\n try {\n return SAMLAuthCredential._create(providerId, pendingToken);\n } catch (e) {\n return null;\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/**\n * @license\n * Copyright 2020 Twitter LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nexport class TwitterAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.TWITTER. */\n static readonly TWITTER_SIGN_IN_METHOD: 'twitter.com' = SignInMethod.TWITTER;\n /** Always set to {@link ProviderId}.TWITTER. */\n static readonly PROVIDER_ID: 'twitter.com' = ProviderId.TWITTER;\n\n constructor() {\n super(ProviderId.TWITTER);\n }\n\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token: string, secret: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n } catch {\n return null;\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 {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignUpRequest {\n idToken?: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignUpResponse extends IdTokenResponse {\n displayName?: string;\n email?: string;\n}\n\nexport async function signUp(\n auth: Auth,\n request: SignUpRequest\n): Promise {\n return _performSignInRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n _addTidIfNecessary(auth, request)\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 { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { UserImpl } from './user_impl';\nimport { AuthInternal } from '../../model/auth';\nimport { OperationType, ProviderId } from '../../model/enums';\n\ninterface UserCredentialParams {\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse?: PhoneOrOauthTokenResponse;\n readonly operationType: OperationType;\n}\n\nexport class UserCredentialImpl\n implements UserCredentialInternal, UserCredentialParams\n{\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse: PhoneOrOauthTokenResponse | undefined;\n readonly operationType: OperationType;\n\n constructor(params: UserCredentialParams) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n operationType: OperationType,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise {\n const user = await UserImpl._fromIdTokenResponse(\n auth,\n idTokenResponse,\n isAnonymous\n );\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n\n static async _forOperation(\n user: UserInternal,\n operationType: OperationType,\n response: PhoneOrOauthTokenResponse\n ): Promise {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\n\nfunction providerIdForResponse(\n response: IdTokenResponse\n): ProviderId | string | null {\n if (response.providerId) {\n return response.providerId;\n }\n\n if ('phoneNumber' in response) {\n return ProviderId.PHONE;\n }\n\n return null;\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 { Auth, UserCredential } from '../../model/public_types';\nimport { signUp } from '../../api/authentication/sign_up';\nimport { UserInternal } from '../../model/user';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\n/**\n * Asynchronously signs in as an anonymous user.\n *\n * @remarks\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\n * new anonymous user identity will be created and returned.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport async function signInAnonymously(auth: Auth): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n await authInternal._initializationPromise;\n if (authInternal.currentUser?.isAnonymous) {\n // If an anonymous user is already signed in, no need to sign them in again.\n return new UserCredentialImpl({\n user: authInternal.currentUser as UserInternal,\n providerId: null,\n operationType: OperationType.SIGN_IN\n });\n }\n const response = await signUp(authInternal, {\n returnSecureToken: true\n });\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response,\n true\n );\n await authInternal._updateCurrentUser(userCredential.user);\n return userCredential;\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 { MultiFactorError as MultiFactorErrorPublic } from '../model/public_types';\nimport { FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../model/auth';\nimport { IdTokenResponse } from '../model/id_token';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserInternal } from '../model/user';\nimport { AuthCredential } from '../core/credentials';\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { OperationType } from '../model/enums';\n\nexport type MultiFactorErrorData = MultiFactorErrorPublic['customData'] & {\n _serverResponse: IdTokenMfaResponse;\n};\n\nexport class MultiFactorError\n extends FirebaseError\n implements MultiFactorErrorPublic\n{\n readonly customData: MultiFactorErrorData;\n\n private constructor(\n auth: AuthInternal,\n error: FirebaseError,\n readonly operationType: OperationType,\n readonly user?: UserInternal\n ) {\n super(error.code, error.message);\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 Object.setPrototypeOf(this, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData!._serverResponse as IdTokenMfaResponse,\n operationType\n };\n }\n\n static _fromErrorAndOperation(\n auth: AuthInternal,\n error: FirebaseError,\n operationType: OperationType,\n user?: UserInternal\n ): MultiFactorError {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\n\nexport function _processCredentialSavingMfaContextIfNecessary(\n auth: AuthInternal,\n operationType: OperationType,\n credential: AuthCredential,\n user?: UserInternal\n): Promise {\n const idTokenProvider =\n operationType === OperationType.REAUTHENTICATE\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${AuthErrorCode.MFA_REQUIRED}`) {\n throw MultiFactorError._fromErrorAndOperation(\n auth,\n error,\n operationType,\n user\n );\n }\n\n throw error;\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\nexport interface ProviderAssociatedObject {\n providerId?: string;\n}\n\n/**\n * Takes a set of UserInfo provider data and converts it to a set of names\n */\nexport function providerDataAsNames(\n providerData: T[]\n): Set {\n return new Set(\n providerData\n .map(({ providerId }) => providerId)\n .filter(pid => !!pid) as string[]\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\nimport { User } from '../../model/public_types';\n\nimport { deleteLinkedAccounts } from '../../api/account_management/account';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { providerDataAsNames } from '../util/providers';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { _reloadWithoutSaving } from './reload';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType, ProviderId } from '../../model/enums';\n\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nexport async function unlink(user: User, providerId: string): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n\n userInternal.providerData = userInternal.providerData.filter(pd =>\n providersLeft.has(pd.providerId)\n );\n if (!providersLeft.has(ProviderId.PHONE)) {\n userInternal.phoneNumber = null;\n }\n\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\n\nexport async function _link(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const response = await _logoutIfInvalidated(\n user,\n credential._linkToIdToken(user.auth, await user.getIdToken()),\n bypassAuthState\n );\n return UserCredentialImpl._forOperation(user, OperationType.LINK, response);\n}\n\nexport async function _assertLinkedStatus(\n expected: boolean,\n user: UserInternal,\n provider: string\n): Promise {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n\n const code =\n expected === false\n ? AuthErrorCode.PROVIDER_ALREADY_LINKED\n : AuthErrorCode.NO_SUCH_PROVIDER;\n _assert(providerIds.has(provider) === expected, user.auth, code);\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 { FirebaseError } from '@firebase/util';\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { OperationType } from '../../model/enums';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert, _fail } from '../util/assert';\nimport { _parseToken } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\nexport async function _reauthenticate(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const { auth } = user;\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const operationType = OperationType.REAUTHENTICATE;\n\n try {\n const response = await _logoutIfInvalidated(\n user,\n _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential,\n user\n ),\n bypassAuthState\n );\n _assert(response.idToken, auth, AuthErrorCode.INTERNAL_ERROR);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, AuthErrorCode.USER_MISMATCH);\n\n return UserCredentialImpl._forOperation(user, operationType, response);\n } catch (e) {\n // Convert user deleted error into user mismatch\n if ((e as FirebaseError)?.code === `auth/${AuthErrorCode.USER_DELETED}`) {\n _fail(auth, AuthErrorCode.USER_MISMATCH);\n }\n throw e;\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 { UserCredential, Auth, User } from '../../model/public_types';\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _assertLinkedStatus, _link } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\nexport async function _signInWithCredential(\n auth: AuthInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const operationType = OperationType.SIGN_IN;\n const response = await _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential\n );\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n auth,\n operationType,\n response\n );\n\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function signInWithCredential(\n auth: Auth,\n credential: AuthCredential\n): Promise {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function linkWithCredential(\n user: User,\n credential: AuthCredential\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n\n return _link(userInternal, credential);\n}\n\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\n * or a `TOKEN_EXPIRED` error.\n *\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function reauthenticateWithCredential(\n user: User,\n credential: AuthCredential\n): Promise {\n return _reauthenticate(getModularInstance(user) as UserInternal, credential);\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithCustomTokenRequest {\n token: string;\n returnSecureToken: boolean;\n tenantId?: string;\n}\n\nexport interface SignInWithCustomTokenResponse extends IdTokenResponse {}\n\nexport async function signInWithCustomToken(\n auth: Auth,\n request: SignInWithCustomTokenRequest\n): Promise {\n return _performSignInRequest<\n SignInWithCustomTokenRequest,\n SignInWithCustomTokenResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN,\n _addTidIfNecessary(auth, request)\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 { Auth, UserCredential } from '../../model/public_types';\n\nimport { signInWithCustomToken as getIdTokenResponse } from '../../api/authentication/custom_token';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n/**\n * Asynchronously signs in using a custom token.\n *\n * @remarks\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\n * be generated by an auth backend using the\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\n *\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param customToken - The custom token to sign in with.\n *\n * @public\n */\nexport async function signInWithCustomToken(\n auth: Auth,\n customToken: string\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n const response: IdTokenResponse = await getIdTokenResponse(authInternal, {\n token: customToken,\n returnSecureToken: true\n });\n const cred = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(cred.user);\n return cred;\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 {\n FactorId,\n MultiFactorInfo,\n PhoneMultiFactorInfo,\n TotpMultiFactorInfo\n} from '../model/public_types';\nimport {\n PhoneMfaEnrollment,\n MfaEnrollment,\n TotpMfaEnrollment\n} from '../api/account_management/mfa';\nimport { AuthErrorCode } from '../core/errors';\nimport { _fail } from '../core/util/assert';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorInfoImpl implements MultiFactorInfo {\n readonly uid: string;\n readonly displayName?: string | null;\n readonly enrollmentTime: string;\n\n protected constructor(readonly factorId: FactorId, response: MfaEnrollment) {\n this.uid = response.mfaEnrollmentId;\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\n this.displayName = response.displayName;\n }\n\n static _fromServerResponse(\n auth: AuthInternal,\n enrollment: MfaEnrollment\n ): MultiFactorInfoImpl {\n if ('phoneInfo' in enrollment) {\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n } else if ('totpInfo' in enrollment) {\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n }\n return _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n}\n\nexport class PhoneMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements PhoneMultiFactorInfo\n{\n readonly phoneNumber: string;\n\n private constructor(response: PhoneMfaEnrollment) {\n super(FactorId.PHONE, response);\n this.phoneNumber = response.phoneInfo;\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): PhoneMultiFactorInfoImpl {\n return new PhoneMultiFactorInfoImpl(enrollment as PhoneMfaEnrollment);\n }\n}\nexport class TotpMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements TotpMultiFactorInfo\n{\n private constructor(response: TotpMfaEnrollment) {\n super(FactorId.TOTP, response);\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): TotpMultiFactorInfoImpl {\n return new TotpMultiFactorInfoImpl(enrollment as TotpMfaEnrollment);\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 { ActionCodeSettings, Auth } from '../../model/public_types';\n\nimport { GetOobCodeRequest } from '../../api/authentication/email_and_password';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\nexport function _setActionCodeSettingsOnRequest(\n auth: Auth,\n request: GetOobCodeRequest,\n actionCodeSettings: ActionCodeSettings\n): void {\n _assert(\n actionCodeSettings.url?.length > 0,\n auth,\n AuthErrorCode.INVALID_CONTINUE_URI\n );\n _assert(\n typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\n actionCodeSettings.dynamicLinkDomain.length > 0,\n auth,\n AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN\n );\n\n request.continueUrl = actionCodeSettings.url;\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\n\n if (actionCodeSettings.iOS) {\n _assert(\n actionCodeSettings.iOS.bundleId.length > 0,\n auth,\n AuthErrorCode.MISSING_IOS_BUNDLE_ID\n );\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\n }\n\n if (actionCodeSettings.android) {\n _assert(\n actionCodeSettings.android.packageName.length > 0,\n auth,\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME\n );\n request.androidInstallApp = actionCodeSettings.android.installApp;\n request.androidMinimumVersionCode =\n actionCodeSettings.android.minimumVersion;\n request.androidPackageName = actionCodeSettings.android.packageName;\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 {\n ActionCodeInfo,\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as account from '../../api/account_management/email_and_password';\nimport * as authentication from '../../api/authentication/email_and_password';\nimport { signUp, SignUpRequest } from '../../api/authentication/sign_up';\nimport { MultiFactorInfoImpl } from '../../mfa/mfa_info';\nimport { EmailAuthProvider } from '../providers/email';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport {\n _assert,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../util/assert';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { _castAuth } from '../auth/auth_impl';\nimport { AuthErrorCode } from '../errors';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\n/**\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\n * cached for the project or tenant.\n *\n * @remarks\n * We only fetch the password policy if the password did not meet policy requirements and\n * there is an existing policy cached. A developer must call validatePassword at least\n * once for the cache to be automatically updated.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @private\n */\nasync function recachePasswordPolicy(auth: Auth): Promise {\n const authInternal = _castAuth(auth);\n if (authInternal._getPasswordPolicyInternal()) {\n await authInternal._updatePasswordPolicy();\n }\n}\n\n/**\n * Sends a password reset email to the given email address. This method does not throw an error when\n * there's no user account with the given email address and\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendPasswordResetEmail(\n auth: Auth,\n email: string,\n actionCodeSettings?: ActionCodeSettings\n): Promise {\n const authInternal = _castAuth(auth);\n const request: authentication.PasswordResetRequest = {\n requestType: ActionCodeOperation.PASSWORD_RESET,\n email,\n clientType: RecaptchaClientType.WEB\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\n }\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n authentication.sendPasswordResetEmail\n );\n}\n\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport async function confirmPasswordReset(\n auth: Auth,\n oobCode: string,\n newPassword: string\n): Promise {\n await account\n .resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n })\n .catch(async error => {\n if (\n error.code ===\n `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n // Do not return the email.\n}\n\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function applyActionCode(\n auth: Auth,\n oobCode: string\n): Promise {\n await account.applyActionCode(getModularInstance(auth), { oobCode });\n}\n\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function checkActionCode(\n auth: Auth,\n oobCode: string\n): Promise {\n const authModular = getModularInstance(auth);\n const response = await account.resetPassword(authModular, { oobCode });\n\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, AuthErrorCode.INTERNAL_ERROR);\n switch (operation) {\n case ActionCodeOperation.EMAIL_SIGNIN:\n break;\n case ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL:\n _assert(response.newEmail, authModular, AuthErrorCode.INTERNAL_ERROR);\n break;\n case ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION:\n _assert(response.mfaInfo, authModular, AuthErrorCode.INTERNAL_ERROR);\n // fall through\n default:\n _assert(response.email, authModular, AuthErrorCode.INTERNAL_ERROR);\n }\n\n // The multi-factor info for revert second factor addition\n let multiFactorInfo: MultiFactorInfoImpl | null = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(\n _castAuth(authModular),\n response.mfaInfo\n );\n }\n\n return {\n data: {\n email:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.newEmail\n : response.email) || null,\n previousEmail:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nexport async function verifyPasswordResetCode(\n auth: Auth,\n code: string\n): Promise {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email!;\n}\n\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * This method is not supported on {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nexport async function createUserWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n const request: SignUpRequest = {\n returnSecureToken: true,\n email,\n password,\n clientType: RecaptchaClientType.WEB\n };\n const signUpResponse: Promise = handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n signUp\n );\n const response = await signUpResponse.catch(error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(userCredential.user);\n\n return userCredential;\n}\n\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match. When\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled, this method fails with \"auth/invalid-credential\" in case of an invalid\n * email/password.\n *\n * This method is not supported on {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nexport function signInWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n return signInWithCredential(\n getModularInstance(auth),\n EmailAuthProvider.credential(email, password)\n ).catch(async error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\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 {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as api from '../../api/authentication/email_and_password';\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthProvider } from '../providers/email';\nimport { _getCurrentUrl } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { getModularInstance } from '@firebase/util';\nimport { _castAuth } from '../auth/auth_impl';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\n/**\n * Sends a sign-in email link to the user with the specified email.\n *\n * @remarks\n * The sign-in operation has to always be completed in the app unlike other out of band email\n * actions (password reset and email verifications). This is because, at the end of the flow,\n * the user is expected to be signed in and their Auth state persisted within the app.\n *\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\n * address and the email link supplied in the email sent to the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param authInternal - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n email: string,\n actionCodeSettings: ActionCodeSettings\n): Promise {\n const authInternal = _castAuth(auth);\n const request: api.EmailSignInRequest = {\n requestType: ActionCodeOperation.EMAIL_SIGNIN,\n email,\n clientType: RecaptchaClientType.WEB\n };\n function setActionCodeSettings(\n request: api.EmailSignInRequest,\n actionCodeSettings: ActionCodeSettings\n ): void {\n _assert(\n actionCodeSettings.handleCodeInApp,\n authInternal,\n AuthErrorCode.ARGUMENT_ERROR\n );\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n authInternal,\n request,\n actionCodeSettings\n );\n }\n }\n setActionCodeSettings(request, actionCodeSettings);\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n api.sendSignInLinkToEmail\n );\n}\n\n/**\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\n *\n * @param auth - The {@link Auth} instance.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport function isSignInWithEmailLink(auth: Auth, emailLink: string): boolean {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n return actionCodeUrl?.operation === ActionCodeOperation.EMAIL_SIGNIN;\n}\n\n/**\n * Asynchronously signs in using an email and sign-in email link.\n *\n * @remarks\n * If no link is passed, the link is inferred from the current URL.\n *\n * Fails with an error if the email address is invalid or OTP in email link expires.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport async function signInWithEmailLink(\n auth: Auth,\n email: string,\n emailLink?: string\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authModular = getModularInstance(auth);\n const credential = EmailAuthProvider.credentialWithLink(\n email,\n emailLink || _getCurrentUrl()\n );\n // Check if the tenant ID in the email link matches the tenant ID on Auth\n // instance.\n _assert(\n credential._tenantId === (authModular.tenantId || null),\n authModular,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n return signInWithCredential(authModular, credential);\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface CreateAuthUriRequest {\n identifier: string;\n continueUri: string;\n tenantId?: string;\n}\n\nexport interface CreateAuthUriResponse {\n signinMethods: string[];\n}\n\nexport async function createAuthUri(\n auth: Auth,\n request: CreateAuthUriRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.CREATE_AUTH_URI,\n _addTidIfNecessary(auth, request)\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 {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n User\n} from '../../model/public_types';\n\nimport {\n createAuthUri,\n CreateAuthUriRequest\n} from '../../api/authentication/create_auth_uri';\nimport * as api from '../../api/authentication/email_and_password';\nimport { UserInternal } from '../../model/user';\nimport { _getCurrentUrl, _isHttpOrHttps } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Gets the list of possible sign in methods for the given email address. This method returns an\n * empty list when\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled, irrespective of the number of authentication methods available for the given email.\n *\n * @remarks\n * This is useful to differentiate methods of sign-in for the same provider, eg.\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\n * {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n *\n * Deprecated. Migrating off of this method is recommended as a security best-practice.\n * Learn more in the Identity Platform documentation for\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}.\n * @public\n */\nexport async function fetchSignInMethodsForEmail(\n auth: Auth,\n email: string\n): Promise {\n // createAuthUri returns an error if continue URI is not http or https.\n // For environments like Cordova, Chrome extensions, native frameworks, file\n // systems, etc, use http://localhost as continue URL.\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\n const request: CreateAuthUriRequest = {\n identifier: email,\n continueUri\n };\n\n const { signinMethods } = await createAuthUri(\n getModularInstance(auth),\n request\n );\n\n return signinMethods || [];\n}\n\n/**\n * Sends a verification email to a user.\n *\n * @remarks\n * The verification process is completed by calling {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendEmailVerification(user, actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendEmailVerification(\n user: User,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_EMAIL,\n idToken\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.sendEmailVerification(userInternal.auth, request);\n\n if (email !== user.email) {\n await user.reload();\n }\n}\n\n/**\n * Sends a verification email to a new email address.\n *\n * @remarks\n * The user's email will be updated to the new one after being verified.\n *\n * If you have a custom email action handler, you can complete the verification process by calling\n * {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param newEmail - The new email address to be verified before update.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function verifyBeforeUpdateEmail(\n user: User,\n newEmail: string,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyAndChangeEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n idToken,\n newEmail\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.verifyAndChangeEmail(userInternal.auth, request);\n\n if (email !== user.email) {\n // If the local copy of the email on user is outdated, reload the\n // user.\n await user.reload();\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 { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface UpdateProfileRequest {\n idToken: string;\n displayName?: string | null;\n photoUrl?: string | null;\n returnSecureToken: boolean;\n}\n\nexport interface UpdateProfileResponse extends IdTokenResponse {\n displayName?: string | null;\n photoUrl?: string | null;\n}\n\nexport async function updateProfile(\n auth: Auth,\n request: UpdateProfileRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n request\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 { User } from '../../model/public_types';\n\nimport {\n updateEmailPassword as apiUpdateEmailPassword,\n UpdateEmailPasswordRequest\n} from '../../api/account_management/email_and_password';\nimport { updateProfile as apiUpdateProfile } from '../../api/account_management/profile';\nimport { UserInternal } from '../../model/user';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\nimport { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';\n\n/**\n * Updates a user's profile data.\n *\n * @param user - The user.\n * @param profile - The profile's `displayName` and `photoURL` to update.\n *\n * @public\n */\nexport async function updateProfile(\n user: User,\n {\n displayName,\n photoURL: photoUrl\n }: { displayName?: string | null; photoURL?: string | null }\n): Promise {\n if (displayName === undefined && photoUrl === undefined) {\n return;\n }\n\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await userInternal.getIdToken();\n const profileRequest = {\n idToken,\n displayName,\n photoUrl,\n returnSecureToken: true\n };\n const response = await _logoutIfInvalidated(\n userInternal,\n apiUpdateProfile(userInternal.auth, profileRequest)\n );\n\n userInternal.displayName = response.displayName || null;\n userInternal.photoURL = response.photoUrl || null;\n\n // Update the password provider as well\n const passwordProvider = userInternal.providerData.find(\n ({ providerId }) => providerId === ProviderId.PASSWORD\n );\n if (passwordProvider) {\n passwordProvider.displayName = userInternal.displayName;\n passwordProvider.photoURL = userInternal.photoURL;\n }\n\n await userInternal._updateTokensIfNecessary(response);\n}\n\n/**\n * Updates the user's email address.\n *\n * @remarks\n * An email will be sent to the original email address (if it was set) that allows to revoke the\n * email address change, in order to protect them from account hijacking.\n *\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newEmail - The new email address.\n *\n * Throws \"auth/operation-not-allowed\" error when\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled.\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\n *\n * @public\n */\nexport function updateEmail(user: User, newEmail: string): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(userInternal.auth)\n );\n }\n return updateEmailOrPassword(userInternal, newEmail, null);\n}\n\n/**\n * Updates the user's password.\n *\n * @remarks\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport function updatePassword(user: User, newPassword: string): Promise {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n null,\n newPassword\n );\n}\n\nasync function updateEmailOrPassword(\n user: UserInternal,\n email: string | null,\n password: string | null\n): Promise {\n const { auth } = user;\n const idToken = await user.getIdToken();\n const request: UpdateEmailPasswordRequest = {\n idToken,\n returnSecureToken: true\n };\n\n if (email) {\n request.email = email;\n }\n\n if (password) {\n request.password = password;\n }\n\n const response = await _logoutIfInvalidated(\n user,\n apiUpdateEmailPassword(auth, request)\n );\n await user._updateTokensIfNecessary(response, /* reload */ true);\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 { AdditionalUserInfo, UserCredential } from '../../model/public_types';\nimport { IdTokenResponse, IdTokenResponseKind } from '../../model/id_token';\nimport { _parseToken } from './id_token_result';\nimport { UserCredentialInternal } from '../../model/user';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Parse the `AdditionalUserInfo` from the ID token response.\n *\n */\nexport function _fromIdTokenResponse(\n idTokenResponse?: IdTokenResponse\n): AdditionalUserInfo | null {\n if (!idTokenResponse) {\n return null;\n }\n const { providerId } = idTokenResponse;\n const profile = idTokenResponse.rawUserInfo\n ? JSON.parse(idTokenResponse.rawUserInfo)\n : {};\n const isNewUser =\n idTokenResponse.isNewUser ||\n idTokenResponse.kind === IdTokenResponseKind.SignupNewUser;\n if (!providerId && idTokenResponse?.idToken) {\n const signInProvider = _parseToken(idTokenResponse.idToken)?.firebase?.[\n 'sign_in_provider'\n ];\n if (signInProvider) {\n const filteredProviderId =\n signInProvider !== ProviderId.ANONYMOUS &&\n signInProvider !== ProviderId.CUSTOM\n ? (signInProvider as ProviderId)\n : null;\n // Uses generic class in accordance with the legacy SDK.\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\n }\n }\n if (!providerId) {\n return null;\n }\n switch (providerId) {\n case ProviderId.FACEBOOK:\n return new FacebookAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GITHUB:\n return new GithubAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GOOGLE:\n return new GoogleAdditionalUserInfo(isNewUser, profile);\n case ProviderId.TWITTER:\n return new TwitterAdditionalUserInfo(\n isNewUser,\n profile,\n idTokenResponse.screenName || null\n );\n case ProviderId.CUSTOM:\n case ProviderId.ANONYMOUS:\n return new GenericAdditionalUserInfo(isNewUser, null);\n default:\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\n }\n}\n\nclass GenericAdditionalUserInfo implements AdditionalUserInfo {\n constructor(\n readonly isNewUser: boolean,\n readonly providerId: ProviderId | string | null,\n readonly profile: Record = {}\n ) {}\n}\n\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\n constructor(\n isNewUser: boolean,\n providerId: ProviderId,\n profile: Record,\n readonly username: string | null\n ) {\n super(isNewUser, providerId, profile);\n }\n}\n\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record) {\n super(isNewUser, ProviderId.FACEBOOK, profile);\n }\n}\n\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(isNewUser: boolean, profile: Record) {\n super(\n isNewUser,\n ProviderId.GITHUB,\n profile,\n typeof profile?.login === 'string' ? profile?.login : null\n );\n }\n}\n\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record) {\n super(isNewUser, ProviderId.GOOGLE, profile);\n }\n}\n\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(\n isNewUser: boolean,\n profile: Record,\n screenName: string | null\n ) {\n super(isNewUser, ProviderId.TWITTER, profile, screenName);\n }\n}\n\n/**\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\n *\n * @param userCredential - The user credential.\n *\n * @public\n */\nexport function getAdditionalUserInfo(\n userCredential: UserCredential\n): AdditionalUserInfo | null {\n const { user, _tokenResponse } = userCredential as UserCredentialInternal;\n if (user.isAnonymous && !_tokenResponse) {\n // Handle the special case where signInAnonymously() gets called twice.\n // No network call is made so there's nothing to actually fill this in\n return {\n providerId: null,\n isNewUser: false,\n profile: null\n };\n }\n\n return _fromIdTokenResponse(_tokenResponse);\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 } from '@firebase/util';\nimport {\n Auth,\n NextOrObserver,\n Persistence,\n User,\n CompleteFn,\n ErrorFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../model/public_types';\nimport { _initializeRecaptchaConfig } from '../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { _castAuth } from '../core/auth/auth_impl';\n\nexport {\n debugErrorMap,\n prodErrorMap,\n AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as AuthErrorCodes\n} from './errors';\n\n// Non-optional auth methods.\n/**\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\n * `Auth` session and applies this type of persistence for future sign-in requests, including\n * sign-in with redirect requests.\n *\n * @remarks\n * This makes it easy for a user signing in to specify whether their session should be\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\n * that are shared by other users or have sensitive data.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * setPersistence(auth, browserSessionPersistence);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param persistence - The {@link Persistence} to use.\n * @returns A `Promise` that resolves once the persistence change has completed\n *\n * @public\n */\nexport function setPersistence(\n auth: Auth,\n persistence: Persistence\n): Promise {\n return getModularInstance(auth).setPersistence(persistence);\n}\n\n/**\n * Loads the reCAPTCHA configuration into the `Auth` instance.\n *\n * @remarks\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\n * verification flow should be triggered for each auth provider, into the\n * current Auth session.\n *\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\n * auth flows.\n *\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * initializeRecaptchaConfig(auth);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function initializeRecaptchaConfig(auth: Auth): Promise {\n return _initializeRecaptchaConfig(auth);\n}\n\n/**\n * Validates the password against the password policy configured for the project or tenant.\n *\n * @remarks\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\n * policy configured for the project. Otherwise, this method will use the policy configured\n * for the tenant. If a password policy has not been configured, then the default policy\n * configured for all projects will be used.\n *\n * If an auth flow fails because a submitted password does not meet the password policy\n * requirements and this method has previously been called, then this method will use the\n * most recent policy available when called again.\n *\n * @example\n * ```javascript\n * validatePassword(auth, 'some-password');\n * ```\n *\n * @param auth The {@link Auth} instance.\n * @param password The password to validate.\n *\n * @public\n */\nexport async function validatePassword(\n auth: Auth,\n password: string\n): Promise {\n const authInternal = _castAuth(auth);\n return authInternal.validatePassword(password);\n}\n\n/**\n * Adds an observer for changes to the signed-in user's ID token.\n *\n * @remarks\n * This includes sign-in, sign-out, and token refresh events.\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onIdTokenChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onIdTokenChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Adds a blocking callback that runs before an auth state change\n * sets a new user.\n *\n * @param auth - The {@link Auth} instance.\n * @param callback - callback triggered before new user value is set.\n * If this throws, it blocks the user from being set.\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\n * callback throws, allowing you to undo any side effects.\n */\nexport function beforeAuthStateChanged(\n auth: Auth,\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n): Unsubscribe {\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\n}\n/**\n * Adds an observer for changes to the user's sign-in state.\n *\n * @remarks\n * To keep the old behavior, see {@link onIdTokenChanged}.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onAuthStateChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onAuthStateChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Sets the current language to the default device/browser preference.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function useDeviceLanguage(auth: Auth): void {\n getModularInstance(auth).useDeviceLanguage();\n}\n/**\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\n * {@link Auth} instance.\n *\n * @remarks\n * A new instance copy of the user provided will be made and set as currentUser.\n *\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\n * like other sign in methods.\n *\n * The operation fails with an error if the user to be updated belongs to a different Firebase\n * project.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param user - The new {@link User}.\n *\n * @public\n */\nexport function updateCurrentUser(\n auth: Auth,\n user: User | null\n): Promise {\n return getModularInstance(auth).updateCurrentUser(user);\n}\n/**\n * Signs out the current user.\n *\n * @remarks\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function signOut(auth: Auth): Promise {\n return getModularInstance(auth).signOut();\n}\n\n/**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n *\n * @param auth - The {@link Auth} instance.\n * @param token - The Apple OAuth access token.\n *\n * @public\n */\nexport function revokeAccessToken(auth: Auth, token: string): Promise {\n const authInternal = _castAuth(auth);\n return authInternal.revokeAccessToken(token);\n}\n\nexport { initializeAuth } from './auth/initialize';\nexport { connectAuthEmulator } from './auth/emulator';\n\n// credentials\nexport { AuthCredential } from './credentials';\nexport { EmailAuthCredential } from './credentials/email';\nexport { OAuthCredential } from './credentials/oauth';\nexport { PhoneAuthCredential } from './credentials/phone';\n\n// persistence\nexport { inMemoryPersistence } from './persistence/in_memory';\n\n// providers\nexport { EmailAuthProvider } from './providers/email';\nexport { FacebookAuthProvider } from './providers/facebook';\nexport { CustomParameters } from './providers/federated';\nexport { GoogleAuthProvider } from './providers/google';\nexport { GithubAuthProvider } from './providers/github';\nexport { OAuthProvider, OAuthCredentialOptions } from './providers/oauth';\nexport { SAMLAuthProvider } from './providers/saml';\nexport { TwitterAuthProvider } from './providers/twitter';\n\n// strategies\nexport { signInAnonymously } from './strategies/anonymous';\nexport {\n signInWithCredential,\n linkWithCredential,\n reauthenticateWithCredential\n} from './strategies/credential';\nexport { signInWithCustomToken } from './strategies/custom_token';\nexport {\n sendPasswordResetEmail,\n confirmPasswordReset,\n applyActionCode,\n checkActionCode,\n verifyPasswordResetCode,\n createUserWithEmailAndPassword,\n signInWithEmailAndPassword\n} from './strategies/email_and_password';\nexport {\n sendSignInLinkToEmail,\n isSignInWithEmailLink,\n signInWithEmailLink\n} from './strategies/email_link';\nexport {\n fetchSignInMethodsForEmail,\n sendEmailVerification,\n verifyBeforeUpdateEmail\n} from './strategies/email';\n\n// core\nexport { ActionCodeURL, parseActionCodeURL } from './action_code_url';\n\n// user\nexport {\n updateProfile,\n updateEmail,\n updatePassword\n} from './user/account_info';\nexport { getIdToken, getIdTokenResult } from './user/id_token_result';\nexport { unlink } from './user/link_unlink';\nexport { getAdditionalUserInfo } from './user/additional_user_info';\n\n// Non-optional user methods.\nexport { reload } from './user/reload';\n/**\n * Deletes and signs out the user.\n *\n * @remarks\n * Important: this is a security-sensitive operation that requires the user to have recently\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function deleteUser(user: User): Promise {\n return getModularInstance(user).delete();\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 { UserInternal } from '../model/user';\nimport { MultiFactorSession } from '../model/public_types';\n\nexport const enum MultiFactorSessionType {\n ENROLL = 'enroll',\n SIGN_IN = 'signin'\n}\n\ninterface SerializedMultiFactorSession {\n multiFactorSession: {\n idToken?: string;\n pendingCredential?: string;\n };\n}\n\nexport class MultiFactorSessionImpl implements MultiFactorSession {\n private constructor(\n readonly type: MultiFactorSessionType,\n readonly credential: string,\n readonly user?: UserInternal\n ) {}\n\n static _fromIdtoken(\n idToken: string,\n user?: UserInternal\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.ENROLL,\n idToken,\n user\n );\n }\n\n static _fromMfaPendingCredential(\n mfaPendingCredential: string\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.SIGN_IN,\n mfaPendingCredential\n );\n }\n\n toJSON(): SerializedMultiFactorSession {\n const key =\n this.type === MultiFactorSessionType.ENROLL\n ? 'idToken'\n : 'pendingCredential';\n return {\n multiFactorSession: {\n [key]: this.credential\n }\n };\n }\n\n static fromJSON(\n obj: Partial\n ): MultiFactorSessionImpl | null {\n if (obj?.multiFactorSession) {\n if (obj.multiFactorSession?.pendingCredential) {\n return MultiFactorSessionImpl._fromMfaPendingCredential(\n obj.multiFactorSession.pendingCredential\n );\n } else if (obj.multiFactorSession?.idToken) {\n return MultiFactorSessionImpl._fromIdtoken(\n obj.multiFactorSession.idToken\n );\n }\n }\n return null;\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 {\n Auth,\n MultiFactorResolver,\n UserCredential,\n MultiFactorError\n} from '../model/public_types';\n\nimport { _castAuth } from '../core/auth/auth_impl';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserCredentialImpl } from '../core/user/user_credential_impl';\nimport { _assert, _fail } from '../core/util/assert';\nimport { UserCredentialInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorError as MultiFactorErrorInternal } from './mfa_error';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../model/enums';\n\nexport class MultiFactorResolverImpl implements MultiFactorResolver {\n private constructor(\n readonly session: MultiFactorSessionImpl,\n readonly hints: MultiFactorInfoImpl[],\n private readonly signInResolver: (\n assertion: MultiFactorAssertionImpl\n ) => Promise\n ) {}\n\n /** @internal */\n static _fromError(\n authExtern: Auth,\n error: MultiFactorErrorInternal\n ): MultiFactorResolverImpl {\n const auth = _castAuth(authExtern);\n const serverResponse = error.customData._serverResponse;\n const hints = (serverResponse.mfaInfo || []).map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(auth, enrollment)\n );\n\n _assert(\n serverResponse.mfaPendingCredential,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(\n serverResponse.mfaPendingCredential\n );\n\n return new MultiFactorResolverImpl(\n session,\n hints,\n async (\n assertion: MultiFactorAssertionImpl\n ): Promise => {\n const mfaResponse = await assertion._process(auth, session);\n // Clear out the unneeded fields from the old login response\n delete serverResponse.mfaInfo;\n delete serverResponse.mfaPendingCredential;\n\n // Use in the new token & refresh token in the old response\n const idTokenResponse = {\n ...serverResponse,\n idToken: mfaResponse.idToken,\n refreshToken: mfaResponse.refreshToken\n };\n\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\n switch (error.operationType) {\n case OperationType.SIGN_IN:\n const userCredential =\n await UserCredentialImpl._fromIdTokenResponse(\n auth,\n error.operationType,\n idTokenResponse\n );\n await auth._updateCurrentUser(userCredential.user);\n return userCredential;\n case OperationType.REAUTHENTICATE:\n _assert(error.user, auth, AuthErrorCode.INTERNAL_ERROR);\n return UserCredentialImpl._forOperation(\n error.user,\n error.operationType,\n idTokenResponse\n );\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n );\n }\n\n async resolveSignIn(\n assertionExtern: MultiFactorAssertionImpl\n ): Promise {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n return this.signInResolver(assertion);\n }\n}\n\n/**\n * Provides a {@link MultiFactorResolver} suitable for completion of a\n * multi-factor flow.\n *\n * @param auth - The {@link Auth} instance.\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\n * reauthentication operation.\n *\n * @public\n */\nexport function getMultiFactorResolver(\n auth: Auth,\n error: MultiFactorError\n): MultiFactorResolver {\n const authModular = getModularInstance(auth);\n const errorInternal = error as MultiFactorErrorInternal;\n _assert(\n error.customData.operationType,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n errorInternal.customData._serverResponse?.mfaPendingCredential,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\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 {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { SignInWithPhoneNumberRequest } from '../authentication/sms';\nimport { FinalizeMfaResponse } from '../authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\n\n/**\n * MFA Info as returned by the API.\n */\ninterface BaseMfaEnrollment {\n mfaEnrollmentId: string;\n enrolledAt: number;\n displayName?: string;\n}\n\n/**\n * An MFA provided by SMS verification.\n */\nexport interface PhoneMfaEnrollment extends BaseMfaEnrollment {\n phoneInfo: string;\n}\n\n/**\n * An MFA provided by TOTP (Time-based One Time Password).\n */\nexport interface TotpMfaEnrollment extends BaseMfaEnrollment {}\n\n/**\n * MfaEnrollment can be any subtype of BaseMfaEnrollment, currently only PhoneMfaEnrollment and TotpMfaEnrollment are supported.\n */\nexport type MfaEnrollment = PhoneMfaEnrollment | TotpMfaEnrollment;\n\nexport interface StartPhoneMfaEnrollmentRequest {\n idToken: string;\n phoneEnrollmentInfo: {\n phoneNumber: string;\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaEnrollmentResponse {\n phoneSessionInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startEnrollPhoneMfa(\n auth: AuthInternal,\n request: StartPhoneMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n StartPhoneMfaEnrollmentRequest,\n StartPhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaEnrollmentRequest {\n idToken: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollPhoneMfa(\n auth: AuthInternal,\n request: FinalizePhoneMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n FinalizePhoneMfaEnrollmentRequest,\n FinalizePhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface StartTotpMfaEnrollmentRequest {\n idToken: string;\n totpEnrollmentInfo: {};\n tenantId?: string;\n}\n\nexport interface StartTotpMfaEnrollmentResponse {\n totpSessionInfo: {\n sharedSecretKey: string;\n verificationCodeLength: number;\n hashingAlgorithm: string;\n periodSec: number;\n sessionInfo: string;\n finalizeEnrollmentTime: number;\n };\n}\n\nexport function startEnrollTotpMfa(\n auth: AuthInternal,\n request: StartTotpMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n StartTotpMfaEnrollmentRequest,\n StartTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface TotpVerificationInfo {\n sessionInfo: string;\n verificationCode: string;\n}\nexport interface FinalizeTotpMfaEnrollmentRequest {\n idToken: string;\n totpVerificationInfo: TotpVerificationInfo;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizeTotpMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollTotpMfa(\n auth: AuthInternal,\n request: FinalizeTotpMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n FinalizeTotpMfaEnrollmentRequest,\n FinalizeTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface WithdrawMfaRequest {\n idToken: string;\n mfaEnrollmentId: string;\n tenantId?: string;\n}\n\nexport interface WithdrawMfaResponse extends FinalizeMfaResponse {}\n\nexport function withdrawMfa(\n auth: AuthInternal,\n request: WithdrawMfaRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.WITHDRAW_MFA,\n _addTidIfNecessary(auth, request)\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 */\nimport {\n MultiFactorAssertion,\n MultiFactorInfo,\n MultiFactorSession,\n MultiFactorUser,\n User\n} from '../model/public_types';\n\nimport { withdrawMfa } from '../api/account_management/mfa';\nimport { _logoutIfInvalidated } from '../core/user/invalidation';\nimport { UserInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\n\nexport class MultiFactorUserImpl implements MultiFactorUser {\n enrolledFactors: MultiFactorInfo[] = [];\n\n private constructor(readonly user: UserInternal) {\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment)\n );\n }\n });\n }\n\n static _fromUser(user: UserInternal): MultiFactorUserImpl {\n return new MultiFactorUserImpl(user);\n }\n\n async getSession(): Promise {\n return MultiFactorSessionImpl._fromIdtoken(\n await this.user.getIdToken(),\n this.user\n );\n }\n\n async enroll(\n assertionExtern: MultiFactorAssertion,\n displayName?: string | null\n ): Promise {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n const session = (await this.getSession()) as MultiFactorSessionImpl;\n const finalizeMfaResponse = await _logoutIfInvalidated(\n this.user,\n assertion._process(this.user.auth, session, displayName)\n );\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n\n async unenroll(infoOrUid: MultiFactorInfo | string): Promise {\n const mfaEnrollmentId =\n typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n try {\n const idTokenResponse = await _logoutIfInvalidated(\n this.user,\n withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n })\n );\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(\n ({ uid }) => uid !== mfaEnrollmentId\n );\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n await this.user.reload();\n } catch (e) {\n throw e;\n }\n }\n}\n\nconst multiFactorUserCache = new WeakMap();\n\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nexport function multiFactor(user: User): MultiFactorUser {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(\n userModular,\n MultiFactorUserImpl._fromUser(userModular as UserInternal)\n );\n }\n return multiFactorUserCache.get(userModular)!;\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 */\nimport { Persistence } from '../../model/public_types';\n\nexport const enum PersistenceType {\n SESSION = 'SESSION',\n LOCAL = 'LOCAL',\n NONE = 'NONE'\n}\n\nexport type PersistedBlob = Record;\n\nexport interface Instantiator {\n (blob: PersistedBlob): T;\n}\n\nexport type PersistenceValue = PersistedBlob | string;\n\nexport const STORAGE_AVAILABLE_KEY = '__sak';\n\nexport interface StorageEventListener {\n (value: PersistenceValue | null): void;\n}\n\nexport interface PersistenceInternal extends Persistence {\n type: PersistenceType;\n _isAvailable(): Promise;\n _set(key: string, value: PersistenceValue): Promise;\n _get(key: string): Promise;\n _remove(key: string): Promise;\n _addListener(key: string, listener: StorageEventListener): void;\n _removeListener(key: string, listener: StorageEventListener): void;\n // Should this persistence allow migration up the chosen hierarchy?\n _shouldAllowMigration?: boolean;\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 {\n PersistenceValue,\n STORAGE_AVAILABLE_KEY,\n PersistenceType\n} from '../../core/persistence';\n\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\n\nexport abstract class BrowserPersistenceClass {\n protected constructor(\n protected readonly storageRetriever: () => Storage,\n readonly type: PersistenceType\n ) {}\n\n _isAvailable(): Promise {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n _set(key: string, value: PersistenceValue): Promise {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n\n _get(key: string): Promise {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n\n _remove(key: string): Promise {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n\n protected get storage(): Storage {\n return this.storageRetriever();\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 { Persistence } from '../../model/public_types';\n\nimport { getUA } from '@firebase/util';\nimport {\n _isSafari,\n _isIOS,\n _isIframe,\n _isMobileBrowser,\n _isIE10\n} from '../../core/util/browser';\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nfunction _iframeCannotSyncWebStorage(): boolean {\n const ua = getUA();\n return _isSafari(ua) || _isIOS(ua);\n}\n\n// The polling period in case events are not supported\nexport const _POLLING_INTERVAL_MS = 1000;\n\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\nclass BrowserLocalPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'LOCAL' = 'LOCAL';\n\n constructor() {\n super(() => window.localStorage, PersistenceType.LOCAL);\n }\n\n private readonly boundEventHandler = (\n event: StorageEvent,\n poll?: boolean\n ): void => this.onStorageEvent(event, poll);\n private readonly listeners: Record> = {};\n private readonly localCache: Record = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n\n // Safari or iOS browser and embedded in an iframe.\n private readonly safariLocalStorageNotSynced =\n _iframeCannotSyncWebStorage() && _isIframe();\n // Whether to use polling instead of depending on window events\n private readonly fallbackToPolling = _isMobileBrowser();\n readonly _shouldAllowMigration = true;\n\n private forAllChangedKeys(\n cb: (key: string, oldValue: string | null, newValue: string | null) => void\n ): void {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n\n private onStorageEvent(event: StorageEvent, poll = false): void {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys(\n (key: string, _oldValue: string | null, newValue: string | null) => {\n this.notifyListeners(key, newValue);\n }\n );\n return;\n }\n\n const key = event.key;\n\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n\n // Safari embedded iframe. Storage event will trigger with the delta\n // changes but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced) {\n // Get current iframe page value.\n const storedValue = this.storage.getItem(key);\n // Value not synchronized, synchronize manually.\n if (event.newValue !== storedValue) {\n if (event.newValue !== null) {\n // Value changed from current value.\n this.storage.setItem(key, event.newValue);\n } else {\n // Current value deleted.\n this.storage.removeItem(key);\n }\n } else if (this.localCache[key] === event.newValue && !poll) {\n // Already detected and processed, do not trigger listeners again.\n return;\n }\n }\n\n const triggerListeners = (): void => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n this.notifyListeners(key, storedValue);\n };\n\n const storedValue = this.storage.getItem(key);\n if (\n _isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue\n ) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n }\n\n private notifyListeners(key: string, value: string | null): void {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys(\n (key: string, oldValue: string | null, newValue: string | null) => {\n this.onStorageEvent(\n new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }),\n /* poll */ true\n );\n }\n );\n }, _POLLING_INTERVAL_MS);\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n private attachListener(): void {\n window.addEventListener('storage', this.boundEventHandler);\n }\n\n private detachListener(): void {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in some mobile browsers. A localStorage change in the foreground window\n // will not be detected in the background window via the storage event.\n // This was detected in iOS 7.x mobile browsers\n if (this.fallbackToPolling) {\n this.startPolling();\n } else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n\n // Update local cache on base operations:\n\n async _set(key: string, value: PersistenceValue): Promise {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n\n async _get(key: string): Promise {\n const value = await super._get(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n\n async _remove(key: string): Promise {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserLocalPersistence: Persistence = BrowserLocalPersistence;\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 { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nclass BrowserSessionPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'SESSION' = 'SESSION';\n\n constructor() {\n super(() => window.sessionStorage, PersistenceType.SESSION);\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserSessionPersistence: Persistence = BrowserSessionPersistence;\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/** TODO: remove this once tslib has a polyfill for Promise.allSettled */\ninterface PromiseFulfilledResult {\n fulfilled: true;\n value: T;\n}\n\ninterface PromiseRejectedResult {\n fulfilled: false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any;\n}\n\nexport type PromiseSettledResult =\n | PromiseFulfilledResult\n | PromiseRejectedResult;\n\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nexport function _allSettled(\n promises: Array>\n): Promise>> {\n return Promise.all(\n promises.map(async promise => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n } as PromiseFulfilledResult;\n } catch (reason) {\n return {\n fulfilled: false,\n reason\n } as PromiseRejectedResult;\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\nimport {\n ReceiverHandler,\n _EventType,\n _ReceiverResponse,\n SenderMessageEvent,\n _Status,\n _SenderRequest\n} from './index';\nimport { _allSettled } from './promise';\n\n/**\n * Interface class for receiving messages.\n *\n */\nexport class Receiver {\n private static readonly receivers: Receiver[] = [];\n private readonly boundEventHandler: EventListener;\n\n private readonly handlersMap: {\n // Typescript doesn't have existential types :(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [eventType: string]: Set>;\n } = {};\n\n constructor(private readonly eventTarget: EventTarget) {\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget: EventTarget): Receiver {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n const existingInstance = this.receivers.find(receiver =>\n receiver.isListeningto(eventTarget)\n );\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n\n private isListeningto(eventTarget: EventTarget): boolean {\n return this.eventTarget === eventTarget;\n }\n\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n private async handleEvent<\n T extends _ReceiverResponse,\n S extends _SenderRequest\n >(event: Event): Promise {\n const messageEvent = event as MessageEvent>;\n const { eventId, eventType, data } = messageEvent.data;\n\n const handlers: Set> | undefined =\n this.handlersMap[eventType];\n if (!handlers?.size) {\n return;\n }\n\n messageEvent.ports[0].postMessage({\n status: _Status.ACK,\n eventId,\n eventType\n });\n\n const promises = Array.from(handlers).map(async handler =>\n handler(messageEvent.origin, data)\n );\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: _Status.DONE,\n eventId,\n eventType,\n response\n });\n }\n\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe(\n eventType: _EventType,\n eventHandler: ReceiverHandler\n ): void {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n\n this.handlersMap[eventType].add(eventHandler);\n }\n\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe(\n eventType: _EventType,\n eventHandler?: ReceiverHandler\n ): void {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\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\nexport function _generateEventId(prefix = '', digits = 10): string {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\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 { _generateEventId } from '../../core/util/event_id';\nimport {\n _SenderRequest,\n _EventType,\n ReceiverMessageEvent,\n _MessageError,\n SenderMessageEvent,\n _Status,\n _ReceiverMessageResponse,\n _ReceiverResponse,\n _TimeoutDuration\n} from './index';\n\ninterface MessageHandler {\n messageChannel: MessageChannel;\n onMessage: EventListenerOrEventListenerObject;\n}\n\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nexport class Sender {\n private readonly handlers = new Set();\n\n constructor(private readonly target: ServiceWorker) {}\n\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n private removeMessageHandler(handler: MessageHandler): void {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener(\n 'message',\n handler.onMessage\n );\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send(\n eventType: _EventType,\n data: S,\n timeout = _TimeoutDuration.ACK\n ): Promise<_ReceiverMessageResponse> {\n const messageChannel =\n typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(_MessageError.CONNECTION_UNAVAILABLE);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer: any;\n let handler: MessageHandler;\n return new Promise<_ReceiverMessageResponse>((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(_MessageError.UNSUPPORTED_EVENT));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event: Event): void {\n const messageEvent = event as MessageEvent>;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case _Status.ACK:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(_MessageError.TIMEOUT));\n }, _TimeoutDuration.COMPLETION);\n break;\n case _Status.DONE:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(_MessageError.INVALID_RESPONSE));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage(\n {\n eventType,\n eventId,\n data\n } as SenderMessageEvent,\n [messageChannel.port2]\n );\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\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\nimport { Recaptcha, GreCAPTCHATopLevel } from './recaptcha/recaptcha';\n\n/**\n * A specialized window type that melds the normal window type plus the\n * various bits we need. The three different blocks that are &'d together\n * cant be defined in the same block together.\n */\nexport type AuthWindow = {\n // Standard window types\n [T in keyof Window]: Window[T];\n} & {\n // Any known / named properties we want to add\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n ___jsl?: Record;\n gapi?: typeof gapi;\n} & {\n // A final catch-all for callbacks (which will have random names) that\n // we will stick on the window.\n [callback: string]: (...args: unknown[]) => void;\n};\n\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nexport function _window(): AuthWindow {\n return window as unknown as AuthWindow;\n}\n\nexport function _setWindowLocation(url: string): void {\n _window().location.href = url;\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 { _window } from '../auth_window';\n\nexport function _isWorker(): boolean {\n return (\n typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function'\n );\n}\n\nexport async function _getActiveServiceWorker(): Promise {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n } catch {\n return null;\n }\n}\n\nexport function _getServiceWorkerController(): ServiceWorker | null {\n return navigator?.serviceWorker?.controller || null;\n}\n\nexport function _getWorkerGlobalScope(): ServiceWorker | null {\n return _isWorker() ? (self as unknown as ServiceWorker) : null;\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 { Persistence } from '../../model/public_types';\nimport {\n PersistedBlob,\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener,\n STORAGE_AVAILABLE_KEY\n} from '../../core/persistence/';\nimport {\n _EventType,\n _PingResponse,\n KeyChangedResponse,\n KeyChangedRequest,\n PingRequest,\n _TimeoutDuration\n} from '../messagechannel/index';\nimport { Receiver } from '../messagechannel/receiver';\nimport { Sender } from '../messagechannel/sender';\nimport {\n _isWorker,\n _getActiveServiceWorker,\n _getServiceWorkerController,\n _getWorkerGlobalScope\n} from '../util/worker';\n\nexport const DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n\ninterface DBObject {\n [DB_DATA_KEYPATH]: string;\n value: PersistedBlob;\n}\n\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\n *\n */\nclass DBPromise {\n constructor(private readonly request: IDBRequest) {}\n\n toPromise(): Promise {\n return new Promise((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\n\nfunction getObjectStore(db: IDBDatabase, isReadWrite: boolean): IDBObjectStore {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\n\nexport async function _clearDatabase(db: IDBDatabase): Promise {\n const objectStore = getObjectStore(db, true);\n return new DBPromise(objectStore.clear()).toPromise();\n}\n\nexport function _deleteDatabase(): Promise {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise(request).toPromise();\n}\n\nexport function _openDatabase(): Promise {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n } catch (e) {\n reject(e);\n }\n });\n\n request.addEventListener('success', async () => {\n const db: IDBDatabase = request.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n } else {\n resolve(db);\n }\n });\n });\n}\n\nexport async function _putObject(\n db: IDBDatabase,\n key: string,\n value: PersistenceValue | string\n): Promise {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise(request).toPromise();\n}\n\nasync function getObject(\n db: IDBDatabase,\n key: string\n): Promise {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise(request).toPromise();\n return data === undefined ? null : data.value;\n}\n\nexport function _deleteObject(db: IDBDatabase, key: string): Promise {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise(request).toPromise();\n}\n\nexport const _POLLING_INTERVAL_MS = 800;\nexport const _TRANSACTION_RETRY_COUNT = 3;\n\nclass IndexedDBLocalPersistence implements InternalPersistence {\n static type: 'LOCAL' = 'LOCAL';\n\n type = PersistenceType.LOCAL;\n db?: IDBDatabase;\n readonly _shouldAllowMigration = true;\n\n private readonly listeners: Record> = {};\n private readonly localCache: Record = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n private pendingWrites = 0;\n\n private receiver: Receiver | null = null;\n private sender: Sender | null = null;\n private serviceWorkerReceiverAvailable = false;\n private activeServiceWorker: ServiceWorker | null = null;\n // Visible for testing only\n readonly _workerInitializationPromise: Promise;\n\n constructor() {\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(\n () => {},\n () => {}\n );\n }\n\n async _openDb(): Promise {\n if (this.db) {\n return this.db;\n }\n this.db = await _openDatabase();\n return this.db;\n }\n\n async _withRetries(op: (db: IDBDatabase) => Promise): Promise {\n let numAttempts = 0;\n\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n } catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.db) {\n this.db.close();\n this.db = undefined;\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n private async initializeServiceWorkerMessaging(): Promise {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n\n /**\n * As the worker we should listen to events from the main window.\n */\n private async initializeReceiver(): Promise {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope()!);\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\n _EventType.KEY_CHANGED,\n async (_origin: string, data: KeyChangedRequest) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n }\n );\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\n _EventType.PING,\n async (_origin: string, _data: PingRequest) => {\n return [_EventType.KEY_CHANGED];\n }\n );\n }\n\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n private async initializeSender(): Promise {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send<_PingResponse, PingRequest>(\n _EventType.PING,\n {},\n _TimeoutDuration.LONG_ACK\n );\n if (!results) {\n return;\n }\n if (\n results[0]?.fulfilled &&\n results[0]?.value.includes(_EventType.KEY_CHANGED)\n ) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n private async notifyServiceWorker(key: string): Promise {\n if (\n !this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker\n ) {\n return;\n }\n try {\n await this.sender._send(\n _EventType.KEY_CHANGED,\n { key },\n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? _TimeoutDuration.LONG_ACK\n : _TimeoutDuration.ACK\n );\n } catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n\n async _isAvailable(): Promise {\n try {\n if (!indexedDB) {\n return false;\n }\n const db = await _openDatabase();\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n return true;\n } catch {}\n return false;\n }\n\n private async _withPendingWrite(write: () => Promise): Promise {\n this.pendingWrites++;\n try {\n await write();\n } finally {\n this.pendingWrites--;\n }\n }\n\n async _set(key: string, value: PersistenceValue): Promise {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n\n async _get(key: string): Promise {\n const obj = (await this._withRetries((db: IDBDatabase) =>\n getObject(db, key)\n )) as T;\n this.localCache[key] = obj;\n return obj;\n }\n\n async _remove(key: string): Promise {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n\n private async _poll(): Promise {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db: IDBDatabase) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise(getAllRequest).toPromise();\n });\n\n if (!result) {\n return [];\n }\n\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n\n const keys = [];\n const keysInResult = new Set();\n if (result.length !== 0) {\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value as PersistenceValue);\n keys.push(key);\n }\n }\n }\n\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n\n private notifyListeners(\n key: string,\n newValue: PersistenceValue | null\n ): void {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(\n async () => this._poll(),\n _POLLING_INTERVAL_MS\n );\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n }\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nexport const indexedDBLocalPersistence: Persistence = IndexedDBLocalPersistence;\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 {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from '../account_management/mfa';\nimport { SignInWithIdpResponse } from './idp';\nimport {\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n} from './sms';\n\nexport interface FinalizeMfaResponse {\n idToken: string;\n refreshToken: string;\n}\n\n/**\n * @internal\n */\nexport interface IdTokenMfaResponse extends IdTokenResponse {\n mfaPendingCredential?: string;\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface StartPhoneMfaSignInRequest {\n mfaPendingCredential: string;\n mfaEnrollmentId: string;\n phoneSignInInfo: {\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaSignInResponse {\n phoneResponseInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startSignInPhoneMfa(\n auth: Auth,\n request: StartPhoneMfaSignInRequest\n): Promise {\n return _performApiRequest<\n StartPhoneMfaSignInRequest,\n StartPhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaSignInRequest {\n mfaPendingCredential: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n tenantId?: string;\n}\n\n// TOTP MFA Sign in only has a finalize phase. Phone MFA has a start phase to initiate sending an\n// SMS and a finalize phase to complete sign in. With TOTP, the user already has the OTP in the\n// TOTP/Authenticator app.\nexport interface FinalizeTotpMfaSignInRequest {\n mfaPendingCredential: string;\n totpVerificationInfo: { verificationCode: string };\n tenantId?: string;\n mfaEnrollmentId: string;\n}\n\nexport interface FinalizePhoneMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport interface FinalizeTotpMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport function finalizeSignInPhoneMfa(\n auth: Auth,\n request: FinalizePhoneMfaSignInRequest\n): Promise {\n return _performApiRequest<\n FinalizePhoneMfaSignInRequest,\n FinalizePhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport function finalizeSignInTotpMfa(\n auth: Auth,\n request: FinalizeTotpMfaSignInRequest\n): Promise {\n return _performApiRequest<\n FinalizeTotpMfaSignInRequest,\n FinalizeTotpMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport type PhoneOrOauthTokenResponse =\n | SignInWithPhoneNumberResponse\n | SignInWithIdpResponse\n | IdTokenResponse;\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 { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport { RecaptchaParameters } from '../../model/public_types';\nimport {\n Recaptcha,\n GreCAPTCHATopLevel,\n GreCAPTCHARenderOption,\n GreCAPTCHA\n} from './recaptcha';\n\nexport const _SOLVE_TIME_MS = 500;\nexport const _EXPIRATION_TIME_MS = 60_000;\nexport const _WIDGET_ID_START = 1_000_000_000_000;\n\nexport interface Widget {\n getResponse: () => string | null;\n delete: () => void;\n execute: () => void;\n}\n\nexport class MockReCaptcha implements Recaptcha {\n private counter = _WIDGET_ID_START;\n _widgets = new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n render(\n container: string | HTMLElement,\n parameters?: RecaptchaParameters\n ): number {\n const id = this.counter;\n this._widgets.set(\n id,\n new MockWidget(container, this.auth.name, parameters || {})\n );\n this.counter++;\n return id;\n }\n\n reset(optWidgetId?: number): void {\n const id = optWidgetId || _WIDGET_ID_START;\n void this._widgets.get(id)?.delete();\n this._widgets.delete(id);\n }\n\n getResponse(optWidgetId?: number): string {\n const id = optWidgetId || _WIDGET_ID_START;\n return this._widgets.get(id)?.getResponse() || '';\n }\n\n async execute(optWidgetId?: number | string): Promise {\n const id: number = (optWidgetId as number) || _WIDGET_ID_START;\n void this._widgets.get(id)?.execute();\n return '';\n }\n}\n\nexport class MockGreCAPTCHATopLevel implements GreCAPTCHATopLevel {\n enterprise: GreCAPTCHA = new MockGreCAPTCHA();\n ready(callback: () => void): void {\n callback();\n }\n\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey: string,\n _options: { action: string }\n ): Promise {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container: string | HTMLElement,\n _parameters: GreCAPTCHARenderOption\n ): string {\n return '';\n }\n}\n\nexport class MockGreCAPTCHA implements GreCAPTCHA {\n ready(callback: () => void): void {\n callback();\n }\n\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey: string,\n _options: { action: string }\n ): Promise {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container: string | HTMLElement,\n _parameters: GreCAPTCHARenderOption\n ): string {\n return '';\n }\n}\n\nexport class MockWidget {\n private readonly container: HTMLElement;\n private readonly isVisible: boolean;\n private timerId: number | null = null;\n private deleted = false;\n private responseToken: string | null = null;\n private readonly clickHandler = (): void => {\n this.execute();\n };\n\n constructor(\n containerOrId: string | HTMLElement,\n appName: string,\n private readonly params: RecaptchaParameters\n ) {\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, AuthErrorCode.ARGUMENT_ERROR, { appName });\n\n this.container = container;\n this.isVisible = this.params.size !== 'invisible';\n if (this.isVisible) {\n this.execute();\n } else {\n this.container.addEventListener('click', this.clickHandler);\n }\n }\n\n getResponse(): string | null {\n this.checkIfDeleted();\n return this.responseToken;\n }\n\n delete(): void {\n this.checkIfDeleted();\n this.deleted = true;\n if (this.timerId) {\n clearTimeout(this.timerId);\n this.timerId = null;\n }\n this.container.removeEventListener('click', this.clickHandler);\n }\n\n execute(): void {\n this.checkIfDeleted();\n if (this.timerId) {\n return;\n }\n\n this.timerId = window.setTimeout(() => {\n this.responseToken = generateRandomAlphaNumericString(50);\n const { callback, 'expired-callback': expiredCallback } = this.params;\n if (callback) {\n try {\n callback(this.responseToken);\n } catch (e) {}\n }\n\n this.timerId = window.setTimeout(() => {\n this.timerId = null;\n this.responseToken = null;\n if (expiredCallback) {\n try {\n expiredCallback();\n } catch (e) {}\n }\n\n if (this.isVisible) {\n this.execute();\n }\n }, _EXPIRATION_TIME_MS);\n }, _SOLVE_TIME_MS);\n }\n\n private checkIfDeleted(): void {\n if (this.deleted) {\n throw new Error('reCAPTCHA mock was already deleted!');\n }\n }\n}\n\nfunction generateRandomAlphaNumericString(len: number): string {\n const chars = [];\n const allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < len; i++) {\n chars.push(\n allowedChars.charAt(Math.floor(Math.random() * allowedChars.length))\n );\n }\n return chars.join('');\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 { querystring } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as jsHelpers from '../load_js';\nimport { Recaptcha, isV2 } from './recaptcha';\nimport { MockReCaptcha } from './recaptcha_mock';\n\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nexport const _JSLOAD_CALLBACK = jsHelpers._generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\n\n/**\n * We need to mark this interface as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport interface ReCaptchaLoader {\n load(auth: AuthInternal, hl?: string): Promise;\n clearedOneInstance(): void;\n}\n\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nexport class ReCaptchaLoaderImpl implements ReCaptchaLoader {\n private hostLanguage = '';\n private counter = 0;\n /**\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\n * `window.grecaptcha.render()` will not. Another load will add it.\n */\n private readonly librarySeparatelyLoaded = !!_window().grecaptcha?.render;\n\n load(auth: AuthInternal, hl = ''): Promise {\n _assert(isHostLanguageValid(hl), auth, AuthErrorCode.ARGUMENT_ERROR);\n\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\n return Promise.resolve(_window().grecaptcha! as Recaptcha);\n }\n return new Promise((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, NETWORK_TIMEOUT_DELAY.get());\n\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n\n const recaptcha = _window().grecaptcha as Recaptcha;\n\n if (!recaptcha || !isV2(recaptcha)) {\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n return;\n }\n\n // Wrap the greptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n\n const url = `${jsHelpers._recaptchaV2ScriptUrl()}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n\n jsHelpers._loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n });\n });\n }\n\n clearedOneInstance(): void {\n this.counter--;\n }\n\n private shouldResolveImmediately(hl: string): boolean {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (\n !!_window().grecaptcha?.render &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded)\n );\n }\n}\n\nfunction isHostLanguageValid(hl: string): boolean {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\n\nexport class MockReCaptchaLoaderImpl implements ReCaptchaLoader {\n async load(auth: AuthInternal): Promise {\n return new MockReCaptcha(auth);\n }\n\n clearedOneInstance(): void {}\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 { Auth, RecaptchaParameters } from '../../model/public_types';\nimport { getRecaptchaParams } from '../../api/authentication/recaptcha';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { _isHttpOrHttps } from '../../core/util/location';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport { _isWorker } from '../util/worker';\nimport { Recaptcha } from './recaptcha';\nimport {\n MockReCaptchaLoaderImpl,\n ReCaptchaLoader,\n ReCaptchaLoaderImpl\n} from './recaptcha_loader';\n\nexport const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\n\nconst DEFAULT_PARAMS: RecaptchaParameters = {\n theme: 'light',\n type: 'image'\n};\n\ntype TokenCallback = (token: string) => void;\n\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @remarks\n * `RecaptchaVerifier` does not work in a Node.js environment.\n *\n * @public\n */\nexport class RecaptchaVerifier implements ApplicationVerifierInternal {\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n readonly type = RECAPTCHA_VERIFIER_TYPE;\n private destroyed = false;\n private widgetId: number | null = null;\n private readonly container: HTMLElement;\n private readonly isInvisible: boolean;\n private readonly tokenChangeListeners = new Set();\n private renderPromise: Promise | null = null;\n private readonly auth: AuthInternal;\n\n /** @internal */\n readonly _recaptchaLoader: ReCaptchaLoader;\n private recaptcha: Recaptcha | null = null;\n\n /**\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n */\n constructor(\n authExtern: Auth,\n containerOrId: HTMLElement | string,\n private readonly parameters: RecaptchaParameters = {\n ...DEFAULT_PARAMS\n }\n ) {\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify(): Promise {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n\n return new Promise(resolve => {\n const tokenChange = (token: string): void => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render(): Promise {\n try {\n this.assertNotDestroyed();\n } catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n\n if (this.renderPromise) {\n return this.renderPromise;\n }\n\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n\n return this.renderPromise;\n }\n\n /** @internal */\n _reset(): void {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear(): void {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n\n private validateStartingState(): void {\n _assert(!this.parameters.sitekey, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n this.isInvisible || !this.container.hasChildNodes(),\n this.auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n }\n\n private makeTokenCallback(\n existing: TokenCallback | string | undefined\n ): TokenCallback {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n } else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n\n private assertNotDestroyed(): void {\n _assert(!this.destroyed, this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n\n private async makeRenderPromise(): Promise {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n\n this.widgetId = this.getAssertedRecaptcha().render(\n container,\n this.parameters\n );\n }\n\n return this.widgetId;\n }\n\n private async init(): Promise {\n _assert(\n _isHttpOrHttps() && !_isWorker(),\n this.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(\n this.auth,\n this.auth.languageCode || undefined\n );\n\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.parameters.sitekey = siteKey;\n }\n\n private getAssertedRecaptcha(): Recaptcha {\n _assert(this.recaptcha, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.recaptcha;\n }\n}\n\nfunction domReady(): Promise {\n let resolver: (() => void) | null = null;\n return new Promise(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n\n throw e;\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 {\n ApplicationVerifier,\n Auth,\n ConfirmationResult,\n PhoneInfoOptions,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { startEnrollPhoneMfa } from '../../api/account_management/mfa';\nimport { startSignInPhoneMfa } from '../../api/authentication/mfa';\nimport { sendPhoneVerificationCode } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assertLinkedStatus, _link } from '../../core/user/link_unlink';\nimport {\n _assert,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport {\n linkWithCredential,\n reauthenticateWithCredential,\n signInWithCredential\n} from '../../core/strategies/credential';\nimport {\n MultiFactorSessionImpl,\n MultiFactorSessionType\n} from '../../mfa/mfa_session';\nimport { UserInternal } from '../../model/user';\nimport { RECAPTCHA_VERIFIER_TYPE } from '../recaptcha/recaptcha_verifier';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\ninterface OnConfirmationCallback {\n (credential: PhoneAuthCredential): Promise;\n}\n\nclass ConfirmationResultImpl implements ConfirmationResult {\n constructor(\n readonly verificationId: string,\n private readonly onConfirmation: OnConfirmationCallback\n ) {}\n\n confirm(verificationCode: string): Promise {\n const authCredential = PhoneAuthCredential._fromVerification(\n this.verificationId,\n verificationCode\n );\n return this.onConfirmation(authCredential);\n }\n}\n\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function signInWithPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(\n authInternal,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n signInWithCredential(authInternal, cred)\n );\n}\n\n/**\n * Links the user account with the given phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function linkWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(false, userInternal, ProviderId.PHONE);\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n linkWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function reauthenticateWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(userInternal.auth)\n );\n }\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n reauthenticateWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nexport async function _verifyPhoneNumber(\n auth: AuthInternal,\n options: PhoneInfoOptions | string,\n verifier: ApplicationVerifierInternal\n): Promise {\n const recaptchaToken = await verifier.verify();\n\n try {\n _assert(\n typeof recaptchaToken === 'string',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n verifier.type === RECAPTCHA_VERIFIER_TYPE,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n let phoneInfoOptions: PhoneInfoOptions;\n\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n } else {\n phoneInfoOptions = options;\n }\n\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session as MultiFactorSessionImpl;\n\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(\n session.type === MultiFactorSessionType.ENROLL,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollPhoneMfa(auth, {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n }\n });\n return response.phoneSessionInfo.sessionInfo;\n } else {\n _assert(\n session.type === MultiFactorSessionType.SIGN_IN,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const mfaEnrollmentId =\n phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, AuthErrorCode.MISSING_MFA_INFO);\n const response = await startSignInPhoneMfa(auth, {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n recaptchaToken\n }\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n } else {\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n });\n return sessionInfo;\n }\n } finally {\n verifier._reset();\n }\n}\n\n/**\n * Updates the user's phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nexport async function updatePhoneNumber(\n user: User,\n credential: PhoneAuthCredential\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(userInternal.auth)\n );\n }\n await _link(userInternal, credential);\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 {\n Auth,\n PhoneInfoOptions,\n ApplicationVerifier,\n UserCredential\n} from '../../model/public_types';\n\nimport { SignInWithPhoneNumberResponse } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal as ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal as AuthInternal } from '../../model/auth';\nimport { UserCredentialInternal as UserCredentialInternal } from '../../model/user';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { _verifyPhoneNumber } from '../strategies/phone';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthCredential } from '../../core';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @remarks\n * `PhoneAuthProvider` does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nexport class PhoneAuthProvider {\n /** Always set to {@link ProviderId}.PHONE. */\n static readonly PROVIDER_ID: 'phone' = ProviderId.PHONE;\n /** Always set to {@link SignInMethod}.PHONE. */\n static readonly PHONE_SIGN_IN_METHOD: 'phone' = SignInMethod.PHONE;\n\n /** Always set to {@link ProviderId}.PHONE. */\n readonly providerId = PhoneAuthProvider.PROVIDER_ID;\n private readonly auth: AuthInternal;\n\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth: Auth) {\n this.auth = _castAuth(auth);\n }\n\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - For abuse prevention, this method also requires a\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\n * {@link RecaptchaVerifier}.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow..\n */\n verifyPhoneNumber(\n phoneOptions: PhoneInfoOptions | string,\n applicationVerifier: ApplicationVerifier\n ): Promise {\n return _verifyPhoneNumber(\n this.auth,\n phoneOptions,\n getModularInstance(applicationVerifier as ApplicationVerifierInternal)\n );\n }\n\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return PhoneAuthCredential._fromVerification(\n verificationId,\n verificationCode\n );\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n const credential = userCredential as UserCredentialInternal;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return PhoneAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): AuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } =\n tokenResponse as SignInWithPhoneNumberResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(\n phoneNumber,\n temporaryProof\n );\n }\n return null;\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 { PopupRedirectResolver } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { _getInstance } from './instantiator';\n\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nexport function _withDefaultResolver(\n auth: AuthInternal,\n resolverOverride: PopupRedirectResolver | undefined\n): PopupRedirectResolverInternal {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n\n _assert(auth._popupRedirectResolver, auth, AuthErrorCode.ARGUMENT_ERROR);\n\n return auth._popupRedirectResolver;\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 {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _link as _linkUser } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { _assert } from '../util/assert';\nimport { _signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { ProviderId } from '../../model/enums';\n\nexport interface IdpTaskParams {\n auth: AuthInternal;\n requestUri: string;\n sessionId?: string;\n tenantId?: string;\n postBody?: string;\n pendingToken?: string;\n user?: UserInternal;\n bypassAuthState?: boolean;\n}\n\nexport type IdpTask = (\n params: IdpTaskParams\n) => Promise;\n\nclass IdpCredential extends AuthCredential {\n constructor(readonly params: IdpTaskParams) {\n super(ProviderId.CUSTOM, ProviderId.CUSTOM);\n }\n\n _getIdTokenResponse(auth: AuthInternal): Promise {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n private _buildIdpRequest(idToken?: string): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n\n if (idToken) {\n request.idToken = idToken;\n }\n\n return request;\n }\n}\n\nexport function _signIn(\n params: IdpTaskParams\n): Promise {\n return _signInWithCredential(\n params.auth,\n new IdpCredential(params),\n params.bypassAuthState\n ) as Promise;\n}\n\nexport function _reauth(\n params: IdpTaskParams\n): Promise {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _reauthenticate(\n user,\n new IdpCredential(params),\n params.bypassAuthState\n );\n}\n\nexport async function _link(\n params: IdpTaskParams\n): Promise {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _linkUser(user, new IdpCredential(params), params.bypassAuthState);\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 { FirebaseError } from '@firebase/util';\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { debugAssert, _fail } from '../util/assert';\nimport {\n _link,\n _reauth,\n _signIn,\n IdpTask,\n IdpTaskParams\n} from '../strategies/idp';\nimport { AuthInternal } from '../../model/auth';\n\ninterface PendingPromise {\n resolve: (cred: UserCredentialInternal | null) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nexport abstract class AbstractPopupRedirectOperation\n implements AuthEventConsumer\n{\n private pendingPromise: PendingPromise | null = null;\n private eventManager: EventManager | null = null;\n readonly filter: AuthEventType[];\n\n abstract eventId: string | null;\n\n constructor(\n protected readonly auth: AuthInternal,\n filter: AuthEventType | AuthEventType[],\n protected readonly resolver: PopupRedirectResolverInternal,\n protected user?: UserInternal,\n protected readonly bypassAuthState = false\n ) {\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n\n abstract onExecution(): Promise;\n\n execute(): Promise {\n return new Promise(\n async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n } catch (e) {\n this.reject(e as Error);\n }\n }\n );\n }\n\n async onAuthEvent(event: AuthEvent): Promise {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n\n const params: IdpTaskParams = {\n auth: this.auth,\n requestUri: urlResponse!,\n sessionId: sessionId!,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n\n try {\n this.resolve(await this.getIdpTask(type)(params));\n } catch (e) {\n this.reject(e as Error);\n }\n }\n\n onError(error: FirebaseError): void {\n this.reject(error);\n }\n\n private getIdpTask(type: AuthEventType): IdpTask {\n switch (type) {\n case AuthEventType.SIGN_IN_VIA_POPUP:\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n return _signIn;\n case AuthEventType.LINK_VIA_POPUP:\n case AuthEventType.LINK_VIA_REDIRECT:\n return _link;\n case AuthEventType.REAUTH_VIA_POPUP:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return _reauth;\n default:\n _fail(this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n protected resolve(cred: UserCredentialInternal | null): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n\n protected reject(error: Error): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n\n private unregisterAndCleanUp(): void {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n\n this.pendingPromise = null;\n this.cleanUp();\n }\n\n abstract cleanUp(): void;\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 {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _assert,\n debugAssert,\n _createError,\n _assertInstanceOf\n} from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport { AuthPopup } from '../util/popup';\nimport { AbstractPopupRedirectOperation } from '../../core/strategies/abstract_popup_redirect_operation';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\n/*\n * The event timeout is the same on mobile and desktop, no need for Delay. Set this to 8s since\n * blocking functions can take upto 7s to complete sign in, as documented in:\n * https://cloud.google.com/identity-platform/docs/blocking-functions#understanding_blocking_functions\n * https://firebase.google.com/docs/auth/extend-with-blocking-functions#understanding_blocking_functions\n */\nexport const enum _Timeout {\n AUTH_EVENT = 8000\n}\nexport const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function signInWithPopup(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _createError(auth, AuthErrorCode.OPERATION_NOT_SUPPORTED)\n );\n }\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(\n authInternal,\n AuthEventType.SIGN_IN_VIA_POPUP,\n provider,\n resolverInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function reauthenticateWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _createError(userInternal.auth, AuthErrorCode.OPERATION_NOT_SUPPORTED)\n );\n }\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.REAUTH_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function linkWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.LINK_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n // Only one popup is ever shown at once. The lifecycle of the current popup\n // can be managed / cancelled by the constructor.\n private static currentPopupAction: PopupOperation | null = null;\n private authWindow: AuthPopup | null = null;\n private pollId: number | null = null;\n\n constructor(\n auth: AuthInternal,\n filter: AuthEventType,\n private readonly provider: AuthProvider,\n resolver: PopupRedirectResolverInternal,\n user?: UserInternal\n ) {\n super(auth, filter, resolver, user);\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n\n PopupOperation.currentPopupAction = this;\n }\n\n async executeNotNull(): Promise {\n const result = await this.execute();\n _assert(result, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return result;\n }\n\n async onExecution(): Promise {\n debugAssert(\n this.filter.length === 1,\n 'Popup operations only handle one event'\n );\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(\n this.auth,\n this.provider,\n this.filter[0], // There's always one, see constructor\n eventId\n );\n this.authWindow.associatedEvent = eventId;\n\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(\n _createError(this.auth, AuthErrorCode.WEB_STORAGE_UNSUPPORTED)\n );\n }\n });\n\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n\n get eventId(): string | null {\n return this.authWindow?.associatedEvent || null;\n }\n\n cancel(): void {\n this.reject(_createError(this.auth, AuthErrorCode.EXPIRED_POPUP_REQUEST));\n }\n\n cleanUp(): void {\n if (this.authWindow) {\n this.authWindow.close();\n }\n\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n\n private pollUserCancellation(): void {\n const poll = (): void => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight. This is specifically true for\n // Firefox or if the opener is in an iframe, in which case the oauth\n // helper closes the popup.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(\n _createError(this.auth, AuthErrorCode.POPUP_CLOSED_BY_USER)\n );\n }, _Timeout.AUTH_EVENT);\n return;\n }\n\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n\n poll();\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 { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserCredentialInternal } from '../../model/user';\nimport { PersistenceInternal } from '../persistence';\nimport { _persistenceKeyName } from '../persistence/persistence_user_manager';\nimport { _getInstance } from '../util/instantiator';\nimport { AbstractPopupRedirectOperation } from './abstract_popup_redirect_operation';\n\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap: Map<\n string,\n () => Promise\n> = new Map();\n\nexport class RedirectAction extends AbstractPopupRedirectOperation {\n eventId = null;\n\n constructor(\n auth: AuthInternal,\n resolver: PopupRedirectResolverInternal,\n bypassAuthState = false\n ) {\n super(\n auth,\n [\n AuthEventType.SIGN_IN_VIA_REDIRECT,\n AuthEventType.LINK_VIA_REDIRECT,\n AuthEventType.REAUTH_VIA_REDIRECT,\n AuthEventType.UNKNOWN\n ],\n resolver,\n undefined,\n bypassAuthState\n );\n }\n\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute(): Promise {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(\n this.resolver,\n this.auth\n );\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n } catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n\n return readyOutcome();\n }\n\n async onAuthEvent(event: AuthEvent): Promise {\n if (event.type === AuthEventType.SIGN_IN_VIA_REDIRECT) {\n return super.onAuthEvent(event);\n } else if (event.type === AuthEventType.UNKNOWN) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n } else {\n this.resolve(null);\n }\n }\n }\n\n async onExecution(): Promise {}\n\n cleanUp(): void {}\n}\n\nexport async function _getAndClearPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\n\nexport async function _setPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\n\nexport function _clearRedirectOutcomes(): void {\n redirectOutcomeMap.clear();\n}\n\nexport function _overrideRedirectResult(\n auth: AuthInternal,\n result: () => Promise\n): void {\n redirectOutcomeMap.set(auth._key(), result);\n}\n\nfunction resolverPersistence(\n resolver: PopupRedirectResolverInternal\n): PersistenceInternal {\n return _getInstance(resolver._redirectPersistence);\n}\n\nfunction pendingRedirectKey(auth: AuthInternal): string {\n return _persistenceKeyName(\n PENDING_REDIRECT_KEY,\n auth.config.apiKey,\n auth.name\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 {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { _assertLinkedStatus } from '../../core/user/link_unlink';\nimport {\n _assertInstanceOf,\n _serverAppCurrentUserOperationNotSupportedError\n} from '../../core/util/assert';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport {\n RedirectAction,\n _setPendingRedirectStatus\n} from '../../core/strategies/redirect';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link signInWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _signInWithRedirect(auth, provider, resolver) as Promise;\n}\n\nexport async function _signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await authInternal._initializationPromise;\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n\n return resolverInternal._openRedirect(\n authInternal,\n provider,\n AuthEventType.SIGN_IN_VIA_REDIRECT\n );\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link reauthenticateWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Reauthenticate using a redirect.\n * await reauthenticateWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _reauthenticateWithRedirect(\n user,\n provider,\n resolver\n ) as Promise;\n}\nexport async function _reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(userInternal.auth)\n );\n }\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.REAUTH_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link linkWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _linkWithRedirect(user, provider, resolver) as Promise;\n}\nexport async function _linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.LINK_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns `null`.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function getRedirectResult(\n auth: Auth,\n resolver?: PopupRedirectResolver\n): Promise {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\n\nexport async function _getRedirectResult(\n auth: Auth,\n resolverExtern?: PopupRedirectResolver,\n bypassAuthState = false\n): Promise {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(\n _serverAppCurrentUserOperationNotSupportedError(auth)\n );\n }\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user as UserInternal);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n\n return result;\n}\n\nasync function prepareUserForRedirect(user: UserInternal): Promise {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\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 {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager\n} from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { AuthInternal } from '../../model/auth';\nimport { _createError } from '../util/assert';\n\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\n\nexport class AuthEventManager implements EventManager {\n private readonly cachedEventUids: Set = new Set();\n private readonly consumers: Set = new Set();\n protected queuedRedirectEvent: AuthEvent | null = null;\n protected hasHandledPotentialRedirect = false;\n private lastProcessedEventTime = Date.now();\n\n constructor(private readonly auth: AuthInternal) {}\n\n registerConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.add(authEventConsumer);\n\n if (\n this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)\n ) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n\n unregisterConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.delete(authEventConsumer);\n }\n\n onEvent(event: AuthEvent): boolean {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n\n this.hasHandledPotentialRedirect = true;\n\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n\n return handled;\n }\n\n private sendToConsumer(event: AuthEvent, consumer: AuthEventConsumer): void {\n if (event.error && !isNullRedirectEvent(event)) {\n const code =\n (event.error.code?.split('auth/')[1] as AuthErrorCode) ||\n AuthErrorCode.INTERNAL_ERROR;\n consumer.onError(_createError(this.auth, code));\n } else {\n consumer.onAuthEvent(event);\n }\n }\n\n private isEventForConsumer(\n event: AuthEvent,\n consumer: AuthEventConsumer\n ): boolean {\n const eventIdMatches =\n consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n\n private hasEventBeenHandled(event: AuthEvent): boolean {\n if (\n Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS\n ) {\n this.cachedEventUids.clear();\n }\n\n return this.cachedEventUids.has(eventUid(event));\n }\n\n private saveEventToCache(event: AuthEvent): void {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\n\nfunction eventUid(e: AuthEvent): string {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\n\nfunction isNullRedirectEvent({ type, error }: AuthEvent): boolean {\n return (\n type === AuthEventType.UNKNOWN &&\n error?.code === `auth/${AuthErrorCode.NO_AUTH_EVENT}`\n );\n}\n\nfunction isRedirectEvent(event: AuthEvent): boolean {\n switch (event.type) {\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n case AuthEventType.LINK_VIA_REDIRECT:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return true;\n case AuthEventType.UNKNOWN:\n return isNullRedirectEvent(event);\n default:\n return false;\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 { _performApiRequest, Endpoint, HttpMethod } from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface GetProjectConfigRequest {\n androidPackageName?: string;\n iosBundleId?: string;\n}\n\nexport interface GetProjectConfigResponse {\n authorizedDomains: string[];\n}\n\nexport async function _getProjectConfig(\n auth: Auth,\n request: GetProjectConfigRequest = {}\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PROJECT_CONFIG,\n request\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 { _getProjectConfig } from '../../api/project_config/get_project_config';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from './assert';\nimport { _getCurrentUrl } from './location';\n\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\n\nexport async function _validateOrigin(auth: AuthInternal): Promise {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n\n const { authorizedDomains } = await _getProjectConfig(auth);\n\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n } catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, AuthErrorCode.INVALID_ORIGIN);\n}\n\nfunction matchDomain(expected: string): boolean {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (\n protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', '')\n );\n }\n\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n\n if (IP_ADDRESS_REGEX.test(expected)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return hostname === expected;\n }\n\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',\n 'i'\n );\n return re.test(hostname);\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 { AuthErrorCode } from '../../core/errors';\nimport { _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as js from '../load_js';\n\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\n\n/**\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfunction resetUnloadedGapiModules(): void {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(beacon.H)) {\n // Requested modules.\n beacon.H[hint].r = beacon.H[hint].r || [];\n // Loaded modules.\n beacon.H[hint].L = beacon.H[hint].L || [];\n // Set requested modules to a copy of the loaded modules.\n beacon.H[hint].r = [...beacon.H[hint].L];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\n\nfunction loadGapi(auth: AuthInternal): Promise {\n return new Promise((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe(): void {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n resetUnloadedGapiModules();\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n } else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\n } else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n const cbName = js._generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n } else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }\n };\n // Load GApi loader.\n return js\n ._loadJS(`${js._gapiScriptUrl()}?onload=${cbName}`)\n .catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\n\nlet cachedGApiLoader: Promise | null = null;\nexport function _loadGapi(auth: AuthInternal): Promise {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\nexport function _resetLoader(): void {\n cachedGApiLoader = null;\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 { SDK_VERSION } from '@firebase/app';\nimport { querystring } from '@firebase/util';\nimport { DefaultConfig } from '../../../internal';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _emulatorUrl } from '../../core/util/emulator';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as gapiLoader from './gapi';\n\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\n\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [DefaultConfig.API_HOST, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\n\nfunction getIframeUrl(auth: AuthInternal): string {\n const config = auth.config;\n _assert(config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n\n const params: Record = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\n\nexport async function _openIframe(\n auth: AuthInternal\n): Promise {\n const context = await gapiLoader._loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, AuthErrorCode.INTERNAL_ERROR);\n return context.open(\n {\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n },\n (iframe: gapi.iframes.Iframe) =>\n new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n\n const networkError = _createError(\n auth,\n AuthErrorCode.NETWORK_REQUEST_FAILED\n );\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve(): void {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\n }\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\n reject(networkError);\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\nimport { getUA } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport {\n _isChromeIOS,\n _isFirefox,\n _isIOSStandalone\n} from '../../core/util/browser';\nimport { AuthInternal } from '../../model/auth';\n\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\n\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\n\nconst FIREFOX_EMPTY_URL = 'http://localhost';\n\nexport class AuthPopup {\n associatedEvent: string | null = null;\n\n constructor(readonly window: Window | null) {}\n\n close(): void {\n if (this.window) {\n try {\n this.window.close();\n } catch (e) {}\n }\n }\n}\n\nexport function _open(\n auth: AuthInternal,\n url?: string,\n name?: string,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n): AuthPopup {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n\n const options: { [key: string]: string } = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\n\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n const ua = getUA().toLowerCase();\n\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options.scrollbars = 'yes';\n }\n\n const optionsString = Object.entries(options).reduce(\n (accum, [key, value]) => `${accum}${key}=${value},`,\n ''\n );\n\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, AuthErrorCode.POPUP_BLOCKED);\n\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n\n return new AuthPopup(newWin);\n}\n\nfunction openAsNewWindowIOS(url: string, target: string): void {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 1,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 1,\n null\n );\n el.dispatchEvent(click);\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 { SDK_VERSION } from '@firebase/app';\nimport { AuthProvider } from '../../model/public_types';\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { isEmpty, querystring } from '@firebase/util';\nimport { _emulatorUrl } from './emulator';\nimport { FederatedAuthProvider } from '../providers/federated';\nimport { BaseOAuthProvider } from '../providers/oauth';\n\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n\n/**\n * Fragment name for the App Check token that gets passed to the widget\n *\n * @internal\n */\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ntype WidgetParams = {\n apiKey: ApiKey;\n appName: AppName;\n authType: AuthEventType;\n redirectUrl?: string;\n v: string;\n providerId?: string;\n scopes?: string;\n customParameters?: string;\n eventId?: string;\n tid?: string;\n} & { [key: string]: string | undefined };\n\nexport async function _getRedirectUrl(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n redirectUrl?: string,\n eventId?: string,\n additionalParams?: Record\n): Promise {\n _assert(auth.config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n _assert(auth.config.apiKey, auth, AuthErrorCode.INVALID_API_KEY);\n\n const params: WidgetParams = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n\n // TODO: maybe set eid as endipointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n\n const paramsDict = params as Record;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n\n // Sets the App Check token to pass to the widget\n const appCheckToken = await auth._getAppCheckToken();\n const appCheckTokenFragment = appCheckToken\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\n : '';\n\n // Start at index 1 to skip the leading '&' in the query string\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(\n 1\n )}${appCheckTokenFragment}`;\n}\n\nfunction getHandlerBase({ config }: AuthInternal): string {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\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 { AuthProvider, PopupRedirectResolver } from '../model/public_types';\n\nimport { AuthEventManager } from '../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../core/errors';\nimport { _assert, debugAssert, _fail } from '../core/util/assert';\nimport { _generateEventId } from '../core/util/event_id';\nimport { _getCurrentUrl } from '../core/util/location';\nimport { _validateOrigin } from '../core/util/validate_origin';\nimport { AuthInternal } from '../model/auth';\nimport {\n AuthEventType,\n EventManager,\n GapiAuthEvent,\n GapiOutcome,\n PopupRedirectResolverInternal\n} from '../model/popup_redirect';\nimport { _setWindowLocation } from './auth_window';\nimport { _openIframe } from './iframe/iframe';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { _open, AuthPopup } from './util/popup';\nimport { _getRedirectResult } from './strategies/redirect';\nimport { _getRedirectUrl } from '../core/util/handler';\nimport { _isIOS, _isMobileBrowser, _isSafari } from '../core/util/browser';\nimport { _overrideRedirectResult } from '../core/strategies/redirect';\n\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\n\ninterface WebStorageSupportMessage extends gapi.iframes.Message {\n [index: number]: Record;\n}\n\ninterface ManagerOrPromise {\n manager?: EventManager;\n promise?: Promise;\n}\n\nclass BrowserPopupRedirectResolver implements PopupRedirectResolverInternal {\n private readonly eventManagers: Record = {};\n private readonly iframes: Record = {};\n private readonly originValidationPromises: Record> = {};\n\n readonly _redirectPersistence = browserSessionPersistence;\n\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise {\n debugAssert(\n this.eventManagers[auth._key()]?.manager,\n '_initialize() not called before _openPopup()'\n );\n\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n return _open(auth, url, _generateEventId());\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise {\n await this._originValidation(auth);\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n _setWindowLocation(url);\n return new Promise(() => {});\n }\n\n _initialize(auth: AuthInternal): Promise {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n } else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n\n return promise;\n }\n\n private async initAndGetManager(auth: AuthInternal): Promise {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register(\n 'authEvent',\n (iframeEvent: GapiAuthEvent | null) => {\n _assert(iframeEvent?.authEvent, auth, AuthErrorCode.INVALID_AUTH_EVENT);\n // TODO: Consider splitting redirect and popup events earlier on\n\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? GapiOutcome.ACK : GapiOutcome.ERROR };\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n\n _isIframeWebStorageSupported(\n auth: AuthInternal,\n cb: (supported: boolean) => unknown\n ): void {\n const iframe = this.iframes[auth._key()];\n iframe.send(\n WEB_STORAGE_SUPPORT_KEY,\n { type: WEB_STORAGE_SUPPORT_KEY },\n result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n }\n\n _originValidation(auth: AuthInternal): Promise {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n get _shouldInitProactively(): boolean {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n\n _completeRedirectFn = _getRedirectResult;\n\n _overrideRedirectResult = _overrideRedirectResult;\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @public\n */\nexport const browserPopupRedirectResolver: PopupRedirectResolver =\n BrowserPopupRedirectResolver;\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 */\nimport { FactorId, MultiFactorAssertion } from '../model/public_types';\nimport { debugFail } from '../core/util/assert';\nimport { MultiFactorSessionImpl, MultiFactorSessionType } from './mfa_session';\nimport { FinalizeMfaResponse } from '../api/authentication/mfa';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorAssertionImpl implements MultiFactorAssertion {\n protected constructor(readonly factorId: FactorId) {}\n\n _process(\n auth: AuthInternal,\n session: MultiFactorSessionImpl,\n displayName?: string | null\n ): Promise {\n switch (session.type) {\n case MultiFactorSessionType.ENROLL:\n return this._finalizeEnroll(auth, session.credential, displayName);\n case MultiFactorSessionType.SIGN_IN:\n return this._finalizeSignIn(auth, session.credential);\n default:\n return debugFail('unexpected MultiFactorSessionType');\n }\n }\n\n abstract _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise;\n abstract _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise;\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 */\nimport {\n FactorId,\n PhoneMultiFactorAssertion\n} from '../../../model/public_types';\n\nimport { MultiFactorAssertionImpl } from '../../../mfa/mfa_assertion';\nimport { AuthInternal } from '../../../model/auth';\nimport { finalizeEnrollPhoneMfa } from '../../../api/account_management/mfa';\nimport { PhoneAuthCredential } from '../../../core/credentials/phone';\nimport {\n finalizeSignInPhoneMfa,\n FinalizeMfaResponse\n} from '../../../api/authentication/mfa';\n\n/**\n * {@inheritdoc PhoneMultiFactorAssertion}\n *\n * @public\n */\nexport class PhoneMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements PhoneMultiFactorAssertion\n{\n private constructor(private readonly credential: PhoneAuthCredential) {\n super(FactorId.PHONE);\n }\n\n /** @internal */\n static _fromCredential(\n credential: PhoneAuthCredential\n ): PhoneMultiFactorAssertionImpl {\n return new PhoneMultiFactorAssertionImpl(credential);\n }\n\n /** @internal */\n _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise {\n return finalizeEnrollPhoneMfa(auth, {\n idToken,\n displayName,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise {\n return finalizeSignInPhoneMfa(auth, {\n mfaPendingCredential,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n}\n\n/**\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\n *\n * @public\n */\nexport class PhoneMultiFactorGenerator {\n private constructor() {}\n\n /**\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}\n */\n static assertion(credential: PhoneAuthCredential): PhoneMultiFactorAssertion {\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\n }\n\n /**\n * The identifier of the phone second factor: `phone`.\n */\n static FACTOR_ID = 'phone';\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 */\nimport {\n TotpMultiFactorAssertion,\n MultiFactorSession,\n FactorId\n} from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport {\n finalizeEnrollTotpMfa,\n startEnrollTotpMfa,\n StartTotpMfaEnrollmentResponse,\n TotpVerificationInfo\n} from '../../api/account_management/mfa';\nimport {\n FinalizeMfaResponse,\n finalizeSignInTotpMfa\n} from '../../api/authentication/mfa';\nimport { MultiFactorAssertionImpl } from '../../mfa/mfa_assertion';\nimport { MultiFactorSessionImpl } from '../mfa_session';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\n\n/**\n * Provider for generating a {@link TotpMultiFactorAssertion}.\n *\n * @public\n */\nexport class TotpMultiFactorGenerator {\n /**\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\n * the TOTP (time-based one-time password) second factor.\n * This assertion is used to complete enrollment in TOTP second factor.\n *\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\n * @param oneTimePassword One-time password from TOTP App.\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\n * {@link MultiFactorUser.enroll}.\n */\n static assertionForEnrollment(\n secret: TotpSecret,\n oneTimePassword: string\n ): TotpMultiFactorAssertion {\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\n }\n\n /**\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\n * This assertion is used to complete signIn with TOTP as the second factor.\n *\n * @param enrollmentId identifies the enrolled TOTP second factor.\n * @param oneTimePassword One-time password from TOTP App.\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}.\n */\n static assertionForSignIn(\n enrollmentId: string,\n oneTimePassword: string\n ): TotpMultiFactorAssertion {\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(\n enrollmentId,\n oneTimePassword\n );\n }\n\n /**\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\n * Used for generating a QR code URL or inputting into a TOTP app.\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\n *\n * @param session The {@link MultiFactorSession} that the user is part of.\n * @returns A promise to {@link TotpSecret}.\n */\n static async generateSecret(\n session: MultiFactorSession\n ): Promise {\n const mfaSession = session as MultiFactorSessionImpl;\n _assert(\n typeof mfaSession.user?.auth !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollTotpMfa(mfaSession.user.auth, {\n idToken: mfaSession.credential,\n totpEnrollmentInfo: {}\n });\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(\n response,\n mfaSession.user.auth\n );\n }\n\n /**\n * The identifier of the TOTP second factor: `totp`.\n */\n static FACTOR_ID: 'totp' = FactorId.TOTP;\n}\n\nexport class TotpMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements TotpMultiFactorAssertion\n{\n constructor(\n readonly otp: string,\n readonly enrollmentId?: string,\n readonly secret?: TotpSecret\n ) {\n super(FactorId.TOTP);\n }\n\n /** @internal */\n static _fromSecret(\n secret: TotpSecret,\n otp: string\n ): TotpMultiFactorAssertionImpl {\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\n }\n\n /** @internal */\n static _fromEnrollmentId(\n enrollmentId: string,\n otp: string\n ): TotpMultiFactorAssertionImpl {\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\n }\n\n /** @internal */\n async _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise {\n _assert(\n typeof this.secret !== 'undefined',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return finalizeEnrollTotpMfa(auth, {\n idToken,\n displayName,\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\n });\n }\n\n /** @internal */\n async _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise {\n _assert(\n this.enrollmentId !== undefined && this.otp !== undefined,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n const totpVerificationInfo = { verificationCode: this.otp };\n return finalizeSignInTotpMfa(auth, {\n mfaPendingCredential,\n mfaEnrollmentId: this.enrollmentId,\n totpVerificationInfo\n });\n }\n}\n\n/**\n * Provider for generating a {@link TotpMultiFactorAssertion}.\n *\n * Stores the shared secret key and other parameters to generate time-based OTPs.\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\n * @public\n */\nexport class TotpSecret {\n /**\n * Shared secret key/seed used for enrolling in TOTP MFA and generating OTPs.\n */\n readonly secretKey: string;\n /**\n * Hashing algorithm used.\n */\n readonly hashingAlgorithm: string;\n /**\n * Length of the one-time passwords to be generated.\n */\n readonly codeLength: number;\n /**\n * The interval (in seconds) when the OTP codes should change.\n */\n readonly codeIntervalSeconds: number;\n /**\n * The timestamp (UTC string) by which TOTP enrollment should be completed.\n */\n // This can be used by callers to show a countdown of when to enter OTP code by.\n readonly enrollmentCompletionDeadline: string;\n\n // The public members are declared outside the constructor so the docs can be generated.\n private constructor(\n secretKey: string,\n hashingAlgorithm: string,\n codeLength: number,\n codeIntervalSeconds: number,\n enrollmentCompletionDeadline: string,\n private readonly sessionInfo: string,\n private readonly auth: AuthInternal\n ) {\n this.secretKey = secretKey;\n this.hashingAlgorithm = hashingAlgorithm;\n this.codeLength = codeLength;\n this.codeIntervalSeconds = codeIntervalSeconds;\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\n }\n\n /** @internal */\n static _fromStartTotpMfaEnrollmentResponse(\n response: StartTotpMfaEnrollmentResponse,\n auth: AuthInternal\n ): TotpSecret {\n return new TotpSecret(\n response.totpSessionInfo.sharedSecretKey,\n response.totpSessionInfo.hashingAlgorithm,\n response.totpSessionInfo.verificationCodeLength,\n response.totpSessionInfo.periodSec,\n new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),\n response.totpSessionInfo.sessionInfo,\n auth\n );\n }\n\n /** @internal */\n _makeTotpVerificationInfo(otp: string): TotpVerificationInfo {\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\n }\n\n /**\n * Returns a QR code URL as described in\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\n * If the optional parameters are unspecified, an accountName of and issuer of are used.\n *\n * @param accountName the name of the account/app along with a user identifier.\n * @param issuer issuer of the TOTP (likely the app name).\n * @returns A QR code URL string.\n */\n generateQrCodeUrl(accountName?: string, issuer?: string): string {\n let useDefaults = false;\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\n useDefaults = true;\n }\n if (useDefaults) {\n if (_isEmptyString(accountName)) {\n accountName = this.auth.currentUser?.email || 'unknownuser';\n }\n if (_isEmptyString(issuer)) {\n issuer = this.auth.name;\n }\n }\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\n }\n}\n\n/** @internal */\nfunction _isEmptyString(input?: string): boolean {\n return typeof input === 'undefined' || input?.length === 0;\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 { Unsubscribe } from '@firebase/util';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\n\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\ninterface TokenListener {\n (tok: string | null): unknown;\n}\n\nexport class AuthInterop implements FirebaseAuthInternal {\n private readonly internalListeners: Map =\n new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n getUid(): string | null {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n\n async getToken(\n forceRefresh?: boolean\n ): Promise<{ accessToken: string } | null> {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n\n addAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(\n (user as UserInternal | null)?.stsTokenManager.accessToken || null\n );\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n\n removeAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n\n private assertAuthConfigured(): void {\n _assert(\n this.auth._initializationPromise,\n AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n );\n }\n\n private updateProactiveRefresh(): void {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n } else {\n this.auth._stopProactiveRefresh();\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 { _registerComponent, registerVersion } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\n\nimport { name, version } from '../../../package.json';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _getClientVersion, ClientPlatform } from '../util/version';\nimport { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';\nimport { AuthInterop } from './firebase_internal';\nimport { ConfigInternal } from '../../model/auth';\nimport { Dependencies } from '../../model/public_types';\nimport { _initializeAuthInstance } from './initialize';\n\nexport const enum _ComponentName {\n AUTH = 'auth',\n AUTH_INTERNAL = 'auth-internal'\n}\n\nfunction getVersionForPlatform(\n clientPlatform: ClientPlatform\n): string | undefined {\n switch (clientPlatform) {\n case ClientPlatform.NODE:\n return 'node';\n case ClientPlatform.REACT_NATIVE:\n return 'rn';\n case ClientPlatform.WORKER:\n return 'webworker';\n case ClientPlatform.CORDOVA:\n return 'cordova';\n case ClientPlatform.WEB_EXTENSION:\n return 'web-extension';\n default:\n return undefined;\n }\n}\n\n/** @internal */\nexport function registerAuth(clientPlatform: ClientPlatform): void {\n _registerComponent(\n new Component(\n _ComponentName.AUTH,\n (container, { options: deps }: { options?: Dependencies }) => {\n const app = container.getProvider('app').getImmediate()!;\n const heartbeatServiceProvider =\n container.getProvider<'heartbeat'>('heartbeat');\n const appCheckServiceProvider =\n container.getProvider<'app-check-internal'>('app-check-internal');\n const { apiKey, authDomain } = app.options;\n\n _assert(\n apiKey && !apiKey.includes(':'),\n AuthErrorCode.INVALID_API_KEY,\n { appName: app.name }\n );\n\n const config: ConfigInternal = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: DefaultConfig.API_HOST,\n tokenApiHost: DefaultConfig.TOKEN_API_HOST,\n apiScheme: DefaultConfig.API_SCHEME,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n\n const authInstance = new AuthImpl(\n app,\n heartbeatServiceProvider,\n appCheckServiceProvider,\n config\n );\n _initializeAuthInstance(authInstance, deps);\n\n return authInstance;\n },\n ComponentType.PUBLIC\n )\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback(\n (container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\n _ComponentName.AUTH_INTERNAL\n );\n authInternalProvider.initialize();\n }\n )\n );\n\n _registerComponent(\n new Component(\n _ComponentName.AUTH_INTERNAL,\n container => {\n const auth = _castAuth(\n container.getProvider(_ComponentName.AUTH).getImmediate()!\n );\n return (auth => new AuthInterop(auth))(auth);\n },\n ComponentType.PRIVATE\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\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, getApp, _getProvider } from '@firebase/app';\n\nimport {\n initializeAuth,\n beforeAuthStateChanged,\n onIdTokenChanged,\n connectAuthEmulator\n} from '..';\nimport { registerAuth } from '../core/auth/register';\nimport { ClientPlatform } from '../core/util/version';\nimport { browserLocalPersistence } from './persistence/local_storage';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { indexedDBLocalPersistence } from './persistence/indexed_db';\nimport { browserPopupRedirectResolver } from './popup_redirect';\nimport { Auth, User } from '../model/public_types';\nimport { getDefaultEmulatorHost, getExperimentalSetting } from '@firebase/util';\nimport { _setExternalJSProvider } from './load_js';\nimport { _createError } from '../core/util/assert';\nimport { AuthErrorCode } from '../core/errors';\n\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\nconst authIdTokenMaxAge =\n getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\n\nlet lastPostedIdToken: string | undefined | null = null;\n\nconst mintCookieFactory = (url: string) => async (user: User | null) => {\n const idTokenResult = user && (await user.getIdTokenResult());\n const idTokenAge =\n idTokenResult &&\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1_000;\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\n return;\n }\n // Specifically trip null => undefined when logged out, to delete any existing cookie\n const idToken = idTokenResult?.token;\n if (lastPostedIdToken === idToken) {\n return;\n }\n lastPostedIdToken = idToken;\n await fetch(url, {\n method: idToken ? 'POST' : 'DELETE',\n headers: idToken\n ? {\n 'Authorization': `Bearer ${idToken}`\n }\n : {}\n });\n};\n\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nexport function getAuth(app: FirebaseApp = getApp()): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n\n const auth = initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n\n const authTokenSyncPath = getExperimentalSetting('authTokenSyncURL');\n // Only do the Cookie exchange in a secure context\n if (\n authTokenSyncPath &&\n typeof isSecureContext === 'boolean' &&\n isSecureContext\n ) {\n // Don't allow urls (XSS possibility), only paths on the same domain\n const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);\n if (location.origin === authTokenSyncUrl.origin) {\n const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());\n beforeAuthStateChanged(auth, mintCookie, () =>\n mintCookie(auth.currentUser)\n );\n onIdTokenChanged(auth, user => mintCookie(user));\n }\n }\n\n const authEmulatorHost = getDefaultEmulatorHost('auth');\n if (authEmulatorHost) {\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\n }\n\n return auth;\n}\n\nfunction getScriptParentElement(): HTMLDocument | HTMLHeadElement {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n\n_setExternalJSProvider({\n loadJS(url: string): Promise {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(AuthErrorCode.INTERNAL_ERROR);\n error.customData = e as unknown as Record;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n },\n\n gapiScript: 'https://apis.google.com/js/api.js',\n recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',\n recaptchaEnterpriseScript:\n 'https://www.google.com/recaptcha/enterprise.js?render='\n});\n\nregisterAuth(ClientPlatform.BROWSER);\n", "/**\n * Authentication for data storage.\n */\nimport { init } from './firebaseService.js';\nimport { getAuth, GoogleAuthProvider, signInWithRedirect, onAuthStateChanged, signOut as fbSignOut } from 'firebase/auth';\n\nlet isAuthConfigured = false;\nlet currentUser = null;\nlet emitter = null;\n\n/**\n * Get current user.\n * @returns {User|null}\n */\nconst getUser = function () {\n return currentUser;\n};\n/**\n * Is current user logged in.\n * @returns {Boolean}\n */\nconst isAuthed = function () {\n return getUser() !== null;\n};\n/**\n * @param {Error} error Error usually from firebase\n * @param {String} method Method it happened it.\n */\nconst handleError = function (error, method) {\n const errorCode = error.code || '';\n const errorMessage = error.message || '';\n const message = `${method} auth error ${errorCode}: ${errorMessage}`;\n console.log(message);\n if (emitter) {\n emitter.trigger('error:display', message);\n }\n};\n\n/**\n * Trigger a signin (Google only).\n */\nconst signIn = async function () {\n if (!isAuthConfigured) {\n return;\n }\n try {\n const auth = getAuth();\n const provider = new GoogleAuthProvider();\n await signInWithRedirect(auth, provider);\n } catch (error) {\n handleError(error, 'signIn');\n }\n};\n/**\n *\n * @param {EventEmitter} em\n */\nconst monitorAuth = function (em) {\n // local reference to EventEmitter\n emitter = em;\n try {\n init();\n const auth = getAuth();\n isAuthConfigured = true;\n\n onAuthStateChanged(auth, user => {\n if (user != null) {\n console.log('Auth state changed to have a user.');\n currentUser = user;\n emitter.trigger('auth:signin');\n } else {\n console.log('Auth state changed to no user.');\n currentUser = null;\n emitter.trigger('auth:signout');\n }\n });\n\n emitter.trigger('auth:enabled');\n } catch (error) {\n handleError(error, 'monitorAuth');\n }\n};\n/**\n * Sign out.\n */\nconst signOut = function () {\n if (!isAuthConfigured) {\n return;\n }\n const auth = getAuth();\n fbSignOut(auth).then(() => {\n // Don't really need to do anything here\n // The observer catches the change the triggers any events.\n }).catch((error) => {\n handleError(error, 'signOut');\n });\n};\n\nexport {\n getUser,\n signIn,\n monitorAuth,\n signOut,\n isAuthed\n};\n", "import { getFirestore, collection, doc, getDoc, getDocs, setDoc, deleteDoc } from 'firebase/firestore';\nimport { getUser } from './AuthService.js';\n\n/**\n * Get Firebase userid if user is authed.\n * @returns {String|null}\n * @throws Error\n */\nconst getUserId = function () {\n const user = getUser();\n if (!user || !user.uid) {\n throw new Error('User not authed.');\n }\n return user.uid;\n};\n/**\n * Get document reference for a single character\n * @param {String} userId Firebase user id\n * @param {String} key Character key\n * @returns {DocumentReference}\n */\nconst getRefForKey = function (userId, key) {\n const db = getFirestore();\n return doc(db, `/users/${userId}/characters`, key);\n};\n/**\n * Get collection reference for user's characters.\n * @param {String} userId Firebase user id\n * @returns {CollectionReference}\n */\nconst getRefForCollection = function (userId) {\n const db = getFirestore();\n return collection(db, `/users/${userId}/characters`);\n};\n/**\n * Get single character.\n * @param {String} key Character key.\n * @returns {Object|null}\n * @throws Error\n */\nconst get = async function (key) {\n const userId = getUserId();\n if (!userId) {\n return null;\n }\n const docRef = getRefForKey(userId, key);\n try {\n const docSnap = await getDoc(docRef);\n if (docSnap.exists()) {\n return docSnap.data();\n } else {\n return null;\n }\n } catch (err) {\n console.log(`Database.get error: ${err}`);\n throw new Error(`Database.get error: ${err}`);\n }\n};\n/**\n * Save single character.\n * @param {String} key Character key.\n * @param {Object} char_obj Character data.\n * @returns {Boolean}\n * @throws Error\n */\nconst set = async function (key, char_obj) {\n const userId = getUserId();\n if (!userId) {\n return false;\n }\n const docRef = getRefForKey(userId, key);\n try {\n await setDoc(docRef, char_obj);\n } catch (err) {\n console.log(`Database.set error: ${err}`);\n throw new Error(`Database.set error: ${err}`);\n }\n return true;\n};\n/**\n * Get all characters for current user.\n * @returns {Object[]}\n * @throws Error\n */\nconst getAll = async function () {\n const userId = getUserId();\n if (!userId) {\n return [];\n }\n const char_obj = [];\n try {\n const querySnapshot = await getDocs(getRefForCollection(userId));\n querySnapshot.forEach((doc) => {\n char_obj.push(doc.data());\n });\n } catch (err) {\n console.log(`Database.getAll error: ${err}`);\n throw new Error(`Database.getAll error: ${err}`);\n }\n return char_obj;\n};\n/**\n * Remove a character from the remote.\n * @param {String} key\n * @returns {Boolean}\n * @throws Error\n */\nconst remove = async function (key) {\n const userId = getUserId();\n if (!userId) {\n return false;\n }\n const docRef = getRefForKey(userId, key);\n try {\n await deleteDoc(docRef);\n } catch (err) {\n console.log(`Database.remove error: ${err}`);\n throw new Error(`Database.remove error: ${err}`);\n }\n return true;\n};\n\nexport default {\n get,\n set,\n getAll,\n remove\n};\n", "// Simple tabs.\nclass Tabs {\n /**\n * @param {Element} tablist UL element for the tabs.\n */\n constructor (tablist) {\n this.tablist = tablist;\n this.tabs = [];\n this.panes = [];\n if (!tablist) {\n return;\n }\n this.tabs = tablist.querySelectorAll('a[role=tab]');\n this.panes = tablist.parentNode.querySelectorAll('section[role=tabpanel]');\n Array.from(this.tabs).forEach((tab) => {\n tab.addEventListener('click', this.changeTab.bind(this));\n });\n }\n /**\n * Switch to a specific pane.\n * @param {String} paneId Html id of pane to switch to.\n */\n switchToPane (paneId) {\n let newIndex = -1;\n if (paneId) {\n newIndex = Array.prototype.findIndex.call(this.panes, (el) => {\n return el.id === paneId;\n });\n } else {\n // next one.\n const oldTab = this.tablist.querySelector('[aria-selected=true]');\n const oldIndex = Array.prototype.indexOf.call(this.tabs, oldTab);\n newIndex = oldIndex + 1;\n if (newIndex >= this.tabs.length) {\n newIndex = 0;\n }\n }\n if (newIndex !== -1) {\n this.tabs[newIndex].click();\n }\n }\n /**\n * Handler: Change tabs on tab click.\n * @param {Event} ev Click event.\n */\n changeTab (ev) {\n ev.preventDefault();\n const oldTab = this.tablist.querySelector('[aria-selected=true]');\n if (!oldTab) {\n return;\n }\n const oldIndex = Array.prototype.indexOf.call(this.tabs, oldTab);\n const newTab = ev.currentTarget;\n const newIndex = Array.prototype.indexOf.call(this.tabs, newTab);\n if (oldIndex === newIndex) {\n return;\n }\n oldTab.setAttribute('aria-selected', false);\n newTab.setAttribute('aria-selected', true);\n const oldPane = this.panes[oldIndex];\n if (oldPane) {\n oldPane.hidden = true;\n }\n const newPane = this.panes[newIndex];\n if (!newPane) {\n return;\n }\n newPane.hidden = false;\n // Focus on first field.\n newPane.querySelector('[data-name]').focus();\n }\n}\n\nexport default Tabs;\n", "/* eslint-disable no-case-declarations */\nimport Tabs from './Tabs.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n

    \n

    \n
    \n`;\nclass SheetView extends HTMLElement {\n /**\n * @param {EventEmitter} emitter\n * @param {Node} templateNode Cloned node from child element.\n */\n constructor ({\n emitter = null,\n templateNode = null\n }) {\n super();\n this.emitter = emitter;\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n // Append child node template to header.\n if (templateNode) {\n this.shadowRoot.appendChild(templateNode);\n }\n // Selector hook so we can always find regardless of child class.\n this.dataset.sheetview = 'true';\n }\n\n connectedCallback () {\n this.mainTabs = new Tabs(this.shadowRoot.querySelector('ul[role=tablist]'));\n // Listen for events emitted from the components\n this.shadowRoot.addEventListener('fieldChange', this._handleFieldChange.bind(this));\n Array.from(this.shadowRoot.querySelectorAll('input[type=number]')).forEach((el) => {\n el.addEventListener('change', this._numberInputChange.bind(this));\n });\n\n this.emitter.on('tab:switch', this.switchToPane, this);\n }\n\n disconnectedCallback () {\n // Listen for events emitted from the components\n this.shadowRoot.removeEventListener('fieldChange', this._handleFieldChange.bind(this));\n Array.from(this.shadowRoot.querySelectorAll('input[type=number]')).forEach((el) => {\n el.removeEventListener('change', this._numberInputChange.bind(this));\n });\n\n this.emitter.off('tab:switch', this.switchToPane, this);\n\n // Remove footer links.\n const nav = document.querySelector('footer-nav');\n nav.removeLinks();\n }\n /**\n * Override in child to check correct class is set.\n * @param {Character} character\n */\n _validateCharacter (character) {\n throw new Error('Invalid character type for this view.');\n }\n /**\n * @param {Character}\n */\n set character (character) {\n this._validateCharacter(character);\n this.cur_character = character;\n this.emitter.trigger('character:set');\n // render character.\n this.renderCharacter();\n }\n /**\n * @returns {Character}\n */\n get character () {\n return this.cur_character;\n }\n /**\n * Change the main tab pane.\n * @param {String} targetPane\n */\n switchToPane (targetPane) {\n if (!this.mainTabs) {\n return;\n }\n this.mainTabs.switchToPane(targetPane);\n }\n /**\n * Handle setting custom fields.\n * @param {HTMLElement} el Editable element of some type\n * @param {String} fieldName Character field\n * @param {String} subFieldName Character Subfield\n * @param {Any} charValue Character's value for field/subfield.\n * @returns {Boolean}\n */\n _renderCustomFields (el, fieldName, subFieldName, charValue) {\n return false;\n }\n /**\n * Any actions to perform after rendering all the fields.\n */\n _renderCustomPost () {\n }\n /**\n * Take character data and fill it into the page\n */\n renderCharacter () {\n if (this.cur_character === null) {\n return;\n }\n\n this.shadowRoot.querySelector('[data-name=\"charname\"]').content = this.cur_character.charname;\n\n const fields = Array.from(this.shadowRoot.querySelectorAll('*[data-name]'));\n fields.forEach((el) => {\n const f = el.getAttribute('data-name');\n if (typeof this.cur_character[f] === 'undefined') {\n return;\n }\n const subf = el.getAttribute('data-subfield');\n const charValue = (subf) ? this.cur_character[f][subf] : this.cur_character[f];\n switch (el.tagName) {\n case 'INPUT':\n case 'TEXTAREA':\n case 'SELECT':\n // Make sure numbers default to 0.\n // this is especially relevant for spell slots.\n if (el.getAttribute('type') === 'number') {\n el.value = charValue || 0;\n } else {\n el.value = charValue || '';\n }\n // For spell slot input we need to trigger the display or not of spells\n const event = new Event('change');\n el.dispatchEvent(event);\n break;\n case 'SIMPLE-LIST':\n el.clear();\n const listItems = charValue || [];\n if (listItems.length > 0) {\n listItems.forEach((item) => {\n if (item.length === 0) {\n return;\n }\n el.addItem(item);\n });\n }\n el.addItem();\n break;\n case 'NOTE-LIST':\n el.clear();\n const noteItems = charValue || [];\n if (noteItems.length > 0) {\n noteItems.forEach((item) => {\n if (item.length === 0) {\n return;\n }\n el.addItem(item);\n });\n }\n el.addItem();\n break;\n case 'TABLE-EDITABLE':\n el.clear();\n const rowItems = charValue || [];\n if (rowItems.length > 0) {\n rowItems.forEach((item) => {\n if (item.length === 0) {\n return;\n }\n el.addRow(item);\n });\n }\n el.addRow();\n break;\n case 'FIELD-EDITABLE':\n el.content = charValue || '';\n break;\n\n default:\n // Custom fields by character type\n if (!this._renderCustomFields(\n el,\n f,\n subf,\n charValue\n )) {\n // Try for basic content editable.\n if (el.getAttribute('content-editable') === 'true') {\n el.innerHTML = charValue || '';\n }\n }\n }\n });\n\n this._renderCustomPost();\n\n this.emitter.trigger('dialog:save:hide');\n }\n /**\n * Trigger the event to show there are unsaved changes.\n */\n _showUnsavedDialog () {\n this.emitter.trigger('dialog:save:show');\n }\n /**\n * Compare two properties to see if they are different\n * For objects/arrays we need to account for them being different objects\n * that have the same properties and values.\n * @param {String|Number|Array|Object|Boolean} valold Existing property value\n * @param {String|Number|Array|Object|Boolean} valnew New property value\n * @return {Boolean}\n */\n _sameValues (valold, valnew) {\n // for efficiency we could do typeof checks\n // and only use JSON for objects...\n return JSON.stringify(valold) === JSON.stringify(valnew);\n }\n /**\n * Handle field change for those that need special handling.\n * in child\n * @param {CustomEvent} ev\n * @param {String} field Field name\n * @param {String} subfield Subfield name\n * @returns {Boolean} On true return from the parent handler.\n */\n _customFieldChange (ev, field, subfield) {\n return false;\n }\n /**\n * When a field is changed in the UI.\n * Update the character and trigger save dialog\n * Only if the value is actually different.\n * @param {CustomEvent} ev\n */\n _handleFieldChange (ev) {\n const field = ev.detail.field || '';\n const subfield = ev.detail.subfield || '';\n if (!field) {\n return;\n }\n const cur_character = this.cur_character;\n if (typeof cur_character[field] === 'undefined') {\n return;\n }\n\n if (this._customFieldChange(ev, field, subfield)) {\n return;\n }\n\n const newValue = ev.detail.value;\n if (subfield) {\n if (typeof cur_character[field] !== 'object' || Array.isArray(cur_character[field])) {\n return;\n }\n const currentVal = cur_character[field][subfield];\n if (!this._sameValues(currentVal, newValue)) {\n cur_character[field][subfield] = ev.detail.value;\n this._showUnsavedDialog();\n }\n return;\n }\n const currentVal = cur_character[field];\n if (!this._sameValues(currentVal, newValue)) {\n cur_character[field] = newValue;\n this._showUnsavedDialog();\n }\n }\n\n _customNumberInputChange () {\n }\n /**\n * Handle input[name=number] changes.\n * @param {Event} ev\n */\n _numberInputChange (ev) {\n const field = ev.target.dataset.name;\n const subfield = ev.target.dataset.subfield;\n if (typeof this.cur_character[field][subfield] === 'undefined') {\n return;\n }\n const newValue = parseInt(ev.target.value, 10);\n this.cur_character[field][subfield] = newValue;\n this.emitter.trigger('dialog:save:show');\n\n this._customNumberInputChange(ev);\n }\n\n navigateTo (id) {\n const el = this.shadowRoot.querySelector(id);\n if (el) {\n el.scrollIntoView();\n // Focus only works sometimes depending on the element...\n // @todo fix that.\n el.focus();\n }\n }\n}\n\nif (!window.customElements.get('sheet-view')) {\n window.customElements.define('sheet-view', SheetView);\n}\n\nexport default SheetView;\n", "/* eslint-disable no-case-declarations */\nimport Character5e from '../models/Character5e.js';\nimport Weapon from '../models/Weapon.js';\nimport SheetView from './SheetView.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n
    \n
    \n
    \n
    \n
    Class
    \n
    \n
    \n
    Race
    \n
    \n
    \n
    Background
    \n
    \n
    \n
    Alignment
    \n
    \n
    \n
    Level
    \n
    \n
    \n
    Experience
    \n
    \n
    \n
    Proficiency Bonus
    \n
    \n
    \n
    Inspiration
    \n
    \n
    \n
    Speed
    \n
    \n
    \n
    Hit Dice
    \n
    \n / \n
    \n
    \n
    \n
    Armor Class
    \n
    \n
    \n
    Hit Points
    \n
    \n / \n
    \n
    \n
    \n
    Death Save Success/Fail
    \n
    \n \n /\n \n
    \n
    \n
    \n
    Class Points
    \n
    \n / \n
    \n
    \n
    \n
    \n\n
    \n

    Attributes

    \n
    \n Str\n Dex\n Con\n Int\n Wis\n Cha\n
    \n\n

    Skills

    \n
    \n Acrobatics (Dex)\n Animal Handling (Wis)\n Arcana (Int)\n Athletics (Str)\n Deception (Cha)\n History (Int)\n Insight (Wis)\n Intimidation (Cha)\n Investigation (Int)\n Medicine (Wis)\n Nature (Int)\n Perception (Wis)\n Performance (Cha)\n Persuasion (Cha)\n Religion (Int)\n Sleight of Hand (Dex)\n Stealth (Dex)\n Survival (Wis)\n
    \n
    \n\n
    \n

    Dice Roller

    \n \n \n \n \n \n \n \n \n

    Weapons & Attacks

    \n \n\n

    Features & Traits

    \n \n\n

    Other Proficiencies

    \n \n\n

    Equipment

    \n \n\n
    \n
    \n
    CP
    \n
    SP
    \n
    \n
    \n
    GP
    \n
    PP
    \n
    \n
    \n
    \n\n
    \n

    Spells

    \n\n
    \n
    \n
    Spell Ability
    \n
    \n
    \n
    Spell Save DC
    \n
    \n
    \n
    Spell Attack Bonus
    \n
    \n
    \n\n \n

    Spell Slots

    \n\n
    \n
    \n
    1st
    \n
    \n \n /\n \n
    \n
    2nd
    \n
    \n \n /\n \n
    \n
    \n
    \n
    3rd
    \n
    \n \n /\n \n
    \n
    4th
    \n
    \n \n /\n \n
    \n
    \n
    \n
    5th
    \n
    \n \n /\n \n
    \n
    6th
    \n
    \n \n /\n \n
    \n
    \n
    \n
    7th
    \n
    \n \n /\n \n
    \n
    8th
    \n
    \n \n /\n \n
    \n
    \n
    \n
    9th
    \n
    \n \n /\n \n
    \n
    \n
    \n
    \n\n
    \n

    Cantrips

    \n \n
    \n \n \n \n \n \n \n \n \n \n
    \n\n\n`;\nclass Character5eSheet extends SheetView {\n /**\n * @param {EventEmitter} emitter\n */\n constructor ({\n emitter\n }) {\n super({\n emitter,\n templateNode: template.content.cloneNode(true)\n });\n this.spellButtons = [];\n }\n\n connectedCallback () {\n super.connectedCallback();\n // Listen for events emitted from the components\n this.shadowRoot.addEventListener('attributeChange', this._handleAttributeChange.bind(this));\n this.shadowRoot.addEventListener('saveChange', this._handleSaveChange.bind(this));\n\n this.emitter.on('character:skill:update', this._updateSkillMod, this);\n this.emitter.on('character:proficiency:update', this._updateProficiency, this);\n this.emitter.on('character:attribute:update', this._updateAttributeMods, this);\n this.emitter.on('character:save:update', this._updateSaveMods, this);\n this.emitter.on('character:set', this._addSpellButtonEvents, this);\n this.emitter.on('character:update:spells', this._updateSpellList, this);\n\n // Set footer links.\n const nav = document.querySelector('footer-nav');\n if (nav) {\n nav.setLinks([\n { label: 'Attributes', tab: 'pane-stats', href: '#page-attributes' },\n { label: 'Skills', tab: 'pane-stats', href: '#page-skills' },\n { label: 'Spells', tab: 'pane-stats', href: '#page-spells' },\n { label: 'Notes', tab: 'pane-notes', href: '#page-notes_adv' }\n ]);\n }\n }\n\n disconnectedCallback () {\n super.disconnectedCallback();\n // Listen for events emitted from the components\n this.shadowRoot.removeEventListener('attributeChange', this._handleAttributeChange.bind(this));\n this.shadowRoot.removeEventListener('saveChange', this._handleSaveChange.bind(this));\n\n this.emitter.off('character:skill:update', this._updateSkillMod, this);\n this.emitter.off('character:proficiency:update', this._updateProficiency, this);\n this.emitter.off('character:attribute:update', this._updateAttributeMods, this);\n this.emitter.off('character:save:update', this._updateSaveMods, this);\n this.emitter.off('character:set', this._addSpellButtonEvents, this);\n this.emitter.off('character:update:spells', this._updateSpellList, this);\n }\n\n _updateSpellList () {\n const fields = this.shadowRoot.querySelectorAll('[data-name=\"spells\"]');\n\n fields.forEach((el) => {\n const f = el.dataset.name || '';\n \n if (typeof this.cur_character[f] === 'undefined' || f === '') {\n return;\n };\n\n const subf = el.dataset.subfield || '';\n const charValue = (subf !== '') ? this.cur_character[f][subf] : this.cur_character[f];\n // spells added the the current character\n const listItems = charValue || [];\n \n el.clear();\n\n listItems.forEach((item) => {\n if (!item) {\n return;\n };\n el.addItem(item);\n });\n\n if (listItems.length === 0) el.addItem();\n });\n };\n\n /**\n * @param {Character5e}\n */\n _validateCharacter (character) {\n if (!(character instanceof Character5e)) {\n throw new Error('Invalid character type for this view.');\n }\n }\n\n _renderCustomFields (el, fieldName, subFieldName, charValue) {\n switch (el.tagName) {\n case 'SKILL-LISTING':\n el.skillValue = charValue || 0;\n el.skillMod = this.cur_character.getSkillMod(subFieldName);\n return true;\n case 'ATTR-LISTING':\n el.attributeScore = charValue || 10;\n el.attributeMod = this.cur_character.attributeMod(fieldName);\n el.saveProficiency = this.cur_character.saves[fieldName];\n el.saveMod = this.cur_character.saveMod(fieldName);\n return true;\n }\n return false;\n }\n\n _renderCustomPost () {\n this.shadowRoot.querySelector('[data-name=\"proficiency\"]').innerHTML = this.cur_character.proficiency;\n }\n\n _customFieldChange (ev, field, subfield) {\n if (field === 'skills') {\n const currentVal = this.character.getSkill(subfield);\n if (!this._sameValues(currentVal, ev.detail.value)) {\n this.character.setSkill(subfield, ev.detail.value);\n this._showUnsavedDialog();\n }\n return true;\n }\n if (field === 'weapons') {\n const currentVal = this.character[field];\n const newValue = ev.detail.value.map((object) => {\n return new Weapon(object);\n });\n if (!this._sameValues(currentVal, newValue)) {\n this.character[field] = newValue;\n this._showUnsavedDialog();\n }\n return true;\n }\n }\n /**\n * Update a skill's modifier in the UI.\n * @param {String} skill\n * @param {String} modifier\n */\n _updateSkillMod (skill, modifier) {\n const el = this.shadowRoot.querySelector(`skill-listing[data-subfield=\"${skill}\"]`);\n if (!el) {\n return;\n }\n el.skillMod = modifier;\n }\n /**\n * Update the proficiency modifier in the UI.\n */\n _updateProficiency () {\n const proficiency = this.cur_character.proficiency;\n this.shadowRoot.querySelector('[data-name=\"proficiency\"]').innerHTML = proficiency;\n\n Array.from(this.shadowRoot.querySelectorAll('skill-listing')).forEach((el) => {\n const skill = el.skillName;\n el.skillMod = this.cur_character.getSkillMod(skill);\n });\n\n Array.from(this.shadowRoot.querySelectorAll('attr-listing')).forEach((el) => {\n const attr = el.attributeName;\n el.saveMod = this.cur_character.saveMod(attr);\n });\n }\n /**\n * Update an attribute's modifier in the UI.\n * @param {String} attribute\n */\n _updateAttributeMods (attribute) {\n const el = this.shadowRoot.querySelector(`attr-listing[data-name=${attribute}]`);\n if (!el) {\n return;\n }\n el.attributeMod = this.cur_character.attributeMod(attribute);\n el.saveMod = this.cur_character.saveMod(attribute);\n }\n /**\n * Update a save modifier in the UI.\n * @param {String} attribute\n */\n _updateSaveMods (attribute) {\n const el = this.shadowRoot.querySelector(`attr-listing[data-name=${attribute}]`);\n if (!el) {\n return;\n }\n el.saveMod = this.cur_character.saveMod(attribute);\n }\n /**\n * Handle input[name=number] changes.\n * @param {Event} ev\n */\n _customNumberInputChange (ev) {\n const field = ev.target.dataset.name;\n const subfield = ev.target.dataset.subfield;\n const newValue = parseInt(ev.target.value, 10);\n if (field === 'spell_slots') {\n const spellList = this.shadowRoot.querySelector(`[data-name=\"spells\"][data-subfield=\"${subfield}\"]`);\n if (!newValue) {\n // this covers 0 and NaN\n spellList.parentNode.hidden = true;\n } else {\n spellList.parentNode.hidden = false;\n }\n }\n }\n /**\n * When an attribute is changed in the UI.\n * @param {CustomEvent} ev\n */\n _handleAttributeChange (ev) {\n const field = ev.detail.field || '';\n if (!field) {\n return;\n }\n this.cur_character.setAttribute(field, ev.detail.value);\n this._showUnsavedDialog();\n }\n /**\n * When a save is (un)checked in the UI.\n * @param {CustomEvent} ev\n */\n _handleSaveChange (ev) {\n const field = ev.detail.field || '';\n if (!field) {\n return;\n }\n this.cur_character.setSaveProficiency(field, ev.detail.value);\n this._showUnsavedDialog();\n }\n}\n\nif (!window.customElements.get('sheet-view-5e')) {\n window.customElements.define('sheet-view-5e', Character5eSheet);\n}\n\nexport default Character5eSheet;\n", "import CharacterVagabonds from '../models/CharacterVagabonds.js';\nimport SheetView from './SheetView';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n\n
    \n
    \n
    \n
    \n
    Conflict Approach
    \n
    \n
    \n
    Goal
    \n
    \n
    \n
    Gimmick
    \n
    \n
    \n
    Background
    \n
    \n
    \n
    Foreground
    \n
    \n
    \n
    Weakness
    \n
    \n
    \n
    Core Flaw
    \n
    \n
    \n
    Level
    \n
    \n
    \n
    Experience
    \n
    \n
    \n
    Initiative
    \n
    \n
    \n
    Armor
    \n
    \n
    \n
    Hit Points
    \n
    \n / \n
    \n
    \n
    \n
    Injuries
    \n
    \n \n
    \n
    \n
    \n
    Coins
    \n
    \n
    \n
    Level Traits/Tags
    \n
    \n \n
    \n
    \n
    \n
    Lineage
    \n
    \n
    \n
    \n\n
    \n

    Dice Roller

    \n \n \n \n

    Techniques

    \n \n\n

    Inventory

    \n \n
    \n
    \n\n\n`;\n\nclass CharacterVagabondsSheet extends SheetView {\n /**\n * @param {EventEmitter} emitter\n */\n constructor ({\n emitter\n }) {\n super({\n emitter,\n templateNode: template.content.cloneNode(true)\n });\n }\n\n connectedCallback () {\n super.connectedCallback();\n\n // Set footer links.\n const nav = document.querySelector('footer-nav');\n if (nav) {\n nav.setLinks([\n { label: 'Attributes', tab: 'pane-stats', href: '#page-attributes' },\n { label: 'Notes', tab: 'pane-notes', href: '#page-notes' }\n\n ]);\n }\n }\n\n disconnectedCallback () {\n super.disconnectedCallback();\n }\n /**\n * Override in child to check correct class is set.\n * @param {CharacterVagabonds} character\n */\n _validateCharacter (character) {\n if (!(character instanceof CharacterVagabonds)) {\n throw new Error('Invalid character type for this view.');\n }\n }\n}\n\nif (!window.customElements.get('sheet-view-vagabonds')) {\n window.customElements.define('sheet-view-vagabonds', CharacterVagabondsSheet);\n}\n\nexport default CharacterVagabondsSheet;\n", "{\n \"name\": \"character-sheet-app\",\n \"version\": \"4.5.3\",\n \"description\": \"Online character sheet for Tabletop Role-Playing Games\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/derikb/character-sheet-app.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/derikb/character-sheet-app/issues\"\n },\n \"homepage\": \"https://github.com/derikb/character-sheet-app#readme\",\n \"keywords\": [\n \"d&d\",\n \"rpg\",\n \"ttrpg\",\n \"character sheet\"\n ],\n \"author\": \"Derik A Badman\",\n \"license\": \"GPL-3.0\",\n \"dependencies\": {\n \"firebase\": \"^10.1.0\",\n \"rpg-table-randomizer\": \"^1.3.2\"\n },\n \"devDependencies\": {\n \"@stylistic/eslint-plugin-js\": \"^2.1.0\",\n \"commit-and-tag-version\": \"^12.0.0\",\n \"esbuild\": \"^0.21\",\n \"eslint\": \"^9.4.0\",\n \"globals\": \"^15.3.0\",\n \"normalize.css\": \"^8.0.1\"\n },\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"start\": \"esbuild --serve=8080 --servedir=./dist ./src/styles.css ./src/index.js ./src/service_worker.js --outdir=./dist --loader:.svg=dataurl --loader:.html=file --bundle\",\n \"build\": \"esbuild ./src/styles.css ./src/index.js ./src/service_worker.js --outdir=./dist --loader:.svg=dataurl --loader:.html=file --minify --sourcemap --bundle\",\n \"release\": \"commit-and-tag-version -a\",\n \"eslint\": \"eslint ./src\"\n },\n \"commit-and-tag-version\": {\n \"scripts\": {\n \"postbump\": \"npm run build && git add ./dist/service_worker.js ./dist/service_worker.js.map ./dist/index.js ./dist/index.js.map ./dist/styles.css ./dist/styles.css.map\"\n },\n \"bumpFiles\": [\n \"package.json\",\n \"package-lock.json\"\n ]\n }\n}\n", "/**\n * Service for retrieving, saving, deleting characters.\n * For now LocalStorage only, but potentially adaptable to different stores.\n */\nimport Character from '../models/Character.js';\nimport Character5e from '../models/Character5e.js';\nimport CharacterVagabonds from '../models/CharacterVagabonds.js';\nimport Storage from './Storage.js';\nimport Database from './Database.js';\nimport { isAuthed } from './AuthService.js';\nimport Character5eSheet from '../views/Character5eSheet.js';\nimport CharacterVagabondsSheet from '../views/CharacterVagabondsSheet.js';\nimport SheetView from '../views/SheetView.js';\nimport { version } from '../../package.json';\n\n/**\n * Compare character version against another version.\n * For any future version based data manipulation.\n *\n * @param {String} charVersion Character semver version number.\n * @param {String} compareVersion Another semver version to compare against.\n * @returns {Boolean} True if charVersion is higher/newert than the compare version.\n */\nconst isCharVersionNewer = function (charVersion, compareVersion) {\n // bacwards compatible\n if (charVersion === '') {\n return false;\n }\n return charVersion.localeCompare(compareVersion, undefined, { numeric: true }) > 0;\n};\n\n/**\n * Currently loaded character data is here\n * @prop {Character|null}\n */\nlet cur_character = null;\n/**\n * @prop {String} appVersion Current app version.\n */\nconst appVersion = version;\n/**\n * Return UTC datetime string for right now\n * @return {String}\n */\nconst currentTimestamp = function () {\n const d = new Date();\n return d.toUTCString();\n};\n/**\n * Get a unique 7 character key to use for a new character.\n * @returns {String}\n */\nconst generateCharacterKey = function () {\n let key = (`${Math.random().toString(36)}00000000000000000`).slice(2, 9);\n while (getCharacter(key) !== null) {\n key = (`${Math.random().toString(36)}00000000000000000`).slice(2, 9);\n }\n return key;\n};\n\n/**\n * Options for games characters can be created for.\n * @todo probably should have a constant file for these.\n * @returns {String[]}\n */\nconst getGameOptions = function () {\n return [\n 'Character5e',\n 'CharacterVagabonds'\n ];\n};\n\n/**\n * Get a Character of appropriate class.\n * @param {String} type className for model.\n * @param {Object} obj Character data.\n * @returns {Character}\n */\nconst characterFactory = function (type, obj) {\n switch (type) {\n // Backwards compatible\n // and default\n case undefined:\n case '':\n case 'Character5e':\n return new Character5e(obj);\n case 'CharacterVagabonds':\n return new CharacterVagabonds(obj);\n default:\n return new Character(obj);\n }\n};\n\n/**\n * Return a new character for a key.\n * @param {String} key\n * @param {String} type Model className\n * @returns {Character}\n */\nconst newCharacter = function (key, type = 'Character5e') {\n return characterFactory(type, { key });\n};\n/**\n * Get a single character model.\n * @param {String} key Character's key.\n * @returns {Character|null}\n */\nconst getCharacter = function (key) {\n if (!key) {\n return null;\n }\n const char_obj = Storage.get(key);\n if (!char_obj || !char_obj.key) {\n return null;\n }\n return characterFactory(char_obj.className, char_obj);\n};\n/**\n * Get a single character model.\n * @param {String} key Character's key.\n * @returns {Character|null}\n * @throws Error\n */\nconst getCharacterRemote = async function (key) {\n if (!key) {\n return null;\n }\n const char_obj = await Database.get(key);\n if (!char_obj || !char_obj.key) {\n return null;\n }\n return characterFactory(char_obj.className, char_obj);\n};\n/**\n * Save a single character.\n * @param {Character} character\n * @returns {Boolean}\n */\nconst saveCharacter = function (character) {\n // Update saved timestamp\n character.updated = currentTimestamp();\n character.version = appVersion;\n return Storage.set(character.key, character);\n};\n/**\n * Save a single character to the remote.\n * @param {Character} character\n * @returns {Boolean}\n * @throws Error\n */\nconst saveCharacterRemote = async function (character) {\n // Update saved timestamp\n // character.updated = currentTimestamp();\n return await Database.set(character.key, character.toJSON());\n};\n/**\n * Remove a character from the store.\n * @param {String} key\n */\nconst removeCharacterLocal = function (key) {\n Storage.remove(key);\n};\n/**\n * Remove a character from the remote.\n * @param {String} key\n * @throws Error\n */\nconst removeCharacterRemote = async function (key) {\n return Database.remove(key);\n};\n/**\n * Get all characters saved locally.\n * @returns {Character[]}\n */\nconst getAllCharactersLocal = function () {\n const characters = [];\n Storage.getAll().forEach((char_obj) => {\n characters.push(\n characterFactory(char_obj.className, char_obj)\n );\n });\n return characters;\n};\n/**\n * Get all characters saved to the remote database.\n * @returns {Map} entries are Character keyed to the key property.\n * @throws Error\n */\nconst getAllCharactersRemote = async function () {\n const characters = new Map();\n if (!isAuthed()) {\n return [];\n }\n const char_objects = await Database.getAll();\n char_objects.forEach((char_obj) => {\n const char = characterFactory(char_obj.className, char_obj);\n characters.set(char.key, char);\n });\n return characters;\n};\n/**\n * Import/save a character from an obj and return the model.\n * @param {Object} char_obj Character data from backup (we hope).\n * @returns {Character}\n * @throws {Error}\n */\nconst importCharacter = function (char_obj) {\n if (typeof char_obj !== 'object' || !char_obj.key) {\n throw new Error(`Data appears to be invalid. Try removing any text that isn't part of the backup (i.e. email introduction).`);\n }\n const newCharacter = characterFactory(char_obj.className, char_obj);\n // do we have this char key already\n const existingCharacter = getCharacter(char_obj.key);\n if (existingCharacter && existingCharacter.charname !== '' && existingCharacter.charname !== newCharacter.charname) {\n // existing key but different name\n if (!newCharacter.key_prev) {\n newCharacter.key_prev = newCharacter.key;\n newCharacter.key = generateCharacterKey();\n } else {\n const temp_key = newCharacter.key_prev;\n newCharacter.key_prev = newCharacter.key;\n newCharacter.key = temp_key;\n }\n }\n saveCharacter(newCharacter);\n return newCharacter;\n};\n/**\n * Set prefix for LocalStorage keys.\n * @param {String} prefix\n */\nconst setLocalStoragePrefix = function (prefix) {\n if (!prefix) {\n throw Error('LocalStorage prefix is empty.');\n }\n Storage.setPrefix(prefix);\n};\n\n/**\n * Set current character based on key.\n * Returns null if key is not locally set.\n * @param {String} key\n * @param {String} type Type of character to create.\n * @param {Boolean} createOnEmpty Create new character if the key isn't found.\n * @returns {Character|null}\n */\nconst setCurrentCharacter = function (key, type, createOnEmpty = false) {\n let char = getCharacter(key);\n if (!char) {\n if (!createOnEmpty) {\n return null;\n }\n char = newCharacter(key, type);\n }\n cur_character = char;\n return cur_character;\n};\n\n/**\n * Get character currently displayed.\n * @returns {Character|null}\n */\nconst getCurrentCharacter = function () {\n return cur_character;\n};\n/**\n * Just the key for the current character.\n * @returns {String}\n */\nconst getCurrentCharacterKey = function () {\n return !cur_character ? '' : cur_character.key;\n};\n/**\n * Save the current character locally.\n */\nconst saveCurrentCharacter = function () {\n if (!cur_character) {\n throw new Error('No character is set.');\n }\n if (cur_character.charname === '') {\n throw new Error('Your character must have name to save!');\n }\n saveCharacter(cur_character);\n};\n/**\n * Get the right view for a character\n * @param {Character} character\n * @param {EventEmitter} emitter\n * @returns {SheetView}\n */\nconst getSheetView = function (character, emitter) {\n let view = null;\n switch (character.className) {\n // Backwards compatible\n case undefined:\n case 'Character5e':\n view = new Character5eSheet({ emitter });\n break;\n case 'CharacterVagabonds':\n view = new CharacterVagabondsSheet({ emitter });\n break;\n default:\n view = new SheetView({ emitter });\n break;\n }\n return view;\n};\n\nexport {\n getGameOptions,\n generateCharacterKey,\n getCharacter,\n getCharacterRemote,\n saveCharacter,\n saveCharacterRemote,\n removeCharacterLocal,\n removeCharacterRemote,\n getAllCharactersLocal,\n getAllCharactersRemote,\n importCharacter,\n setLocalStoragePrefix,\n getCurrentCharacter,\n setCurrentCharacter,\n getCurrentCharacterKey,\n saveCurrentCharacter,\n getSheetView\n};\n", "/**\n * Handing keyboard shortcuts.\n */\nclass ShortCutKeys {\n /**\n * @param {EventEmitter} emitter\n */\n constructor (emitter) {\n this.emitter = emitter;\n this.shortcuts = {};\n document.addEventListener('keydown', this.checkShortCuts.bind(this));\n }\n /**\n * Add a shortcut that triggers an event.\n * @param {String} keys Key Combo use 'Ctrl+' and 'Shift+' to indicate those keys.\n * @param {String} event Event to emit.\n */\n addShortCut (keys, event) {\n this.shortcuts[keys] = event;\n }\n /**\n * Generate the key combo as a string.\n * @param {String} key Key pressed.\n * @param {Boolean} withControl Was control pressed.\n * @param {Boolean} withShift Was shift pressed.\n */\n getKeyCode (key, withControl, withShift) {\n let code = '';\n if (withControl) {\n code += 'Ctrl+';\n }\n if (withShift) {\n code += 'Shift+';\n }\n code += key;\n return code;\n }\n /**\n * Handler: Keydown event.\n * @param {KeyboardEvent} ev Keydown\n */\n checkShortCuts (ev) {\n let withControl = false;\n let withShift = false;\n if (ev.ctrlKey) {\n withControl = true;\n }\n if (ev.shiftKey) {\n withShift = true;\n }\n const key = ev.key;\n const code = this.getKeyCode(key, withControl, withShift);\n const event = this.shortcuts[code] || null;\n if (event) {\n ev.preventDefault();\n ev.stopPropagation();\n this.emitter.trigger(event);\n }\n }\n}\n\nexport default ShortCutKeys;\n", "/**\n * Manager:\n * Interface for save/backup/restore of data...\n */\nimport { generateCharacterKey, getCharacter, removeCharacterLocal, importCharacter, setLocalStoragePrefix, setCurrentCharacter, saveCurrentCharacter, getCurrentCharacterKey, getSheetView, getAllCharactersLocal } from '../services/CharacterService.js';\nimport ShortCutKeys from './ShortCutKeys.js';\nimport { monitorAuth } from '../services/AuthService.js';\n\nconst Manager = {\n /** @prop {EventEmitter} */\n emitter: null,\n /**\n * App name used in character model app property\n */\n appname: '',\n /**\n * Unsaved dialog\n */\n dialog_unsaved: document.querySelector('.alert-unsaved'),\n /**\n * Undo delete dialog\n */\n dialog_undo: document.querySelector('.alert-delete'),\n /**\n * Start a new character and change the hash.\n */\n triggerNewCharacter: function (char_type = '') {\n const key = generateCharacterKey();\n this.loadCharacter(key, char_type)\n .then(() => {\n window.location.hash = `#${key}`;\n })\n .catch((err) => {\n console.log(err);\n });\n },\n /**\n * Change the character based on a hash change\n * or maybe I should process the event in the handler and pass it here if necessary...\n */\n changeCharacter: function () {\n const urlhash = window.location.hash.substring(1);\n // No need if the character is already loaded.\n const cur_character_key = getCurrentCharacterKey();\n if (cur_character_key && urlhash === cur_character_key) {\n return;\n }\n this.loadCharacter(urlhash);\n },\n /**\n * Load character data based on a key\n * @param {String} key Character identifier\n * @param {String} char_type Character class type.\n */\n loadCharacter: async function (key, char_type = '') {\n this.hideUnsavedDialog();\n // Set character or creates one.\n const cur_character = setCurrentCharacter(key, char_type, true);\n cur_character.emitter = this.emitter;\n // Load up correct view\n const sheetView = getSheetView(cur_character, this.emitter);\n document.querySelector('main').innerHTML = '';\n document.querySelector('main').appendChild(\n sheetView\n );\n sheetView.character = cur_character;\n this.emitter.trigger('loaddialog:close');\n this.emitter.trigger('newdialog:close');\n },\n /**\n * Save character data\n */\n saveCharacter: function () {\n // For fields saved on blur we need to trigger it on the active field.\n // Fields that save on change will already have saved.\n if (document.activeElement) {\n const event = new Event('blur');\n document.activeElement.dispatchEvent(event);\n }\n try {\n saveCurrentCharacter();\n } catch (e) {\n this.emitter.trigger('error:display', e.message);\n return;\n }\n this.hideUnsavedDialog();\n },\n /**\n * Save a file of the current character\n * Falls back to showing the data for copy/pasting\n */\n downloadBackup: function (form) {\n const data = [];\n const names = [];\n const checks = Array.from(form.querySelectorAll('input[type=checkbox]:checked'));\n checks.forEach((ch) => {\n const character = getCharacter(ch.value);\n data.push(character);\n names.push(character.charname);\n });\n\n const format = form.querySelector('input[name=format]:checked').value;\n const date = new Date();\n\n if (format === 'email') {\n const body = `Below is the backup data for your character(s) ${names.join(', ')}.\n\nTo use this data, go to: ${window.location.href} and click the \"Restore Backup\" button. Then paste the text below into the box.\n\n---\n\n${JSON.stringify(data)}`;\n\n const url = `mailto:?subject=${encodeURIComponent(`Character backup: ${names.join(', ')} (${date.toLocaleString()})`)}&body=${encodeURIComponent(body)}`;\n\n // Sadly this simple solution doesn't work in iOS\n // document.location.href = url;\n this.emitter.trigger('backup:email', url);\n } else {\n if (typeof window.Blob !== 'function') {\n // fallback to displaying the data for copy/pasting\n this.emitter.trigger('backup:textpaste', JSON.stringify(data));\n return;\n }\n // for env that support it, create a file for download\n const a = document.createElement('a');\n const file = new Blob([JSON.stringify(data)], { type: 'application/json' });\n const url = URL.createObjectURL(file);\n a.href = url;\n a.download = `${this.appname}_${date.getFullYear()}_${date.getMonth() + 1}_${date.getDate()}`;\n document.body.appendChild(a);\n a.click();\n setTimeout(function () {\n document.body.removeChild(a);\n window.URL.revokeObjectURL(url);\n }, 0);\n }\n },\n /**\n * Restore Backup form handler\n * @param {HTMLElement} form\n */\n restoreFormSubmit: function (form) {\n const input_file = form.querySelector('input[type=file]');\n const input = form.querySelector('textarea');\n if (input_file.files && input_file.files.length > 0) {\n Array.from(input_file.files).forEach((f) => {\n const reader = new FileReader();\n // Closure to capture the file information.\n reader.onload = (() => {\n return (e) => {\n this.restoreCharacters(e.target.result);\n };\n })(f);\n reader.readAsText(f);\n });\n } else if (input.value !== '') {\n this.restoreCharacters(input.value);\n }\n },\n /**\n * Take json backup data and load the character(s)\n * @param {String} data JSON string we hope\n */\n restoreCharacters: function (data) {\n try {\n // look for the start of the JSON string Array of Objects\n let start = data.indexOf('[{');\n let end = data.lastIndexOf('}]');\n // make sure it's not :[{, an array of objects inside one of the objects\n const check = data.indexOf(':[{');\n if (check !== -1 && check < start) {\n // if so start over\n start = -1;\n }\n if (start === -1) {\n start = data.indexOf('{');\n end = data.lastIndexOf('}');\n data = data.substring(start);\n data = data.substring(0, end + 1);\n } else {\n data = data.substring(start);\n data = data.substring(0, end + 2);\n }\n data = data.trim(); // just in case\n\n // convert linebreaks to html br else JSON.parse breaks\n // first make sure it's not a break between objects...\n data = data.replace(/\\},[\\r\\n]+\\{/g, '},{');\n data = data.replace(/(?:\\r\\n|\\r|\\n)/g, '
    ');\n let backups = JSON.parse(data);\n // make it an array\n if (!Array.isArray(backups)) {\n backups = [backups];\n }\n const imported_chars = [];\n let reloadCurrentChar = false;\n const currentCharKey = getCurrentCharacterKey();\n backups.forEach((char_obj) => {\n const newCharacter = importCharacter(char_obj);\n // if its the current character we should reload them\n if (newCharacter.key === currentCharKey) {\n reloadCurrentChar = true;\n }\n const li = document.createElement('li');\n li.textContent = `${newCharacter.charname} has been added. `;\n const a = document.createElement('a');\n a.setAttribute('href', `#${newCharacter.key}`);\n a.textContent = 'View character now.';\n a.addEventListener('click', () => {\n this.alert.closeClear();\n });\n li.appendChild(a);\n imported_chars.push(li);\n });\n\n const ul = document.createElement('ul');\n imported_chars.forEach((li) => {\n ul.appendChild(li);\n });\n this.alert.header = 'Restored Characters';\n this.alert.setContent([ul]);\n this.alert.open();\n\n if (reloadCurrentChar) {\n this.loadCharacter(currentCharKey).catch((error) => {\n console.log(error);\n });\n }\n } catch (e) {\n alert(`Error processing backup data: ${e.message}`);\n }\n },\n /**\n * Set a timeout to remove the character in a few seconds.\n * @param {String} key character key\n */\n deleteCharacterTemp: function (key) {\n if (key === '' || key === 'settings') {\n return;\n }\n // if its the current character we should trigger \"new character\" action\n if (getCurrentCharacterKey() === key) {\n this.triggerNewCharacter();\n }\n this.dialog_undo.querySelector('button').dataset.key = key;\n this.dialog_undo.hidden = false;\n // This will trigger a transition bar.\n const timeoutIndicator = this.dialog_undo.querySelector('.delete-timeout');\n // The transition animation doesn't happen if you don't have this timeout,\n // since we are also just now revealing the element.\n setTimeout(() => {\n timeoutIndicator.classList.add('transition', 'timeout');\n }, 10);\n // Note: if we change the timeout of the delete undo, we also need to change the transition timing in the css.\n this[`deleteTimeout${key}`] = setTimeout(this.deleteCharacter.bind(this), 8000, key);\n },\n /**\n * Delete a character from local storage\n * @param {String} key character key\n */\n deleteCharacter: function (key) {\n if (key === '' || key === 'settings') {\n return;\n }\n removeCharacterLocal(key);\n this.dialog_undo.querySelector('button').dataset.key = '';\n this.dialog_undo.hidden = true;\n // This will reset the transition bar.\n const timeoutIndicator = this.dialog_undo.querySelector('.delete-timeout');\n timeoutIndicator.classList.remove('transition', 'timeout');\n },\n /**\n * Remove the timeout and stop the delete from happening.\n * @param {Event} ev Undo button click.\n */\n undoDelete: function (ev) {\n const key = ev.target.dataset.key || null;\n if (!key) {\n return;\n }\n this.dialog_undo.querySelector('button').dataset.key = '';\n this.dialog_undo.hidden = true;\n // Reset transition bar.\n const timeoutIndicator = this.dialog_undo.querySelector('.delete-timeout');\n timeoutIndicator.classList.remove('transition', 'timeout');\n if (this[`deleteTimeout${key}`]) {\n clearTimeout(this[`deleteTimeout${key}`]);\n }\n },\n /**\n * If no characters are saved we show an app intro dialog\n */\n showIntroDialog: function () {\n const template = document.getElementById('introAlert');\n this.alert.setContent([...document.importNode(template.content, true).children]);\n this.alert.open();\n },\n /**\n * Show the unsaved data dialog.\n */\n showUnsavedDialog: function () {\n this.dialog_unsaved.hidden = false;\n },\n /**\n * Hide the unsaved data dialog.\n */\n hideUnsavedDialog: function () {\n this.dialog_unsaved.hidden = true;\n },\n /**\n * Show an error message.\n * @param {String} error\n */\n showErrorMessage: function (error) {\n // Blah, for now just keep it simple and obvious.\n alert(error);\n },\n /**\n * Start up the app with some events and such\n * @param {Object} settings things we need to set external to this script\n * @param {EventEmitter} settings.emitter\n * @param {String} settings.prefix prefix for localStorage keys\n * @param {String} settings.appname used to identify the app property in a character model\n */\n initialize: function ({\n emitter = null,\n prefix = '',\n appname = ''\n }) {\n if (!emitter || !prefix || !appname) {\n document.body.innerHTML = '

    App is missing required settings.

    ';\n return;\n }\n this.emitter = emitter;\n // Set this up first.\n this.emitter.on('error:display', this.showErrorMessage, this);\n\n this.appname = appname;\n // set up storage\n setLocalStoragePrefix(prefix);\n // set up default alert\n this.alert = document.getElementById('alert-main');\n\n monitorAuth(this.emitter);\n\n const shortCuts = new ShortCutKeys(this.emitter);\n shortCuts.addShortCut('Ctrl+Shift+ArrowDown', 'character:save');\n shortCuts.addShortCut('Ctrl+Shift+ArrowRight', 'tab:switch');\n shortCuts.addShortCut('Ctrl+Shift+ArrowLeft', 'tab:switch');\n shortCuts.addShortCut('Ctrl+Shift+ArrowUp', 'loaddialog:toggle');\n\n document.querySelector('.btn-help').addEventListener('click', (ev) => {\n ev.preventDefault();\n const template = document.getElementById('helpDialog');\n const div = document.importNode(template.content, true);\n this.alert.setContent([...div.children]);\n this.alert.open();\n });\n\n // Event: Listen for hashchange and change the current character\n window.addEventListener('hashchange', () => { this.changeCharacter(); }, false);\n\n this.dialog_unsaved.querySelector('.btn-save').addEventListener('click', () => {\n this.emitter.trigger('character:save');\n });\n this.dialog_undo.querySelector('.btn-delete-undo').addEventListener('click', (ev) => {\n this.undoDelete(ev);\n });\n\n // Listen for events, mostly from the menus.\n this.emitter.on('character:new', this.triggerNewCharacter, this);\n this.emitter.on('character:save', this.saveCharacter, this);\n this.emitter.on('character:delete', this.deleteCharacterTemp, this);\n this.emitter.on('backup:download', this.downloadBackup, this);\n this.emitter.on('backup:restore', this.restoreFormSubmit, this);\n this.emitter.on('dialog:save:show', this.showUnsavedDialog, this);\n this.emitter.on('dialog:save:hide', this.hideUnsavedDialog, this);\n\n // Check the hash to see if we need to load a specific character\n const urlhash = window.location.hash.substring(1);\n if (urlhash !== '') {\n this.loadCharacter(urlhash).catch((error) => {\n console.log(error);\n });\n } else {\n // Show intro if they have no characters, since they might be new to this...\n if (getAllCharactersLocal().length === 0) {\n this.showIntroDialog();\n }\n this.triggerNewCharacter();\n }\n }\n};\n\nexport default Manager;\n", "// Confirmation button (i.e. \"Are you sure\" after first click.)\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\nSubmit\nAre you sure?\n`;\n\nclass ConfirmButton extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this._wait = 3000;\n // Default to not triggered\n this._triggered = false;\n // Default to asking for confirmation.\n this._confirm = true;\n // No default callback after confirmation.\n this._confirmCallback = null;\n this.dataset.triggered = 'false';\n // Accessible role\n this.setAttribute('role', 'button');\n }\n connectedCallback () {\n // Add focus-ability if it has not already been set in the html.\n if (this.getAttribute('tabindex') === null) {\n this.setAttribute('tabindex', 0);\n }\n // click handler\n this.addEventListener('click', this._handleClick);\n // space/enter handler to simulate normal button\n this.addEventListener('keydown', this._handleKeyDown);\n this._wait = parseInt(this.dataset.wait || 3000, 10);\n // Allow for setting the confirm click feature to be disabled.\n // Only set this here if the data attribute is explicitly set\n // else it will overwrite the property set on the class directly.\n if (this.dataset.confirm !== undefined) {\n this._confirm = !(this.dataset.confirm === 'false');\n }\n // Unhide slotted content now that the button is loaded.\n // CSS will handle this now based on data-triggered.\n Array.from(this.children).forEach((slotted) => {\n slotted.hidden = false;\n });\n if (this._confirmCallback) {\n this.addEventListener('click', this._confirmCallback);\n }\n }\n disconnectedCallback () {\n this.removeEventListener('click', this._handleClick);\n this.removeEventListener('keydown', this._handleKeyDown);\n if (this._confirmCallback) {\n this.removeEventListener('click', this._confirmCallback);\n }\n }\n /**\n * Update display when triggered value changes.\n * @param {Boolean|String} value\n */\n set triggered (value) {\n const newValue = !!value;\n if (this._triggered === newValue) {\n return;\n }\n this._triggered = newValue;\n // Update data-triggered so the css changes what text is displayed.\n if (this._triggered) {\n this.dataset.triggered = 'true';\n } else {\n this.dataset.triggered = 'false';\n }\n }\n get triggered () {\n return this._triggered;\n }\n get confirm () {\n return this._confirm;\n }\n /**\n * Set if the confirm button/click should be used.\n */\n set confirm (value) {\n this._confirm = !!value;\n }\n\n get confirmCallback () {\n return this._confirmCallback;\n }\n /**\n * Set confirm callback here if you need to set it _before_ putting the button in the DOM.\n * This assures it is triggered after the default event handler.\n */\n set confirmCallback (func) {\n if (typeof func === 'function') {\n this._confirmCallback = func;\n }\n }\n /**\n * Clicking.\n * @param {Event} ev Click event on element.\n */\n _handleClick (ev) {\n if (!this.triggered && this._confirm) {\n // stop any other events from happening\n ev.preventDefault();\n ev.stopImmediatePropagation();\n this.triggered = true;\n // wait a bit then reset.\n setTimeout(() => {\n this.triggered = false;\n }, this._wait);\n }\n // let any other events happen if triggered was true\n // whatever other listeners have been added to the click.\n }\n /**\n * Handle button or space to trigger.\n * @param {KeyboardEvent} ev\n */\n _handleKeyDown (ev) {\n if ((ev.key !== 'Enter' && ev.key !== ' ') || ev.shiftKey) {\n return;\n }\n // Prevent things like space bar trigger scrolling while focused on the button.\n ev.preventDefault();\n this.click();\n }\n /**\n * Use to reset the button from external code.\n */\n reset () {\n this.triggered = false;\n }\n}\n\nif (!window.customElements.get('confirm-button')) {\n window.customElements.define('confirm-button', ConfirmButton);\n}\n\nexport default ConfirmButton;\n", "import { getAllCharactersLocal, getAllCharactersRemote, getCharacter, getCharacterRemote, saveCharacter, saveCharacterRemote, removeCharacterRemote, removeCharacterLocal } from './CharacterService.js';\n\nconst compareLocalToRemote = function (local, remote) {\n // updated stamp on both is in UTC string which can be parse from new Date(utc string)\n const lUpdated = new Date(local);\n const rUpdated = new Date(remote);\n if (lUpdated > rUpdated) {\n return 'local';\n }\n if (rUpdated > lUpdated) {\n return 'remote';\n }\n return 'equal';\n};\n/**\n * Get all characters local and remote\n * With comparisons by key for which is most recent.\n * @returns {Object[]}\n */\nconst getCharacterMatchings = async function () {\n const localCharacters = getAllCharactersLocal();\n const remoteCharacters = await getAllCharactersRemote();\n const matches = [];\n localCharacters.forEach((local) => {\n const match = {\n key: local.key,\n local\n };\n const remote = remoteCharacters.get(local.key);\n if (remote) {\n match.remote = remote;\n remoteCharacters.delete(local.key);\n // Set something to say which is newer.\n match.latest = compareLocalToRemote(local.updated, remote.updated);\n }\n matches.push(match);\n });\n // Any that are on remote but not on local.\n remoteCharacters.forEach((remote) => {\n const match = {\n key: remote.key,\n remote\n };\n matches.push(match);\n });\n return matches;\n};\n/**\n * Upload a character to the remote.\n * @param {String} key\n * @returns {Boolean}\n */\nconst uploadCharacter = async function (key) {\n const char = getCharacter(key);\n if (!char) {\n throw new Error('Character not found');\n }\n const remote = await getCharacterRemote(key);\n if (remote) {\n throw new Error('Character already on the remote');\n }\n return await saveCharacterRemote(char);\n};\n/**\n * Download a character to the local.\n * @param {String} key\n * @returns {Boolean}\n */\nconst downloadCharacter = async function (key) {\n const char = getCharacter(key);\n if (char) {\n return 'Character already on local';\n }\n const remote = await getCharacterRemote(key);\n if (!remote) {\n return 'Character not found on the remote';\n }\n return await saveCharacter(remote);\n};\n/**\n * Delete remote character data.\n * @param {String} key\n * @returns {Boolean}\n */\nconst deleteRemote = async function (key) {\n return removeCharacterRemote(key);\n};\n/**\n * Delete local character data.\n * @param {String} key\n * @returns {Boolean}\n */\nconst deleteLocal = async function (key) {\n return removeCharacterLocal(key);\n};\n/**\n * Update remote character from local data.\n * @param {String} key\n * @returns {Boolean}\n */\nconst syncToRemote = async function (key) {\n const local = getCharacter(key);\n if (!local) {\n throw new Error('Character not found on local');\n }\n return await saveCharacterRemote(local);\n};\n/**\n * Update local character from remote data.\n * @param {String} key\n * @returns {Boolean}\n */\nconst syncToLocal = async function (key) {\n const remote = await getCharacterRemote(key);\n if (!remote) {\n throw new Error('Character not found on the remote');\n }\n const result = await saveCharacter(remote);\n return result;\n};\n\nexport {\n getCharacterMatchings,\n uploadCharacter,\n downloadCharacter,\n deleteRemote,\n deleteLocal,\n syncToRemote,\n syncToLocal\n};\n", "/**\n * Character local/remote sync info/actions.\n */\nimport { downloadCharacter, uploadCharacter, deleteRemote, deleteLocal, syncToLocal, syncToRemote } from '../services/syncService.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n
    ()
    \n
    \n No local copy.\n \n \n
    \n
    \n No remote copy.\n \n \n
    \n
    \n
    \n`;\n\nclass SyncInfo extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.setAttribute('role', 'list-item');\n this.setAttribute('aria-labelledby', 'char-name');\n this._key = '';\n this.localDiv = this.shadowRoot.querySelector('.local');\n this.remoteDiv = this.shadowRoot.querySelector('.remote');\n this.syncDiv = this.shadowRoot.querySelector('.syncaction');\n this.isCurrentCharacter = false;\n }\n\n connectedCallback () {\n this.shadowRoot.addEventListener('click', this.handleButtonClick.bind(this));\n }\n\n disconnectedCallback () {\n this.shadowRoot.removeEventListener('click', this.handleButtonClick.bind(this));\n }\n\n get key () {\n return this._key;\n }\n\n _showError (message) {\n this.shadowRoot.querySelector('.error').innerHTML = message;\n }\n /**\n * Handler clicks in the element.\n * @param {Event} ev Click event\n */\n handleButtonClick (ev) {\n console.log(ev);\n const button = ev.target.closest('button');\n if (!button) {\n return;\n }\n const action = button.dataset.action;\n if (!action) {\n return;\n }\n console.log(`Action: ${action}`);\n\n switch (action) {\n case 'upload':\n uploadCharacter(this._key)\n .then(() => {\n this.remoteDiv.querySelector('.summary').innerHTML = this.localDiv.querySelector('.summary').innerHTML;\n this.remoteDiv.querySelector('.updated').innerHTML = this.localDiv.querySelector('.updated').innerHTML;\n this.remoteDiv.querySelector('.action').innerHTML = '';\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('removeremote', 'Delete from Remote')\n );\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'removeremote':\n deleteRemote(this._key)\n .then(() => {\n this.remoteDiv.querySelector('.summary').innerHTML = 'No remote copy.';\n this.remoteDiv.querySelector('.updated').innerHTML = '';\n this.remoteDiv.querySelector('.action').innerHTML = '';\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('upload', 'Upload')\n );\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'download':\n downloadCharacter(this._key)\n .then(() => {\n this.localDiv.querySelector('.summary').innerHTML = this.remoteDiv.querySelector('.summary').innerHTML;\n this.localDiv.querySelector('.updated').innerHTML = this.remoteDiv.querySelector('.updated').innerHTML;\n this.localDiv.querySelector('.action').innerHTML = '';\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('removelocal', 'Delete from Local')\n );\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'removelocal':\n if (this.isCurrentCharacter) {\n this._showError('You cannot remove the currently displayed character.');\n return;\n }\n deleteLocal(this._key)\n .then(() => {\n this.localDiv.querySelector('.summary').innerHTML = 'No local copy.';\n this.localDiv.querySelector('.updated').innerHTML = '';\n this.localDiv.querySelector('.action').innerHTML = '';\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('download', 'Download')\n );\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'syncup':\n syncToRemote(this._key)\n .then(() => {\n this.remoteDiv.querySelector('.summary').innerHTML = this.localDiv.querySelector('.summary').innerHTML;\n this.remoteDiv.querySelector('.updated').innerHTML = this.localDiv.querySelector('.updated').innerHTML;\n this.remoteDiv.querySelector('.action').innerHTML = '';\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('removeremote', 'Delete from Remote')\n );\n this.syncDiv.innerHTML = '';\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n case 'syncdown':\n if (this.isCurrentCharacter) {\n this._showError('You cannot sync to local the currently displayed character.');\n return;\n }\n syncToLocal(this._key)\n .then(() => {\n this.localDiv.querySelector('.summary').innerHTML = this.remoteDiv.querySelector('.summary').innerHTML;\n this.localDiv.querySelector('.updated').innerHTML = this.remoteDiv.querySelector('.updated').innerHTML;\n this.localDiv.querySelector('.action').innerHTML = '';\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('removelocal', 'Delete from Local')\n );\n this.syncDiv.innerHTML = '';\n })\n .catch((err) => {\n this._showError(err);\n });\n break;\n }\n }\n\n _getButton (action, label) {\n const button = document.createElement('BUTTON');\n button.classList.add('btn-sm');\n button.dataset.action = action;\n button.innerText = label;\n return button;\n }\n /**\n * Set the character data.\n * @param {Object} data\n * @param {String} key Character key.\n * @param {Character} local Local copy\n * @param {Character} remote Remote copy\n * @param {String} latest Which is more recent.\n * @returns\n */\n setData ({\n key = '',\n local = {},\n remote = {},\n latest = ''\n }) {\n if (!key) {\n return;\n }\n this._key = key;\n const charName = local.key\n ? local.charname\n : (remote.key ? remote.charname : '[Unknown]');\n this.shadowRoot.querySelector('.charname').innerHTML = charName;\n this.shadowRoot.querySelector('.key').innerHTML = key;\n if (local.key) {\n this.localDiv.querySelector('.summary').innerHTML = local.summaryHeader;\n this.localDiv.querySelector('.updated').innerHTML = local.updatedTime;\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('removelocal', 'Delete from Local')\n );\n } else {\n this.localDiv.querySelector('.action').appendChild(\n this._getButton('download', 'Download')\n );\n }\n\n if (remote.key) {\n this.remoteDiv.querySelector('.summary').innerHTML = remote.summaryHeader;\n this.remoteDiv.querySelector('.updated').innerHTML = remote.updatedTime;\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('removeremote', 'Delete from Remote')\n );\n } else {\n this.remoteDiv.querySelector('.action').appendChild(\n this._getButton('upload', 'Upload')\n );\n }\n\n if (latest === 'local') {\n this.syncDiv.appendChild(\n this._getButton('syncup', 'Update on Remote')\n );\n } else if (latest === 'remote') {\n this.syncDiv.appendChild(\n this._getButton('syncdown', 'Update on Local')\n );\n }\n }\n}\n\nif (!window.customElements.get('sync-info')) {\n window.customElements.define('sync-info', SyncInfo);\n}\n\nexport default SyncInfo;\n", "/**\n * Action Toolbar\n * Also requires the Modal component.\n */\nimport { getAllCharactersLocal, getCurrentCharacterKey, getGameOptions } from '../services/CharacterService.js';\nimport ConfirmButton from '../components/ConfirmButton.js';\nimport SyncInfo from '../components/SyncInfo.js';\nimport { isAuthed, signIn, signOut } from '../services/AuthService.js';\nimport { getCharacterMatchings } from '../services/syncService.js';\n\n/**\n * Buttons in the toolbar.\n * Mostly in re focus management and keyboard events.\n */\nclass ActionButton {\n /**\n * @param {HTMLElement} el Button element.\n * @param {ActionMenu} menu\n */\n constructor (el, menu) {\n this.el = el;\n this.menu = menu;\n this.action = el.dataset.action || '';\n this.el.addEventListener('keydown', this.handleKeyBoardEvent.bind(this));\n this.el.addEventListener('click', this.menu.setTabFocusToButton.bind(this.menu, this));\n }\n /**\n * Handler: Keyboard actions.\n * @param {KeyboardEvent} ev Keydown event.\n */\n handleKeyBoardEvent (ev) {\n // Stop if any other modifer keys are pressed.\n if (ev.shiftKey || ev.ctrlKey || ev.metaKey || ev.altKey) {\n return;\n }\n if (ev.key === 'ArrowRight') {\n this.removeTabFocus();\n this.menu.setFocusToNext(this);\n return;\n }\n if (ev.key === 'ArrowLeft') {\n this.removeTabFocus();\n this.menu.setFocusToPrevious(this);\n return;\n }\n if (ev.key === 'Home') {\n this.removeTabFocus();\n this.menu.setFocusToFirst();\n return;\n }\n if (ev.key === 'End') {\n this.removeTabFocus();\n this.menu.setFocusToLast();\n }\n }\n\n isFocusable () {\n return this.el.getAttribute('tabindex') > -1;\n }\n\n isVisible () {\n return !!(this.el.offsetWidth || this.el.offsetHeight || this.el.getClientRects().length);\n }\n /**\n * Set button to not be tabbable.\n */\n removeTabFocus () {\n this.el.setAttribute('tabindex', '-1');\n }\n /**\n * Set button to be tabbable.\n */\n setTabFocus () {\n this.el.setAttribute('tabindex', '0');\n }\n /**\n * Focus on this button.\n */\n focus () {\n this.el.focus();\n }\n /**\n * Switch to this button. Set its tabindex and focus.\n * @param {Boolean} forward\n */\n switchTo (forward = true) {\n if (!this.isVisible()) {\n if (forward) {\n this.menu.setFocusToNext(this);\n } else {\n this.menu.setFocusToPrevious(this);\n }\n }\n this.setTabFocus();\n this.focus();\n }\n}\n\n/**\n * Toolbar and associated action events or dialogs.\n */\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n \n \n
    \n \n
    \n \n \n \n \n
    \n
    \n\n`;\n\n/**\n* @prop {Array} Matching action button classes to methods to calls.\n*/\nconst buttonActions = {\n save: '_saveCharacter',\n load: '_openLoadModal',\n new: '_newCharacterModal',\n backup: '_openDownloadForm',\n restore: '_openRestoreForm',\n delete: '_openDeleteModal',\n auth: '_openAuthDialog',\n more: '_showMore'\n};\nclass ActionMenu extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.setAttribute('role', 'toolbar');\n this.setAttribute('aria-label', 'Character Actions');\n this.setAttribute('tabindex', 0);\n /**\n * @prop {ActionButton[]}\n */\n this.buttons = [];\n /**\n * @prop {HTMLELement} Menu toogle button when menu is collapsed on narrow screens.\n */\n this.opener = null;\n /**\n * @prop {Modal} Modal for new menu.\n */\n this.newDialog = null;\n /**\n * @prop {Modal} Modal for load menu.\n */\n this.loadDialog = null;\n /**\n * @prop {Modal} Modal for Backup save.\n */\n this.downloadDialog = null;\n /**\n * @prop {Modal} Modal for Backup restore.\n */\n this.restoreDialog = null;\n /**\n * @prop {Modal} authDialog\n */\n this.authDialog = null;\n /**\n * @prop {Modal} syncDialog\n */\n this.syncDialog = null;\n }\n\n connectedCallback () {\n this.addEventListener('focus', this.focus.bind(this));\n\n const buttons = this.shadowRoot.querySelectorAll('button');\n Array.prototype.forEach.call(buttons, (btn) => {\n this.buttons.push(new ActionButton(btn, this));\n });\n // event handlers for all the menu buttons\n this.shadowRoot.addEventListener('click', this._handleClicks.bind(this));\n }\n\n disconnectedCallback () {\n this.shadowRoot.removeEventListener('click', this._handleClicks.bind(this));\n if (this.emitter) {\n this.emitter.off('newdialog:close', this._closeNewModal, this);\n this.emitter.off('loaddialog:close', this._closeLoadModal, this);\n this.emitter.off('loaddialog:toggle', this._openLoadModal, this);\n this.emitter.off('backup:email', this._emailDownload, this);\n this.emitter.off('backup:textpaste', this._altDownload, this);\n this.emitter.off('auth:enabled', this._showAuth, this);\n this.emitter.off('auth:signin', this._signedIn, this);\n this.emitter.off('auth:signout', this._signedOut, this);\n }\n }\n\n setEmitter (emitter) {\n this.emitter = emitter;\n this.emitter.on('newdialog:close', this._closeNewModal, this);\n this.emitter.on('loaddialog:close', this._closeLoadModal, this);\n this.emitter.on('loaddialog:toggle', this._openLoadModal, this);\n this.emitter.on('backup:email', this._emailDownload, this);\n this.emitter.on('backup:textpaste', this._altDownload, this);\n this.emitter.on('auth:enabled', this._showAuth, this);\n this.emitter.on('auth:signin', this._signedIn, this);\n this.emitter.on('auth:signout', this._signedOut, this);\n }\n\n _handleClicks (ev) {\n const target = ev.target.closest('button');\n const button = this.buttons.find((btn) => { return btn.el === target; });\n if (!button) {\n return;\n }\n const action = buttonActions[button.action] || null;\n if (!action) {\n return;\n }\n this[action](button);\n }\n\n _openAuthDialog () {\n this.authDialog = this.authDialog || document.getElementById('dialog-auth');\n this.authDialog.clear();\n if (this.authDialog.isOpen) {\n this.authDialog.close();\n return;\n }\n let template = null;\n\n if (isAuthed()) {\n template = document.getElementById('authSignOutModal');\n } else {\n template = document.getElementById('authSignInModal');\n }\n this.authDialog.setContent([...document.importNode(template.content, true).children]);\n if (isAuthed()) {\n this.authDialog.querySelector('#signOut').addEventListener('click', () => {\n signOut();\n });\n this.authDialog.querySelector('#syncData').addEventListener('click', () => {\n this._openSyncModal();\n this.authDialog.close();\n });\n } else {\n this.authDialog.querySelector('#googleSignIn').addEventListener('click', () => {\n signIn();\n });\n }\n this.authDialog.open();\n }\n /**\n * Open the character sync modal.\n */\n _openSyncModal () {\n this.syncDialog = this.syncDialog || document.getElementById('dialog-sync');\n this.syncDialog.clear();\n if (this.syncDialog.isOpen) {\n this.syncDialog.close();\n return;\n }\n const template = document.getElementById('syncModal');\n this.syncDialog.setContent([...document.importNode(template.content, true).children]);\n\n const currentCharKey = getCurrentCharacterKey();\n\n getCharacterMatchings().then((matches) => {\n const frag = document.createDocumentFragment();\n matches.forEach((match) => {\n const info = new SyncInfo();\n info.setData(match);\n // Not all actions are allowed for the current character.\n if (info.key === currentCharKey) {\n info.isCurrentCharacter = true;\n }\n frag.appendChild(info);\n });\n this.syncDialog.querySelector('#characterSyncList').appendChild(frag);\n this.syncDialog.open();\n })\n .catch((error) => {\n console.log(error);\n });\n }\n /**\n * Show the dialog for backing up characters.\n * Else close it if its open.\n */\n _openDownloadForm () {\n this.downloadDialog = this.downloadDialog || document.getElementById('dialog-backup');\n this.downloadDialog.clear();\n if (this.downloadDialog.isOpen) {\n this.downloadDialog.close();\n return;\n }\n const template = document.getElementById('backupModal');\n const form = document.importNode(template.content, true);\n\n const checkboxes = [];\n getAllCharactersLocal().forEach((char) => {\n const li = `
  • `;\n checkboxes.push(li);\n });\n form.querySelector('.character_downloads').innerHTML = checkboxes.join('');\n this.downloadDialog.setContent([...form.children], false);\n this.downloadDialog.querySelector('form').addEventListener('submit', (ev) => {\n ev.preventDefault();\n this.emitter.trigger('backup:download', ev.target);\n });\n this.downloadDialog.open();\n }\n /**\n * Show the back up restore form.\n * Else close it if its open.\n */\n _openRestoreForm () {\n this.restoreDialog = this.restoreDialog || document.getElementById('dialog-restore');\n this.restoreDialog.clear();\n if (this.restoreDialog.isOpen) {\n this.restoreDialog.close();\n return;\n }\n const template = document.getElementById('restoreModal');\n const form = document.importNode(template.content, true);\n this.restoreDialog.setContent([...form.children], false);\n this.restoreDialog.querySelector('form').addEventListener('submit', (ev) => {\n ev.preventDefault();\n this.emitter.trigger('backup:restore', ev.target);\n this.restoreDialog.closeClear();\n });\n this.restoreDialog.open();\n }\n /**\n * If file download is unavailable show the data to copy/paste\n * @param {String} data the backup data\n */\n _altDownload (data) {\n const p = document.createElement('p');\n p.innerHTML = `Your current browser/os does not support direct file downloads, so here is the data for you to copy/paste.`;\n const text = document.createElement('textarea');\n text.classList.add('large');\n text.value = data;\n this.downloadDialog.clear();\n this.downloadDialog.header = 'Alernate Download Option';\n this.downloadDialog.setContent([p, text, this.downloadDialog.getCloseButton()], false);\n this.downloadDialog.open();\n }\n /**\n * Show email download link.\n * @param {String} url The email url\n */\n _emailDownload (url) {\n const a = document.createElement('a');\n a.href = url;\n a.setAttribute('target', '_blank');\n a.innerHTML = 'Open new message in default email client';\n a.addEventListener('click', () => {\n this.downloadDialog.closeClear();\n });\n const p = document.createElement('p');\n p.appendChild(a);\n this.downloadDialog.clear();\n this.downloadDialog.setContent([p, this.downloadDialog.getCloseButton()], false);\n this.downloadDialog.open();\n }\n /**\n * Trigger a save character event.\n */\n _saveCharacter () {\n this.emitter.trigger('character:save');\n }\n /**\n * Open the new character modal.\n */\n _newCharacterModal () {\n this.newDialog = this.newDialog || document.getElementById('dialog-new');\n this.newDialog.clear();\n if (this.newDialog.isOpen) {\n this.newDialog.close();\n return;\n }\n\n // Are there unsaved changes\n // This could be done better in the future if we had some kind of central state management.\n let currentlyUnsaved = false;\n // is the unsaved dialog showing...\n const unsavedDialog = document.querySelector('.alert-unsaved');\n if (unsavedDialog && !unsavedDialog.hidden) {\n currentlyUnsaved = true;\n }\n\n const template = document.getElementById('createModal');\n const content = document.importNode(template.content, true);\n\n if (currentlyUnsaved) {\n const alert = document.createElement('p');\n alert.classList.add('alert');\n alert.innerHTML = 'Warning: You have unsaved changes.';\n content.querySelector('form').prepend(alert);\n }\n\n const select = content.querySelector('select');\n getGameOptions().forEach((char_type) => {\n const option = document.createElement('option');\n option.value = char_type;\n option.innerText = char_type;\n select.appendChild(option);\n });\n this.newDialog.setContent([...content.children]);\n this.newDialog.querySelector('form').addEventListener('submit', (ev) => {\n ev.preventDefault();\n const formData = new FormData(ev.target);\n this.emitter.trigger('character:new', formData.get('char_type'));\n });\n this.newDialog.open();\n }\n /**\n * Close the mew modal.\n */\n _closeNewModal () {\n if (this.newDialog !== null) {\n this.newDialog.closeClear();\n }\n }\n /**\n * Load up a character by triggering a hash change.\n * @param {Event} ev Click event\n * @returns\n */\n _loadCharClick (ev) {\n const button = ev.currentTarget;\n const charKey = button.dataset.key || '';\n if (charKey === '') {\n return;\n }\n window.location.hash = `#${charKey}`;\n }\n /**\n * Open the dialog to load a character.\n */\n _openLoadModal () {\n this.loadDialog = this.loadDialog || document.getElementById('dialog-load');\n this.loadDialog.clear();\n if (this.loadDialog.isOpen) {\n this.loadDialog.close();\n return;\n }\n\n // Are there unsaved changes\n // This could be done better in the future if we had some kind of central state management.\n let currentlyUnsaved = false;\n // is the unsaved dialog showing...\n const unsavedDialog = document.querySelector('.alert-unsaved');\n if (unsavedDialog && !unsavedDialog.hidden) {\n currentlyUnsaved = true;\n }\n\n const template = document.getElementById('loadModal');\n const content = document.importNode(template.content, true);\n const list = content.querySelector('ul');\n getAllCharactersLocal().forEach((char) => {\n const li = document.createElement('li');\n const cButton = new ConfirmButton();\n cButton.dataset.key = char.key;\n cButton.classList.add('btn', 'btn-plain');\n cButton.innerHTML = `${char.summaryHeader}\n `;\n if (!currentlyUnsaved) {\n cButton.confirm = false;\n }\n // set this so it's added _after_ the internal confirm event.\n cButton.confirmCallback = this._loadCharClick.bind(this);\n li.appendChild(cButton);\n list.appendChild(li);\n });\n this.loadDialog.setContent([...content.children]);\n this.loadDialog.open();\n }\n /**\n * Close the load modal.\n */\n _closeLoadModal () {\n if (this.loadDialog !== null) {\n this.loadDialog.closeClear();\n }\n }\n /**\n * Modal for deleting characters.\n */\n _openDeleteModal () {\n const modal = document.getElementById('dialog-delete');\n if (modal.isOpen) {\n modal.close();\n return;\n }\n const template = document.getElementById('deleteModal');\n const content = document.importNode(template.content, true);\n\n const items = [];\n getAllCharactersLocal().forEach((char) => {\n const li = `
  • \n ${char.summaryHeader}\n \n
  • `;\n items.push(li);\n });\n content.querySelector('ul').innerHTML = items.join('');\n\n modal.setContent([...content.children]);\n modal.querySelector('ul').addEventListener('click', (ev) => {\n const button = ev.target.tagName === 'CONFIRM-BUTTON' ? ev.target : ev.target.closest('confirm-button');\n if (button && button.classList.contains('btn-delete-char')) {\n ev.preventDefault();\n this.emitter.trigger('character:delete', button.getAttribute('data-key'));\n modal.closeClear();\n }\n });\n modal.open();\n }\n\n _showMore () {\n this.shadowRoot.querySelector('.more-actions').classList.toggle('closed');\n }\n /**\n * Show auth button if auth is setup.\n */\n _showAuth () {\n const authbutton = this.buttons.find((btn) => { return btn.el.classList.contains('btn-auth'); });\n if (authbutton) {\n authbutton.el.classList.remove('hidden');\n }\n }\n /**\n * When user switches to being logged in.\n */\n _signedIn () {\n const button = this.buttons.find((b) => {\n return b.action === 'auth';\n });\n if (button) {\n button.el.innerHTML = 'Sync/Logout';\n }\n // Trigger the dialog so user can sync data.\n this._openAuthDialog();\n }\n /**\n * When user switches to being logged ou.\n */\n _signedOut () {\n const button = this.buttons.find((b) => {\n return b.action === 'auth';\n });\n if (button) {\n button.el.innerHTML = 'Login';\n }\n if (this.authDialog && this.authDialog.isOpen) {\n this.authDialog.close();\n }\n }\n /**\n * Set focus to next button (or wrap around).\n * @param {ActionButton} currentBtn\n */\n setFocusToNext (currentBtn) {\n const index = this.buttons.indexOf(currentBtn);\n const newIndex = index + 1;\n if (newIndex > this.buttons.length - 1) {\n this.setFocusToFirst();\n return;\n }\n this.buttons[newIndex].switchTo();\n }\n /**\n * Set focus to previous button (or wrap around).\n * @param {ActionButton} currentBtn\n */\n setFocusToPrevious (currentBtn) {\n const index = this.buttons.indexOf(currentBtn);\n const newIndex = index - 1;\n if (newIndex < 0) {\n this.setFocusToLast();\n return;\n }\n this.buttons[newIndex].switchTo(false);\n }\n /**\n * Set focus to first button.\n */\n setFocusToFirst () {\n this.buttons[0].switchTo();\n }\n /**\n * Set focus to last button.\n */\n setFocusToLast () {\n this.buttons[this.buttons.length - 1].switchTo(false);\n }\n /**\n * Set focus to specific button.\n * @param {ActionButton} button\n */\n setTabFocusToButton (button) {\n this.buttons.forEach((btn) => {\n if (btn === button) {\n btn.switchTo();\n } else {\n btn.removeTabFocus();\n }\n });\n }\n /**\n * Set focus to whatever button was last focused or else the first one.\n */\n focus () {\n let button = this.buttons.find((btn) => {\n return btn.isFocusable();\n });\n if (!button) {\n button = this.buttons[0];\n }\n this.setTabFocusToButton(button);\n }\n}\n\nif (!window.customElements.get('action-menu')) {\n window.customElements.define('action-menu', ActionMenu);\n}\n\nexport default ActionMenu;\n", "/**\n * Container for Definition list pairs used as note header/text.\n */\nimport CharacterNote from '../models/CharacterNote.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n
    \n
    \n`;\n\nclass NoteListItem extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list-item');\n }\n }\n\n /**\n * Get the content (header and text) of the pair.\n * @returns {CharacterNote}\n */\n get content () {\n return new CharacterNote({\n header: this.shadowRoot.querySelector('dt').innerHTML,\n text: this.shadowRoot.querySelector('dd').innerHTML\n });\n }\n /**\n * Set the header and text of the pair.\n * @param {CharacterNote}\n */\n set content (note) {\n // set the content.\n this.shadowRoot.querySelector('dt').innerHTML = note.header;\n this.shadowRoot.querySelector('dd').innerHTML = note.text;\n }\n /**\n * Clear the text.\n */\n clear () {\n this.content = [];\n }\n /**\n * Get the in focus element.\n * @returns {Element}\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n * @param {Boolean} onContent If true focus on the dd instead.\n */\n focus (onContent = false) {\n if (onContent) {\n this.shadowRoot.querySelector('dd').focus();\n return;\n }\n this.shadowRoot.querySelector('dt').focus();\n }\n /**\n * Determine whether NoteListItem is empty, ignoring lead and trailing whitespace\n * @returns true if empty, false otherwise\n */\n isEmpty () {\n if (this.shadowRoot.querySelector('dt').innerText.trim() === '' &&\n this.shadowRoot.querySelector('dd').innerText.trim() === '') {\n return true;\n }\n return false;\n }\n}\n\nwindow.customElements.define('note-list-item', NoteListItem);\n\nexport default NoteListItem;\n", "/**\n * Set the cursor to the end of the content.\n * Call after setting focus on el\n * @param {HTMLElement} el Element that is contenteditable=true\n */\nconst setCursorAtContentEnd = function (el) {\n const theNodes = el.childNodes;\n if (theNodes.length === 0) {\n return;\n }\n const contentRange = document.createRange();\n const windowSelection = window.getSelection();\n // Remove any previously created ranges\n windowSelection.removeAllRanges();\n contentRange.setStartBefore(theNodes[0]);\n contentRange.setEndAfter(theNodes[theNodes.length - 1]);\n contentRange.collapse(false);\n // add the range to a window selection object.\n windowSelection.addRange(contentRange);\n windowSelection.collapseToEnd();\n};\n\nexport default setCursorAtContentEnd;\n", "import NoteListItem from './NoteListItem.js';\nimport CharacterNote from '../models/CharacterNote.js';\nimport setCursorAtContentEnd from '../utils/setCursorAtContentEnd.js';\n\n/**\n * Parent container for Definition list pairs used as note header/text.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n`;\n\nclass NoteList extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes?\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list');\n }\n // add event listeners\n this.addEventListener('keydown', this._keyDown);\n this.addEventListener('blur', this._blur);\n this._upgradeProperty('fieldName');\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.removeEventListener('keydown', this._keyDown);\n this.removeEventListener('blur', this._blur);\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Setter: field name for data.\n */\n set fieldName (value) {\n this.dataset.name = value;\n }\n /**\n * Getter: field name for data.\n */\n get fieldName () {\n return this.dataset.name || '';\n }\n /**\n * Getter: Content of list items.\n * @returns {CharacterNote[]}\n */\n get contentArray () {\n const items = Array.from(this.shadowRoot.querySelectorAll('note-list-item'));\n const array = [];\n items.forEach((item) => {\n const content = item.content;\n // Check if it's empty.\n if (!content.header && !content.text) {\n return;\n }\n array.push(content);\n });\n return array;\n }\n /**\n * Add a new note-list-item.\n * Set its header/text if appropriate.\n * @param {CharacterNote|null} note\n */\n addItem (note = null) {\n const item = new NoteListItem();\n if (note) {\n item.content = note;\n }\n this.shadowRoot.appendChild(item);\n }\n /**\n * Clear out the items.\n */\n clear () {\n Array.from(this.shadowRoot.querySelectorAll('note-list-item')).forEach((item) => {\n this.shadowRoot.removeChild(item);\n });\n }\n /**\n * Get focused element.\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Handler: Enter to move through the items or add new ones.\n * @param {KeyboardEvent} ev Keypress event\n */\n _keyDown (ev) {\n if ((ev.key !== 'Enter' && ev.key !== 'Backspace') || ev.shiftKey) {\n return;\n }\n const el = this.deepActiveElement();\n // Move to next field on enter.\n if (ev.key === 'Enter') {\n ev.preventDefault();\n ev.stopPropagation();\n if (el.tagName === 'DT' || el.closest('dt')) {\n console.log(el);\n // If this is a child of dt we need to handle this differently.\n el.nextElementSibling.focus();\n } else if (el.tagName === 'DD' || el.closest('dd')) {\n console.log(el);\n if (el.parentNode.host === this.shadowRoot.lastElementChild) {\n // Last NoteListItem, so add a new item and focus.\n const newList = new NoteListItem();\n this.shadowRoot.appendChild(newList);\n newList.focus();\n } else {\n const nextList = el.parentNode.host.nextElementSibling;\n if (nextList) {\n nextList.focus();\n }\n }\n }\n return;\n }\n\n if (ev.key === 'Backspace') {\n // trim this in case of line breaks, spaces, etc.\n if (el.innerText.trim() !== '') {\n return;\n }\n ev.preventDefault();\n ev.stopPropagation();\n if (el.tagName === 'DT' || el.closest('dt')) {\n // If it's not the first NoteListItem, move to the previous one's text field.\n if (el.parentNode.host !== this.shadowRoot.querySelector('note-list-item')) {\n const prevItem = el.parentNode.host.previousElementSibling;\n\n if (prevItem) {\n prevItem.focus(true);\n setCursorAtContentEnd(this.deepActiveElement());\n\n // If both NoteListItem fields are empty, delete it\n if (el.parentNode.host.isEmpty()) {\n el.parentNode.host.remove();\n }\n }\n }\n } else if (el.tagName === 'DD' || el.closest('dd')) {\n // NoteListItem focus always goes to the DT.\n el.parentNode.host.focus();\n setCursorAtContentEnd(this.deepActiveElement());\n }\n }\n }\n /**\n * On blur dispatch an event so the character model can be updated.\n * @param {Event} ev\n */\n _blur (ev) {\n const detail = {\n field: this.fieldName,\n value: this.contentArray\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('note-list-item').focus();\n }\n}\n\nwindow.customElements.define('note-list', NoteList);\n\nexport default NoteList;\n", "import setCursorAtContentEnd from '../utils/setCursorAtContentEnd.js';\n\n/**\n * Parent container for a simple list.\n * Add data-number=\"true\" to make it a numbered list.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n`;\n\nclass SimpleList extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes?\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list');\n }\n // add event listeners\n this.addEventListener('keydown', this._keyDown);\n this.addEventListener('blur', this._blur);\n this._upgradeProperty('fieldName');\n this._upgradeProperty('subFieldName');\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.removeEventListener('keydown', this._keyDown);\n this.removeEventListener('blur', this._blur);\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Setter: field name for data.\n */\n set fieldName (value) {\n this.dataset.name = value;\n }\n /**\n * Getter: field name for data.\n */\n get fieldName () {\n return this.dataset.name || '';\n }\n /**\n * Setter: subfield name for data.\n */\n set subFieldName (value) {\n this.dataset.subfield = value;\n }\n /**\n * Getter: subfield name for data.\n */\n get subFieldName () {\n return this.dataset.subfield || '';\n }\n /**\n * Getter: Content of list items.\n */\n get contentArray () {\n const items = Array.from(this.shadowRoot.querySelectorAll('li'));\n const array = [];\n items.forEach((item) => {\n const content = item.innerHTML;\n if (content === '') {\n return;\n }\n array.push(content);\n });\n return array;\n }\n /**\n * Add a new li.\n * Set its text if appropriate.\n * @param {String} content\n * @returns {HTMLLIElement}\n */\n addItem (content = '') {\n const item = document.createElement('li');\n item.setAttribute('contenteditable', true);\n item.innerHTML = content;\n this.shadowRoot.appendChild(item);\n return item;\n }\n /**\n * Clear out the items.\n */\n clear () {\n Array.from(this.shadowRoot.querySelectorAll('li')).forEach((item) => {\n this.shadowRoot.removeChild(item);\n });\n }\n /**\n * Get focused element.\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Handler: Enter to move through the items or add new ones.\n * @param {KeyboardEvent} ev Keypress event\n */\n _keyDown (ev) {\n if ((ev.key !== 'Enter' && ev.key !== 'Backspace') || ev.shiftKey) {\n return;\n }\n const el = this.deepActiveElement();\n if (el.tagName !== 'LI' && !el.closest('li')) {\n return;\n }\n if (ev.key === 'Enter') {\n ev.preventDefault();\n // compare the focused elements parent component node (note-list-item) to the last item in the list.\n if (el === this.shadowRoot.lastElementChild) {\n // Last one so add a new item and focus.\n const newItem = this.addItem();\n newItem.focus();\n } else {\n // Move to the next item.\n const nextItem = el.nextElementSibling;\n if (nextItem) {\n nextItem.focus();\n }\n }\n return;\n }\n if (ev.key === 'Backspace') {\n if (el !== this.shadowRoot.querySelector('li')) {\n if (el.innerText.trim() === '') {\n ev.preventDefault();\n const prevItem = el.previousElementSibling;\n prevItem.focus();\n setCursorAtContentEnd(prevItem);\n el.remove();\n }\n }\n }\n }\n /**\n * On blur dispatch an event so the character model can be updated.\n * @param {Event} ev\n */\n _blur () {\n const detail = {\n field: this.fieldName,\n subfield: this.subFieldName,\n value: this.contentArray\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('li').focus();\n }\n}\n\nif (!window.customElements.get('simple-list')) {\n window.customElements.define('simple-list', SimpleList);\n}\n\nexport default SimpleList;\n", "import setCursorAtContentEnd from '../utils/setCursorAtContentEnd.js';\n\n/**\n * Editable table.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n \n\n\n\n\n`;\n\nclass TableEditable extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.columns = 0;\n }\n\n connectedCallback () {\n // set any default attributes?\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'table');\n }\n // add event listeners\n this.addEventListener('keydown', this._keyDown);\n this.addEventListener('blur', this._blur);\n this._upgradeProperty('fieldName');\n // for now the column names are also the keys of the data.\n this.columnNames = this.getAttribute('columns').split('||');\n this.columns = this.columnNames.length;\n\n const headRow = this.shadowRoot.querySelector('thead tr');\n this.columnNames.forEach((name) => {\n const th = document.createElement('th');\n th.innerHTML = name;\n headRow.appendChild(th);\n });\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.removeEventListener('keydown', this._keyDown);\n this.removeEventListener('blur', this._blur);\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Setter: field name for data.\n */\n set fieldName (value) {\n this.dataset.name = value;\n }\n /**\n * Getter: field name for data.\n */\n get fieldName () {\n return this.dataset.name || '';\n }\n /**\n * Getter: Content of list items.\n */\n get contentArray () {\n const entries = [];\n const rows = Array.from(this.shadowRoot.querySelectorAll('tbody > tr'));\n\n rows.forEach((row) => {\n const cells = Array.from(row.querySelectorAll('td'));\n if (cells.length === 0) {\n return;\n }\n const rowData = {};\n let isEmpty = true;\n cells.forEach((cell, i) => {\n const key = this.columnNames[i].toLowerCase();\n const text = cell.innerHTML.trim();\n if (text !== '') {\n isEmpty = false;\n }\n rowData[key] = text;\n });\n if (isEmpty) {\n return;\n }\n entries.push(rowData);\n });\n return entries;\n }\n /**\n * Add a new row to the table.\n * Set its header/text if appropriate.\n * @param {String[]} array\n * @returns {HTMLTableRowElement}\n */\n addRow (content = []) {\n const row = document.createElement('tr');\n const cell = document.createElement('td');\n cell.setAttribute('contenteditable', true);\n\n for (let i = 0; i < this.columns; i++) {\n const key = this.columnNames[i].toLowerCase();\n const newCell = cell.cloneNode(false);\n newCell.innerHTML = content[key] || '';\n row.appendChild(newCell);\n }\n this.shadowRoot.querySelector('tbody').appendChild(row);\n return row;\n }\n /**\n * Clear out the body rows.\n */\n clear () {\n Array.from(this.shadowRoot.querySelectorAll('tbody > tr')).forEach((row) => {\n row.parentNode.removeChild(row);\n });\n }\n /**\n * Get focused element.\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Handler: Enter to move through the items or add new ones.\n * @param {KeyboardEvent} ev Keydown event\n */\n _keyDown (ev) {\n if ((ev.key !== 'Enter' && ev.key !== 'Backspace') || ev.shiftKey) {\n return;\n }\n const el = this.deepActiveElement();\n if (el.tagName !== 'TD' && !el.closest(`td`)) {\n return;\n }\n const td = el.tagName === 'TD' ? el : el.closest(`td`);\n const row = td.parentElement;\n if (ev.key === 'Enter') {\n ev.preventDefault();\n\n if (td !== row.lastElementChild) {\n const nextCell = td.nextElementSibling;\n if (nextCell) {\n nextCell.focus();\n }\n return;\n }\n const nextRow = row.nextElementSibling;\n if (nextRow) {\n nextRow.querySelector('td').focus();\n return;\n }\n const newRow = this.addRow();\n newRow.querySelector('td').focus();\n return;\n }\n if (ev.key === 'Backspace') {\n if (td.innerText.trim() !== '') {\n return;\n }\n ev.preventDefault();\n // if it's not the first cell, move to the previous cell.\n if (td !== row.firstElementChild) {\n const prevCell = td.previousElementSibling;\n if (prevCell) {\n prevCell.focus();\n setCursorAtContentEnd(prevCell);\n }\n return;\n }\n // it is the first cell.\n // if there is a prev row, move to its last cell, delete current row if it's empty.\n const prevRow = row.previousElementSibling;\n if (prevRow) {\n prevRow.lastElementChild.focus();\n setCursorAtContentEnd(prevRow.lastElementChild);\n let delRow = true;\n row.querySelectorAll('td').forEach((c) => {\n if (c.innerText.trim() !== '') {\n delRow = false;\n }\n });\n if (delRow) {\n row.remove();\n }\n }\n }\n }\n /**\n * On blur dispatch an event so the character model can be updated.\n * @param {Event} ev\n */\n _blur (ev) {\n const detail = {\n field: this.fieldName,\n value: this.contentArray\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('[contenteditable=true]').focus();\n }\n}\n\nwindow.customElements.define('table-editable', TableEditable);\n\nexport default TableEditable;\n", "/**\n * Container for skill check boxes and data.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n0\n\n`;\n\nclass SkillListing extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list-item');\n }\n\n this.profCheck = this.shadowRoot.querySelector('input[data-name=\"skills\"]');\n this.expertCheck = this.shadowRoot.querySelector('input[data-name=\"expert\"]');\n // add event listeners\n this.profCheck.addEventListener('change', this._checkSkills.bind(this));\n this.expertCheck.addEventListener('change', this._checkExpert.bind(this));\n this.shadowRoot.querySelector('button').addEventListener('click', this._skillCheck.bind(this));\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.profCheck.removeEventListener('change', this._checkSkills.bind(this));\n this.expertCheck.removeEventListener('change', this._checkExpert.bind(this));\n this.shadowRoot.querySelector('button').removeEventListener('click', this._skillCheck.bind(this));\n }\n /**\n * Name of the skill based on the data-subfield attribute.\n * @returns {String}\n */\n get skillName () {\n return this.dataset.subfield || '';\n }\n /**\n * Set skill name.\n * @param {String} val\n */\n set skillName (val) {\n this.dataset.subfield = val;\n }\n get skillLabel () {\n return this.shadowRoot.querySelector('.pc-skill-name').innerHTML;\n }\n /**\n * Set human readable label\n * @param {String} val\n */\n set skillLabel (val) {\n this.shadowRoot.querySelector('.pc-skill-name').innerHTML = val;\n }\n\n get skillValue () {\n if (!this.profCheck.checked) {\n return 0;\n }\n return this.expertCheck.checked ? 2 : 1;\n }\n /**\n * Set skill proficiency/expert status.\n * @param {Number} val\n */\n set skillValue (val) {\n this.profCheck.checked = false;\n this.expertCheck.checked = false;\n if (val > 0) {\n this.profCheck.checked = true;\n this.expertCheck.disabled = false;\n }\n if (val > 1) {\n this.expertCheck.checked = true;\n }\n }\n get skillMod () {\n return this.shadowRoot.querySelector('.pc-skill-mod').innerHTML;\n }\n /**\n * Set the skill modifiter.\n * @param {String} mod\n */\n set skillMod (mod) {\n this.shadowRoot.querySelector('.pc-skill-mod').innerHTML = mod;\n }\n /**\n * Handler when proficiency is (un)checked.\n * @param {Event} ev\n */\n _checkSkills (ev) {\n // change event for checkboxes\n // check data-name of check.\n const expert = this.expertCheck;\n if (!ev.target.checked) {\n expert.checked = false;\n expert.disabled = true;\n } else {\n expert.disabled = false;\n }\n\n const detail = {\n field: 'skills',\n subfield: this.skillName,\n value: ev.target.checked ? 1 : 0\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Handler when expert is (un)checked.\n * @param {Event} ev\n */\n _checkExpert (ev) {\n // change event for checkboxes\n // check data-name of check.\n const detail = {\n field: 'skills',\n subfield: this.skillName,\n value: ev.target.checked ? 2 : 1\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Roll a skill check.\n * @param {ClickEvent} ev\n */\n _skillCheck (ev) {\n const roller = document.querySelector('sheet-view-5e').shadowRoot.querySelector('dice-roller');\n if (!roller) {\n return;\n }\n const mod = this.skillMod;\n const die = `1d20${mod !== '0' ? mod : ''}`;\n roller.roll(die);\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('input').focus();\n }\n}\n\nwindow.customElements.define('skill-listing', SkillListing);\n\nexport default SkillListing;\n", "/**\n * Attribute score/bonus/saves.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n0\n\n0\n\n`;\n\nclass AttributeListing extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n // set any default attributes\n if (!this.hasAttribute('role')) {\n this.setAttribute('role', 'list-item');\n }\n\n this.scoreInput = this.shadowRoot.querySelector('input.pc-attribute');\n this.saveCheck = this.shadowRoot.querySelector('input[name=\"pc-save\"]');\n\n // add event listeners\n this.saveCheck.addEventListener('change', this._checkSave.bind(this));\n this.scoreInput.addEventListener('change', this._scoreUpdate.bind(this));\n this.shadowRoot.querySelector('button').addEventListener('click', this._savingThrow.bind(this));\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.saveCheck.removeEventListener('change', this._checkSave.bind(this));\n this.scoreInput.removeEventListener('change', this._scoreUpdate.bind(this));\n this.shadowRoot.querySelector('button').removeEventListener('click', this._savingThrow.bind(this));\n }\n /**\n * Name of the skill based on the data-name attribute.\n * @returns {String}\n */\n get attributeName () {\n return this.dataset.name || '';\n }\n /**\n * Set attribute name.\n * @param {String} val\n */\n set attributeName (val) {\n this.dataset.name = val;\n }\n /**\n * Get current attribute score.\n * @returns {Number}\n */\n get attributeScore () {\n return parseInt(this.scoreInput.value, 10);\n }\n /**\n * Set the attribute score.\n * @param {Number} val\n */\n set attributeScore (val) {\n this.scoreInput.value = val;\n }\n /**\n * Get if the save is proficient.\n * @returns {Number}\n */\n get saveProficiency () {\n return this.saveCheck.checked ? 1 : 0;\n }\n /**\n * Check (or not) the save proficiency.\n * @param {Number} val\n */\n set saveProficiency (val) {\n this.saveCheck.checked = (val);\n }\n /**\n * Set the attribute modifier.\n * @param {String} val\n */\n set attributeMod (val) {\n this.shadowRoot.querySelector('.pc-attribute-mod').innerHTML = val;\n }\n\n get saveMod () {\n return this.shadowRoot.querySelector('.pc-save-mod').innerHTML;\n }\n /**\n * Set the save modifier.\n * @param {String} mod\n */\n set saveMod (mod) {\n this.shadowRoot.querySelector('.pc-save-mod').innerHTML = mod;\n }\n /**\n * Handler: Change event on saves.\n * @param {Event} ev\n */\n _checkSave (ev) {\n const detail = {\n field: this.attributeName,\n value: ev.target.checked ? 1 : 0\n };\n this.dispatchEvent(new CustomEvent('saveChange', { bubbles: true, detail }));\n }\n /**\n * Handler: Change event on number input.\n * @param {Event} ev\n */\n _scoreUpdate (ev) {\n const detail = {\n field: this.attributeName,\n value: ev.target.value\n };\n this.dispatchEvent(new CustomEvent('attributeChange', { bubbles: true, detail }));\n }\n /**\n * Roll a saving throw.\n * @param {ClickEvent} ev\n */\n _savingThrow (ev) {\n const roller = document.querySelector('sheet-view-5e').shadowRoot.querySelector('dice-roller');\n if (!roller) {\n return;\n }\n const mod = this.saveMod;\n const die = `1d20${mod !== '0' ? mod : ''}`;\n roller.roll(die);\n }\n /**\n * Focus method since HTMLElement doesn't have that by default (I think).\n */\n focus () {\n this.shadowRoot.querySelector('input').focus();\n }\n}\n\nwindow.customElements.define('attr-listing', AttributeListing);\n\nexport default AttributeListing;\n", "/**\n * Sum an array\n * @param {Array} arr an array of numbers\n * @returns {Number} Total value of numbers in array\n */\nconst arraySum = function (arr) {\n let total = 0;\n for (let i = 0; i < arr.length; i++) {\n const v = parseFloat(arr[i]);\n if (!isNaN(v)) {\n total += v;\n }\n }\n return total;\n};\n\n/**\n * Random integer between two numbers (stolen from underscorejs)\n * @param {Number} [min=0] mininum value\n * @param {Number} [max=null] maximum value\n * @returns {Number} random value\n */\nconst randomInteger = function (min = 0, max = null) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n};\n\n/**\n * Random value selection\n * @param {Array} values an array of objects from which to choose\n * @param {Array} weights a matching array of integers to weight the values (i.e. values and weights are in the same order)\n * @returns {String} the randomly selected Array element from values param\n */\nconst getWeightedRandom = function (values, weights) {\n let n = 0;\n const num = randomInteger(1, arraySum.call(this, weights));\n let i = 0;\n for (i; i < values.length; i++) {\n n = n + weights[i];\n if (n >= num) {\n break;\n }\n }\n return values[i];\n};\n/**\n * Random value selection, wrapper for getWeightedRandom that processes the data into values/weights arrays\n * @param {String[]} data values\n * @returns {String|null} the randomly selected string\n */\nconst randomString = function (data) {\n const values = [];\n const weights = [];\n\n if (!Array.isArray(data) || data.length === 0) {\n return null;\n }\n data.forEach((entry) => {\n weights.push(1);\n values.push(entry);\n });\n\n return getWeightedRandom(values, weights);\n};\n\nexport {\n randomInteger,\n getWeightedRandom,\n randomString\n};\n", "/* eslint-disable no-useless-escape */\nimport { randomInteger } from './randomizer.js';\n\n/**\n * @prop {String} die Die notation.\n * @prop {Number} value Random roll for the die notation.\n */\nclass DiceResult {\n constructor ({\n die = '',\n value = 0\n }) {\n this.die = die;\n this.value = value;\n }\n toString () {\n return this.value;\n }\n toJSON () {\n return {\n className: 'DiceResult',\n die: this.die,\n value: this.value\n };\n }\n}\n\nclass DiceRoller {\n /**\n *\n * @param {Number} die Die type\n * @returns {Number}\n */\n getSingleDieResult (die) {\n return randomInteger(1, die);\n }\n /**\n * Apply a modifier to the number of dice retained.\n * @param {Number[]} rolls\n * @param {String} diemod Modifier to dice (drop/keep high/low count).\n * @returns\n */\n applyDieMod (rolls, diemod) {\n const m = diemod.match(/^([dklh]{2})([0-9]*)$/);\n if (m === null) {\n return rolls;\n }\n const count = !m[2] ? 1 : parseInt(m[2]);\n switch (m[1]) {\n case 'dl':\n // Sort ascending\n rolls.sort((a, b) => a - b);\n rolls.splice(0, count);\n return rolls;\n case 'dh':\n // Sort descending\n rolls.sort((a, b) => b - a);\n rolls.splice(0, count);\n return rolls;\n case 'kl':\n // Sort ascending\n rolls.sort((a, b) => a - b);\n return rolls.slice(0, count);\n case 'kh':\n // Sort descending\n rolls.sort((a, b) => b - a);\n return rolls.slice(0, count);\n default:\n return rolls;\n }\n }\n /**\n * Dice rolling simulator\n * @param {Number} [die=6] Die type\n * @param {Number} [number=1] Number of times to roll the die\n * @param {Number} [modifier=0] Numeric modifier to dice total\n * @param {String} [mod_op=+] Operator for the modifier (+,-,/,*)\n * @param {String} [diemod=''] Modifier to the dice (like keep/drop high/low die)\n * @returns {Number} Number rolled (die*number [mod_op][modifier])\n */\n _parseDiceNotation (die = 6, number = 1, modifier = 0, mod_op = '+', diemod = '') {\n modifier = parseInt(modifier, 10);\n die = parseInt(die, 10);\n\n if (number <= 0) {\n number = 1;\n } else {\n number = parseInt(number, 10);\n }\n\n let rolls = [];\n for (let i = 1; i <= number; i++) {\n rolls.push(this.getSingleDieResult(die));\n }\n\n if (diemod !== '') {\n rolls = this.applyDieMod(rolls, diemod);\n }\n let sum = 0;\n if (rolls.length > 0) {\n sum = rolls.reduce((total, cur) => {\n return total + cur;\n });\n }\n if (modifier === 0) {\n return sum;\n }\n\n switch (mod_op) {\n case '*':\n sum = sum * modifier;\n break;\n case '-':\n sum = sum - modifier;\n break;\n case '/':\n sum = sum / modifier;\n break;\n case '+':\n default:\n sum = sum + modifier;\n break;\n }\n return Math.round(sum);\n }\n /**\n * takes a string like '3d6+2', 'd6', '2d6', parses it, and puts it through roll\n * @params {String} string a die roll notation\n * @returns {Number} the result of the roll\n */\n rollDie (string = '') {\n string = string.trim();\n const m = string.match(/^([0-9]*)d([0-9]+)([dklh]{2}[0-9]*)*(?:([\\+\\-\\*\\/])([0-9]+))*$/);\n if (!m) {\n return '';\n }\n return this._parseDiceNotation(m[2], m[1], m[5], m[4], m[3]);\n }\n /**\n * Return a dice result.\n * @param {String} die Die roll notation.\n * @returns {DiceResult}\n */\n getDiceResult (die = '') {\n return new DiceResult({\n die,\n value: this.rollDie(die)\n });\n }\n}\n\n/**\n * takes a string like '3d6+2', 'd6', '2d6', parses it, and puts it through roll\n * @params {String} string a die roll notation\n * @returns {Number} the result of the roll\n */\nconst rollDie = function (string = '') {\n const roller = new DiceRoller();\n return roller.rollDie(string);\n};\n\n/**\n * Return a dice result.\n * @param {String} die Die roll notation.\n * @returns {DiceResult}\n */\nconst getDiceResult = function (die = '') {\n const roller = new DiceRoller();\n return new DiceResult({\n die,\n value: roller.rollDie(die)\n });\n};\n\nexport {\n rollDie,\n DiceResult,\n getDiceResult,\n DiceRoller\n};\nexport default DiceRoller;\n", "/**\n * Class for handling dragging an HTMLElement around the screen.\n *\n * @prop {Number} _startX X coordinate in pixels of drag event when it starts.\n * @prop {Number} _startY Y coordinate in pixels of drag event when it starts.\n * @prop {Number} _startPosX Offset in pixels for the Element when drag starts.\n * @prop {Number} _startPosY Offset in pixels for the Element when drag starts.\n * @prop {Number} _startWidth Starting width of element for resize.\n * @prop {Number} _startHeight Starting height of element for resize.\n * @prop {Boolean} enabled Are dragging events currently enabled.\n * @prop {Function} doDragCallback Bound callback for the drag event.\n * @prop {Function} stopDragCallback Bound callback for the stop drag event.\n * @prop {Function} doResizeCallback Bound callback for the resize event.\n * @prop {Function} stopResizeCallback Bound callback for the stop resize event.\n * @prop {Function} callbackStartDrag Custom callback for when a drag starts. Passed the: dragElement, handleSelector.\n */\nexport default class Dragger {\n /**\n * @prop {HTMLElement} dragElement Element to drag around.\n * @prop {String} handleSelector Selector for the child element inside dragElement which activates dragging. Don't make this a button.\n */\n constructor ({\n dragElement = null,\n handleSelector = null\n }) {\n this.dragElement = dragElement;\n if (!(this.dragElement instanceof HTMLElement)) {\n throw new Error('Dragger.dragElements must be HTMLElement');\n }\n this.handleSelector = handleSelector;\n\n // By binding all these we make sure they can be removed properly.\n this.initDragBound = this.initDrag.bind(this);\n this.doDragCallback = this.doDrag.bind(this);\n this.stopDragCallback = this.stopDrag.bind(this);\n\n this._startX = null;\n this._startY = null;\n this._startPosX = null;\n this._startPosY = null;\n this._startWidth = null;\n this._startHeight = null;\n this.enabled = false;\n this.callbackStartDrag = null;\n }\n /**\n * Get the x position of the mouse/touch.\n * @param {Event} ev Drag or touch Event\n * @return {Number}\n */\n getEventX (ev) {\n return (ev.type.toLowerCase().indexOf('touch') === 0) ? ev.touches[0].clientX : ev.clientX;\n }\n /**\n * Get the y position of the mouse/touch.\n * @param {Event} ev Drag or touch Event\n * @return {Number}\n */\n getEventY (ev) {\n return (ev.type.toLowerCase().indexOf('touch') === 0) ? ev.touches[0].clientY : ev.clientY;\n }\n /**\n * Move the box as we drag\n * @param {Event} ev Drag or touch Event\n */\n doDrag (ev) {\n ev.preventDefault();\n // Adjust the node coords based on how much the event moved.\n this.dragElement.coords = [\n this._startPosX + (this.getEventX(ev) - this._startX),\n this._startPosY + (this.getEventY(ev) - this._startY)\n ];\n }\n /**\n * Stop the drag, make sure the box is visible, clean up.\n */\n stopDrag () {\n // make sure it isn't off the map.\n if (typeof this.dragElement.adjustForParentBounds === 'function') {\n this.dragElement.adjustForParentBounds();\n }\n // save it's location now that the drag is over.\n if (typeof this.dragElement.saveCoords === 'function') {\n this.dragElement.saveCoords();\n }\n document.documentElement.removeEventListener('mousemove', this.doDragCallback, false);\n document.documentElement.removeEventListener('touchmove', this.doDragCallback, false);\n document.documentElement.removeEventListener('mouseup', this.stopDragCallback, false);\n document.documentElement.removeEventListener('touchend', this.stopDragCallback, false);\n }\n /**\n * Start a drag action\n * @param {Event} ev Event for mouse down or touchstart\n */\n initDrag (ev) {\n // Stop on center/right clicks.\n if (ev.button > 1) {\n return;\n }\n ev.preventDefault();\n ev.stopPropagation();\n this._startX = this.getEventX(ev);\n this._startY = this.getEventY(ev);\n [this._startPosX, this._startPosY] = this.dragElement.coords;\n if (this.callbackStartDrag !== null) {\n this.callbackStartDrag(this.dragElement, this.handleSelector);\n }\n document.documentElement.addEventListener('mousemove', this.doDragCallback, false);\n document.documentElement.addEventListener('touchmove', this.doDragCallback, false);\n document.documentElement.addEventListener('mouseup', this.stopDragCallback, false);\n document.documentElement.addEventListener('touchend', this.stopDragCallback, false);\n }\n /**\n * Remove events stop dragging from working.\n */\n disableDrag () {\n if (!this.enabled) {\n return;\n }\n this.dragElement.removeEventListener('mousedown', this.initDragBound, false);\n this.dragElement.removeEventListener('touchstart', this.initDragBound, false);\n const dragHandle = this.handleSelector === ''\n ? this.dragElement\n : this.dragElement.querySelector(this.handleSelector);\n if (dragHandle !== null) {\n dragHandle.style.cursor = 'auto';\n }\n this.enabled = false;\n }\n /**\n * Re-add events starts dragging working again.\n */\n enableDrag () {\n if (this.enabled) {\n return;\n }\n this.dragElement.addEventListener('mousedown', this.initDragBound, false);\n this.dragElement.addEventListener('touchstart', this.initDragBound, false);\n const dragHandle = this.handleSelector === ''\n ? this.dragElement\n : this.dragElement.querySelector(this.handleSelector);\n if (dragHandle !== null) {\n dragHandle.style.cursor = 'move';\n }\n this.enabled = true;\n }\n};\n", "import Dragger from '../utils/dragger.js';\nimport { randomInteger } from 'rpg-table-randomizer/src/randomizer.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n
    \n\n\n`;\n\nclass Die extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.resultDiv = this.shadowRoot.querySelector('div');\n // Default to d6\n this._die = '1d6';\n // Default to empty\n this._result = '';\n this._coords = [0, 0];\n }\n connectedCallback () {\n this.removeButton = this.shadowRoot.querySelector('button.btn-remove');\n this.dragger = new Dragger({\n dragElement: this\n });\n\n this._upgradeProperty('die');\n this._upgradeProperty('result');\n this._upgradeProperty('coords');\n this._updateLabels();\n this.removeButton.addEventListener('click', this.remove.bind(this));\n const [x1, y1] = this.coords;\n if (x1 === 0 && y1 === 0) {\n // Offset from the parent roller.\n // @todo code to avoid collisions, particular with the \"roller\"\n // offset from the dice-roller parent.\n let { x, y } = this.getRootNode().host.getBoundingClientRect();\n x = x + randomInteger(-200, 200);\n y = y + randomInteger(-200, 200);\n this.coords = [x, y];\n }\n this.dragger.enableDrag();\n }\n disconnectedCallback () {\n this.removeButton.removeEventListener('click', this.remove.bind(this));\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Update accessible label on component\n */\n _updateLabels () {\n this.setAttribute('aria-label', `${this.die} roll result: ${this.result}`);\n this.shadowRoot.querySelector('small').innerText = `${this.die}`;\n }\n\n get die () {\n return this._die;\n }\n set die (value) {\n // Should this validate?\n this._die = value;\n this._updateLabels();\n }\n\n get result () {\n return this._result;\n }\n set result (value) {\n this._result = value;\n this.resultDiv.innerText = this._result;\n this._updateLabels();\n }\n\n get coords () {\n return this._coords;\n }\n\n set coords ([x, y]) {\n // @todo this could be cleaned up a lot.\n if (x < 0) {\n x = 0;\n }\n if (x > window.innerWidth) {\n x = window.innerWidth - this.offsetWidth;\n }\n if (y < 0) {\n y = 0;\n }\n if (y > window.innerHeight) {\n y = window.innerHeight - this.offsetHeight;\n }\n this._coords = [x, y];\n this.style.left = `${x}px`;\n this.style.top = `${y}px`;\n this.style.bottom = 'auto';\n this.style.right = 'auto';\n }\n /**\n * Remove the die.\n */\n remove () {\n this.dispatchEvent(\n new CustomEvent(\n 'dice:remove',\n {\n bubbles: true,\n detail: {\n die: this\n }\n }\n )\n );\n }\n}\n\nif (!window.customElements.get('dice-single')) {\n window.customElements.define('dice-single', Die);\n}\n\nexport default Die;\n", "import { getDiceResult, DiceResult } from 'rpg-table-randomizer/src/dice_roller.js';\nimport Die from './Die.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n\n
    \n\n`;\n\nclass DiceRoller extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this._dice = [];\n }\n connectedCallback () {\n this.resultDiv = this.shadowRoot.getElementById('dice-result');\n this.resetButton = this.shadowRoot.querySelector('button.btn-reset');\n\n this._upgradeProperty('dice');\n\n // Remove event from child Die elements.\n this.shadowRoot.addEventListener('dice:remove', this._removeDie.bind(this));\n // Click handler for slotted buttons\n Array.from(this.children).forEach((buttons) => {\n buttons.addEventListener('click', this._handleRoll.bind(this));\n });\n // Clear all dice\n this.resetButton.addEventListener('click', this.reset.bind(this));\n }\n disconnectedCallback () {\n this.shadowRoot.removeEventListener('dice:remove', this._removeDie.bind(this));\n Array.from(this.children).forEach((buttons) => {\n buttons.removeEventListener('click', this._handleRoll.bind(this));\n });\n this.resetButton.removeEventListener('click', this.reset.bind(this));\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Roll a result from an internal event\n * @param {Event} ev Click event on element.\n */\n _handleRoll (ev) {\n const button = ev.target;\n const die = button.dataset.die || '';\n const roll = getDiceResult(`${die}`);\n this._addDie(roll);\n }\n /**\n * Handle roll from external to the component.\n * @param {String} die\n */\n roll (die = '1d6') {\n const roll = getDiceResult(die);\n this._addDie(roll);\n }\n /**\n * @returns {Die[]}\n */\n get dice () {\n return this._dice;\n }\n /**\n * Resets dice to passed ones.\n * @param {Die[]} value\n */\n set dice (value) {\n if (!Array.isArray(value)) {\n throw Error('Dice must be array');\n }\n this._dice = value;\n this.resultDiv.innerHTML = '';\n this._dice.forEach((die) => {\n if (!(die instanceof Die)) {\n return;\n }\n this.resultDiv.appendChild(die);\n });\n }\n /**\n * @param {DiceResult} diceResult\n */\n _addDie (diceResult) {\n const die = new Die();\n die.die = diceResult.die;\n die.result = diceResult.value;\n this._dice.push(die);\n this.resultDiv.appendChild(die);\n }\n /**\n * @param {CustomEvent} ev\n */\n _removeDie (ev) {\n ev.stopImmediatePropagation();\n const die = ev.detail.die || null;\n if (!die) {\n return;\n }\n const index = this._dice.findIndex((d) => d === die);\n if (index < 0) {\n return;\n }\n const dieEl = this._dice[index];\n this.resultDiv.removeChild(dieEl);\n this._dice.splice(index, 1);\n // this.dice = this.dice.filter((d) => d !== die);\n }\n /**\n * Reset the rolls\n */\n reset () {\n this.dice = [];\n }\n}\n\nif (!window.customElements.get('dice-roller')) {\n window.customElements.define('dice-roller', DiceRoller);\n}\n\nexport default DiceRoller;\n", "/**\n * Simple Editable field.\n */\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n`;\n\nclass EditableField extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n if (this.hasAttribute('placeholder')) {\n this.placeholderText = this.getAttribute('placeholder');\n }\n\n // add event listeners\n this.addEventListener('blur', this._blur);\n this._upgradeProperty('fieldName');\n }\n\n disconnectedCallback () {\n // remove event listeners\n this.removeEventListener('blur', this._blur);\n }\n /**\n * In case the property was set before connecting\n * this makes sure the value is retrieved and then reset so that the setter will get used.\n * @param {String} prop\n */\n _upgradeProperty (prop) {\n if (Object.prototype.hasOwnProperty.call(this, prop)) {\n const value = this[prop];\n delete this[prop];\n this[prop] = value;\n }\n }\n /**\n * Setter: field name for data.\n */\n set fieldName (value) {\n this.dataset.name = value;\n }\n /**\n * Getter: field name for data.\n */\n get fieldName () {\n return this.dataset.name || '';\n }\n get placeholderText () {\n this.shadowRoot.querySelector('span').getAttribute('placeholder');\n }\n /**\n * Set placeholder text in the field.\n */\n set placeholderText (val) {\n this.shadowRoot.querySelector('span').setAttribute('placeholder', val);\n }\n /**\n * Getter: Content of field.\n * @returns {String}\n */\n get content () {\n return this.shadowRoot.querySelector('span').innerHTML;\n }\n /**\n * Setter: Content of field.\n * @param {String} value\n */\n set content (value) {\n this.shadowRoot.querySelector('span').innerHTML = value;\n }\n /**\n * On blur dispatch an event so the character model can be updated.\n * @param {Event} ev\n */\n _blur (ev) {\n let currentVal = this.content;\n // Trim empty end spaces/line breaks\n currentVal = currentVal.trim().replace(/(\\s| |)+$/, '');\n this.content = currentVal;\n const detail = {\n field: this.fieldName,\n value: currentVal\n };\n this.dispatchEvent(new CustomEvent('fieldChange', { bubbles: true, detail }));\n }\n /**\n * Focus\n */\n focus () {\n this.shadowRoot.querySelector('[contenteditable=true]').focus();\n }\n}\n\nwindow.customElements.define('field-editable', EditableField);\n\nexport default EditableField;\n", "/**\n * Navigation links for page/tabs.\n * Dynamically updates depending on SheetView type.\n */\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n
      \n
    1. Top
    2. \n
    \n`;\n\nclass FooterNav extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.setAttribute('role', 'navigation');\n this.setAttribute('aria-label', 'Character sheet tab/section navigation');\n this.list = this.shadowRoot.querySelector('ol');\n this.topLink = this.shadowRoot.querySelector('li:first-child');\n\n this.shadowRoot.addEventListener('click', this._handleClicks.bind(this));\n }\n\n _handleClicks (ev) {\n if (ev.target.tagName === 'A') {\n ev.preventDefault();\n const link = ev.target;\n const targetPane = link.dataset.tab;\n\n const sheetView = document.querySelector('[data-sheetview]');\n if (targetPane) {\n sheetView.switchToPane(targetPane);\n }\n const target_id = link.getAttribute('href');\n sheetView.navigateTo(target_id);\n }\n }\n /**\n * Set links in header.\n * @param {Object[]} links\n */\n setLinks (links) {\n links.forEach((link) => {\n const li = document.createElement('li');\n const a = document.createElement('a');\n a.href = link.href || '';\n a.innerText = link.label || '';\n a.dataset.tab = link.tab || '';\n li.appendChild(a);\n this.list.appendChild(li);\n });\n }\n /**\n * Remove all but the top link.\n */\n removeLinks () {\n this.shadowRoot.querySelectorAll('li').forEach((el) => {\n if (el === this.topLink) {\n return;\n }\n el.parentNode.removeChild(el);\n });\n }\n}\n\nif (!window.customElements.get('footer-nav')) {\n window.customElements.define('footer-nav', FooterNav);\n}\n\nexport default FooterNav;\n", "/**\n * Modal.\n */\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n

    \n\n `;\n\nclass Modal extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.setAttribute('role', 'dialog');\n this.setAttribute('aria-labelledby', 'modal-label');\n\n this.boundOutsideClickClose = function () {};\n this.boundKeyboardEvents = function () {};\n this.opener = null;\n this.addEventListener('click', this.handleCloseClick);\n }\n\n connectedCallback () {\n }\n\n disconnectedCallback () {\n }\n\n get header () {\n return this.shadowRoot.querySelector('slot[name=\"header\"]').innerHTML;\n }\n set header (html) {\n this.shadowRoot.querySelector('slot[name=\"header\"]').innerHTML = html;\n }\n /**\n * Is the modal open or not\n */\n get isOpen () {\n return !this.hidden;\n }\n /**\n * Return a close button to use\n * @returns {HTMLElement} button.close\n */\n getCloseButton () {\n const button = document.createElement('button');\n button.setAttribute('type', 'button');\n button.classList.add('close');\n button.textContent = 'Close';\n button.setAttribute('slot', 'content');\n return button;\n }\n /**\n * Adapted from https://github.com/salesforce/kagekiri\n * Get children of a node, including getting slotted content.\n * @param {HTMLElement} node\n * @returns HTMLCollection|HTMLElement[]\n */\n getChildren (node) {\n // is it a slot.\n if (typeof node.assignedElements === 'function') {\n const assigned = node.assignedElements();\n // slotted content or the default\n return assigned.length ? assigned : node.children;\n } else {\n return node.children;\n }\n }\n /**\n * Is an element focusable.\n * This probably doesn't cover ALL possibilities, but its a decent start.\n * @param {HTMLElement} element\n * @param {Boolean} keyboardOnly Are we only looking for tabbable focus.\n */\n isFocusable (element, keyboardOnly = false) {\n const tagName = element.tagName;\n // Just in case.\n if (tagName === undefined) {\n return false;\n }\n // Will be false-y if not set/available.\n const disabled = element.disabled;\n // Convert to integer or NaN if tabindex is not set.\n const tabIndex = parseInt(element.getAttribute('tabindex'), 10);\n const contentEditable = element.getAttribute('contenteditable');\n\n switch (tagName) {\n case 'INPUT':\n case 'TEXTAREA':\n case 'SELECT':\n case 'BUTTON':\n case 'A':\n if (tabIndex === -1) {\n return false;\n }\n if (disabled) {\n return false;\n }\n if (tagName === 'A' && !element.href) {\n return false;\n }\n return true;\n default:\n if (keyboardOnly && tabIndex >= 0) {\n return true;\n } else if (!keyboardOnly && tabIndex >= -1) {\n return true;\n }\n if (contentEditable === 'true') {\n return true;\n }\n }\n return false;\n }\n /**\n * Get focusable elements recursively.\n * @param {HTMLElement} element\n * @param {Boolean} keyboardOnly Only tabbable elements?\n * @param {Boolean} single Only get the first one.\n * @returns\n */\n getFocusableChildren (element, keyboardOnly = false, single = false) {\n let focusables = [];\n const children = Array.from(this.getChildren(element));\n if (children.length === 0) {\n return focusables;\n }\n for (const child of children) {\n // check if element is focusable.\n if (this.isFocusable(child, keyboardOnly)) {\n focusables.push(child);\n if (single) {\n return focusables;\n }\n }\n const childFocusables = this.getFocusableChildren(child, keyboardOnly, single);\n if (single && childFocusables.length === 1) {\n return childFocusables;\n }\n focusables = focusables.concat(childFocusables);\n }\n return focusables;\n }\n /**\n * Get focusable elements in the component\n * Shadow DOM and slotted elements\n * Theoretically in the correct order.\n * @param {Boolean} keyboardOnly Only tabbable elements?\n * @param {Boolean} single Only get the first one.\n * @returns {HTMLElement[]}\n */\n findFocusables (keyboardOnly = false, single = false) {\n return this.getFocusableChildren(this.shadowRoot, keyboardOnly, single);\n }\n /**\n * Get the first focusable element in the modal.\n * @returns {HTMLElement|null}\n */\n findFirstFocusable () {\n return this.findFocusables(false, true).shift();\n }\n /**\n * Get the first tabbing focusable element in the modal.\n * @returns {HTMLElement|null}\n */\n findFirstTabFocusable () {\n return this.findFocusables(true, true).shift();\n }\n /**\n * Return last focusable element in the modal.\n * @returns {HTMLElement|null}\n */\n findLastTabFocusable () {\n const focusables = this.findFocusables(true);\n return focusables[focusables.length - 1];\n }\n /**\n * Find first focusable element in modal and focus on it.\n */\n focusFirst () {\n const focusable = this.findFirstFocusable();\n if (focusable) {\n focusable.focus();\n }\n }\n /**\n * Handler: Clicks outside modal close the modal.\n * Bound to this then listens on document.\n * @param {MouseEvent} ev Click event.\n */\n outsideClickClose (ev) {\n const close = ev.target.closest('modal-mib');\n if (close === null) {\n if (ev.target.classList.contains('btn-dialog')) {\n return;\n }\n // Hide the help.\n this.close();\n this.clear();\n }\n }\n /**\n * Get focused element.\n */\n deepActiveElement () {\n let a = document.activeElement;\n while (a && a.shadowRoot && a.shadowRoot.activeElement) {\n a = a.shadowRoot.activeElement;\n }\n return a;\n }\n /**\n * Handler: Keyboard events to:\n * - Close on Esc\n * - Trap tab focus into modal.\n * @param {KeyboardEvent} ev Keydown event\n */\n keyboardEvents (ev) {\n if (ev.key === 'Escape') {\n this.close();\n return;\n }\n if (ev.key !== 'Tab') {\n return;\n }\n // Get current active/focused element.\n const currentEl = this.deepActiveElement();\n if (ev.shiftKey) {\n // Shift tab, only concerned with first element.\n if (currentEl === this.findFirstFocusable() || currentEl === this.findFirstTabFocusable()) {\n // Go to the last element in the modal.\n const focusable = this.findLastTabFocusable();\n if (focusable) {\n ev.preventDefault();\n focusable.focus();\n }\n }\n return;\n }\n // Tab (no shift), only concerned with last element.\n if (currentEl === this.findLastTabFocusable()) {\n // Go to the first element in the modal.\n const focusable = this.findFirstTabFocusable();\n if (focusable) {\n ev.preventDefault();\n focusable.focus();\n }\n }\n }\n /**\n * Open/show Modal\n */\n open () {\n if (this.isOpen) {\n return;\n }\n /**\n * Get the opener trigger (usually a button/link).\n */\n this.opener = this.deepActiveElement();\n this.hidden = false;\n this.focusFirst();\n // We need to do this to be able to remove the listener later.\n this.boundOutsideClickClose = this.outsideClickClose.bind(this);\n document.addEventListener('click', this.boundOutsideClickClose, true);\n this.boundKeyboardEvents = this.keyboardEvents.bind(this);\n document.addEventListener('keydown', this.boundKeyboardEvents, true);\n }\n /**\n * Close the modal.\n * Return focus to whatever opened it.\n */\n close () {\n this.hidden = true;\n // Remove click handler to close modal.\n document.removeEventListener('click', this.boundOutsideClickClose, true);\n document.removeEventListener('keydown', this.boundKeyboardEvents, true);\n if (this.opener) {\n this.opener.focus();\n }\n }\n /**\n * Clear the modal, by removing the slotted elements in the light DOM\n * Leaves the shadow DOM alone so we can reslot.\n */\n clear () {\n while (this.firstChild) {\n this.removeChild(this.firstChild);\n }\n }\n /**\n * Close and clear contents.\n */\n closeClear () {\n this.close();\n this.clear();\n }\n /**\n * Handler clicks in the modal.\n * If it's the close button then close the modal.\n * @param {Event} ev Click event\n */\n handleCloseClick (ev) {\n if (ev.target.classList.contains('close')) {\n // Close button click\n ev.preventDefault();\n this.close();\n this.clear();\n }\n }\n /**\n * Add content to modal.\n * This adds the content slotted item to the light DOM.\n * @param {HTMLElement[]|HTMLElement} content single element or Array of elements\n * @param {Boolean} includeCloseButton Include a close button at the bottom.\n */\n setContent (content, includeCloseButton = true) {\n if (!Array.isArray(content)) {\n content = [content];\n }\n this.clear(); // make sure we start empty\n const f = document.createDocumentFragment();\n content.forEach((el) => {\n // Default to content slot.\n if (!el.getAttribute('slot')) {\n el.setAttribute('slot', 'content');\n }\n f.appendChild(el);\n });\n if (includeCloseButton) {\n f.appendChild(this.getCloseButton());\n }\n this.appendChild(f);\n }\n}\n\nif (!window.customElements.get('modal-mib')) {\n window.customElements.define('modal-mib', Modal);\n}\n\nexport default Modal;\n", "[\n {\n \"index\": \"acid-arrow\",\n \"name\": \"Acid Arrow\",\n \"desc\": [\n \"A shimmering green arrow streaks toward a target within range and bursts in a spray of acid. Make a ranged spell attack against the target. On a hit, the target takes 4d4 acid damage immediately and 2d4 acid damage at the end of its next turn. On a miss, the arrow splashes the target with acid for half as much of the initial damage and no damage at the end of its next turn.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage (both initial and later) increases by 1d4 for each slot level above 2nd.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Powdered rhubarb leaf and an adder's stomach.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"acid\",\n \"name\": \"Acid\",\n \"url\": \"/api/damage-types/acid\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"4d4\",\n \"3\": \"5d4\",\n \"4\": \"6d4\",\n \"5\": \"7d4\",\n \"6\": \"8d4\",\n \"7\": \"9d4\",\n \"8\": \"10d4\",\n \"9\": \"11d4\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/acid-arrow\"\n },\n {\n \"index\": \"acid-splash\",\n \"name\": \"Acid Splash\",\n \"desc\": [\n \"You hurl a bubble of acid. Choose one creature within range, or choose two creatures within range that are within 5 feet of each other. A target must succeed on a dexterity saving throw or take 1d6 acid damage.\",\n \"This spell's damage increases by 1d6 when you reach 5th level (2d6), 11th level (3d6), and 17th level (4d6).\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"acid\",\n \"name\": \"Acid\",\n \"url\": \"/api/damage-types/acid\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d6\",\n \"5\": \"2d6\",\n \"11\": \"3d6\",\n \"17\": \"4d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/acid-splash\"\n },\n {\n \"index\": \"aid\",\n \"name\": \"Aid\",\n \"desc\": [\n \"Your spell bolsters your allies with toughness and resolve. Choose up to three creatures within range. Each target's hit point maximum and current hit points increase by 5 for the duration.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, a target's hit points increase by an additional 5 for each slot level above 2nd.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny strip of white cloth.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"heal_at_slot_level\": {\n \"2\": \"5\",\n \"3\": \"10\",\n \"4\": \"15\",\n \"5\": \"20\",\n \"6\": \"25\",\n \"7\": \"30\",\n \"8\": \"35\",\n \"9\": \"40\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/aid\"\n },\n {\n \"index\": \"alarm\",\n \"name\": \"Alarm\",\n \"desc\": [\n \"You set an alarm against unwanted intrusion. Choose a door, a window, or an area within range that is no larger than a 20-foot cube. Until the spell ends, an alarm alerts you whenever a Tiny or larger creature touches or enters the warded area. When you cast the spell, you can designate creatures that won't set off the alarm. You also choose whether the alarm is mental or audible.\",\n \"A mental alarm alerts you with a ping in your mind if you are within 1 mile of the warded area. This ping awakens you if you are sleeping.\",\n \"An audible alarm produces the sound of a hand bell for 10 seconds within 60 feet.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny bell and a piece of fine silver wire.\",\n \"ritual\": true,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/alarm\"\n },\n {\n \"index\": \"alter-self\",\n \"name\": \"Alter Self\",\n \"desc\": [\n \"You assume a different form. When you cast the spell, choose one of the following options, the effects of which last for the duration of the spell. While the spell lasts, you can end one option as an action to gain the benefits of a different one.\",\n \"***Aquatic Adaptation.*** You adapt your body to an aquatic environment, sprouting gills and growing webbing between your fingers. You can breathe underwater and gain a swimming speed equal to your walking speed.\",\n \"***Change Appearance.*** You transform your appearance. You decide what you look like, including your height, weight, facial features, sound of your voice, hair length, coloration, and distinguishing characteristics, if any. You can make yourself appear as a member of another race, though none of your statistics change. You also can't appear as a creature of a different size than you, and your basic shape stays the same; if you're bipedal, you can't use this spell to become quadrupedal, for instance. At any time for the duration of the spell, you can use your action to change your appearance in this way again.\",\n \"***Natural Weapons.*** You grow claws, fangs, spines, horns, or a different natural weapon of your choice. Your unarmed strikes deal 1d6 bludgeoning, piercing, or slashing damage, as appropriate to the natural weapon you chose, and you are proficient with your unarmed strikes. Finally, the natural weapon is magic and you have a +1 bonus to the attack and damage rolls you make using it.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/alter-self\"\n },\n {\n \"index\": \"animal-friendship\",\n \"name\": \"Animal Friendship\",\n \"desc\": [\n \"This spell lets you convince a beast that you mean it no harm. Choose a beast that you can see within range. It must see and hear you. If the beast's Intelligence is 4 or higher, the spell fails. Otherwise, the beast must succeed on a wisdom saving throw or be charmed by you for the spell's duration. If you or one of your companions harms the target, the spells ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A morsel of food.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/animal-friendship\"\n },\n {\n \"index\": \"animal-messenger\",\n \"name\": \"Animal Messenger\",\n \"desc\": [\n \"By means of this spell, you use an animal to deliver a message. Choose a Tiny beast you can see within range, such as a squirrel, a blue jay, or a bat. You specify a location, which you must have visited, and a recipient who matches a general description, such as \\\"a man or woman dressed in the uniform of the town guard\\\" or \\\"a red-haired dwarf wearing a pointed hat.\\\" You also speak a message of up to twenty-five words. The target beast travels for the duration of the spell toward the specified location, covering about 50 miles per 24 hours for a flying messenger, or 25 miles for other animals.\",\n \"When the messenger arrives, it delivers your message to the creature that you described, replicating the sound of your voice. The messenger speaks only to a creature matching the description you gave. If the messenger doesn't reach its destination before the spell ends, the message is lost, and the beast makes its way back to where you cast this spell.\"\n ],\n \"higher_level\": [\n \"If you cast this spell using a spell slot of 3nd level or higher, the duration of the spell increases by 48 hours for each slot level above 2nd.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A morsel of food.\",\n \"ritual\": true,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/animal-messenger\"\n },\n {\n \"index\": \"animal-shapes\",\n \"name\": \"Animal Shapes\",\n \"desc\": [\n \"Your magic turns others into beasts. Choose any number of willing creatures that you can see within range. You transform each target into the form of a Large or smaller beast with a challenge rating of 4 or lower. On subsequent turns, you can use your action to transform affected creatures into new forms.\",\n \"The transformation lasts for the duration for each target, or until the target drops to 0 hit points or dies. You can choose a different form for each target. A target's game statistics are replaced by the statistics of the chosen beast, though the target retains its alignment and Intelligence, Wisdom, and Charisma scores. The target assumes the hit points of its new form, and when it reverts to its normal form, it returns to the number of hit points it had before it transformed. If it reverts as a result of dropping to 0 hit points, any excess damage carries over to its normal form. As long as the excess damage doesn't reduce the creature's normal form to 0 hit points, it isn't knocked unconscious. The creature is limited in the actions it can perform by the nature of its new form, and it can't speak or cast spells.\",\n \"The target's gear melds into the new form. The target can't activate, wield, or otherwise benefit from any of its equipment.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 24 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/animal-shapes\"\n },\n {\n \"index\": \"animate-dead\",\n \"name\": \"Animate Dead\",\n \"desc\": [\n \"This spell creates an undead servant. Choose a pile of bones or a corpse of a Medium or Small humanoid within range. Your spell imbues the target with a foul mimicry of life, raising it as an undead creature. The target becomes a skeleton if you chose bones or a zombie if you chose a corpse (the GM has the creature's game statistics).\",\n \"On each of your turns, you can use a bonus action to mentally command any creature you made with this spell if the creature is within 60 feet of you (if you control multiple creatures, you can command any or all of them at the same time, issuing the same command to each one). You decide what action the creature will take and where it will move during its next turn, or you can issue a general command, such as to guard a particular chamber or corridor. If you issue no commands, the creature only defends itself against hostile creatures. Once given an order, the creature continues to follow it until its task is complete.\",\n \"The creature is under your control for 24 hours, after which it stops obeying any command you've given it. To maintain control of the creature for another 24 hours, you must cast this spell on the creature again before the current 24-hour period ends. This use of the spell reasserts your control over up to four creatures you have animated with this spell, rather than animating a new one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, you animate or reassert control over two additional undead creatures for each slot level above 3rd. Each of the creatures must come from a different corpse or pile of bones.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of blood, a piece of flesh, and a pinch of bone dust.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 3,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/animate-dead\"\n },\n {\n \"index\": \"animate-objects\",\n \"name\": \"Animate Objects\",\n \"desc\": [\n \"Objects come to life at your command. Choose up to ten nonmagical objects within range that are not being worn or carried. Medium targets count as two objects, Large targets count as four objects, Huge targets count as eight objects. You can't animate any object larger than Huge. Each target animates and becomes a creature under your control until the spell ends or until reduced to 0 hit points.\",\n \"As a bonus action, you can mentally command any creature you made with this spell if the creature is within 500 feet of you (if you control multiple creatures, you can command any or all of them at the same time, issuing the same command to each one). You decide what action the creature will take and where it will move during its next turn, or you can issue a general command, such as to guard a particular chamber or corridor. If you issue no commands, the creature only defends itself against hostile creatures. Once given an order, the creature continues to follow it until its task is complete.\",\n \"##### Animated Object Statistics\",\n \"| Size | HP | AC | Attack | Str | Dex |\",\n \"|---|---|---|---|---|---|\",\n \"| Tiny | 20 | 18 | +8 to hit, 1d4 + 4 damage | 4 | 18 |\",\n \"| Small | 25 | 16 | +6 to hit, 1d8 + 2 damage | 6 | 14 |\",\n \"| Medium | 40 | 13 | +5 to hit, 2d6 + 1 damage | 10 | 12 |\",\n \"| Large | 50 | 10 | +6 to hit, 2d10 + 2 damage | 14 | 10 |\",\n \"| Huge | 80 | 10 | +8 to hit, 2d12 + 4 damage | 18 | 6 |\",\n \"An animated object is a construct with AC, hit points, attacks, Strength, and Dexterity determined by its size. Its Constitution is 10 and its Intelligence and Wisdom are 3, and its Charisma is 1. Its speed is 30 feet; if the object lacks legs or other appendages it can use for locomotion, it instead has a flying speed of 30 feet and can hover. If the object is securely attached to a surface or a larger object, such as a chain bolted to a wall, its speed is 0. It has blindsight with a radius of 30 feet and is blind beyond that distance. When the animated object drops to 0 hit points, it reverts to its original object form, and any remaining damage carries over to its original object form.\",\n \"If you command an object to attack, it can make a single melee attack against a creature within 5 feet of it. It makes a slam attack with an attack bonus and bludgeoning damage determined by its size. The GM might rule that a specific object inflicts slashing or piercing damage based on its form.\"\n ],\n \"higher_level\": [\n \"If you cast this spell using a spell slot of 6th level or higher, you can animate two additional objects for each slot level above 5th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/animate-objects\"\n },\n {\n \"index\": \"antilife-shell\",\n \"name\": \"Antilife Shell\",\n \"desc\": [\n \"A shimmering barrier extends out from you in a 10-foot radius and moves with you, remaining centered on you and hedging out creatures other than undead and constructs. The barrier lasts for the duration.\",\n \"The barrier prevents an affected creature from passing or reaching through. An affected creature can cast spells or make attacks with ranged or reach weapons through the barrier.\",\n \"If you move so that an affected creature is forced to pass through the barrier, the spell ends.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/antilife-shell\"\n },\n {\n \"index\": \"antimagic-field\",\n \"name\": \"Antimagic Field\",\n \"desc\": [\n \"A 10-foot-radius invisible sphere of antimagic surrounds you. This area is divorced from the magical energy that suffuses the multiverse. Within the sphere, spells can't be cast, summoned creatures disappear, and even magic items become mundane. Until the spell ends, the sphere moves with you, centered on you.\",\n \"Spells and other magical effects, except those created by an artifact or a deity, are suppressed in the sphere and can't protrude into it. A slot expended to cast a suppressed spell is consumed. While an effect is suppressed, it doesn't function, but the time it spends suppressed counts against its duration.\",\n \"***Targeted Effects.*** Spells and other magical effects, such as magic missile and charm person, that target a creature or an object in the sphere have no effect on that target.\",\n \"***Areas of Magic.*** The area of another spell or magical effect, such as fireball, can't extend into the sphere. If the sphere overlaps an area of magic, the part of the area that is covered by the sphere is suppressed. For example, the flames created by a wall of fire are suppressed within the sphere, creating a gap in the wall if the overlap is large enough.\",\n \"***Spells.*** Any active spell or other magical effect on a creature or an object in the sphere is suppressed while the creature or object is in it.\",\n \"***Magic Items.*** The properties and powers of magic items are suppressed in the sphere. For example, a +1 longsword in the sphere functions as a nonmagical longsword.\",\n \"A magic weapon's properties and powers are suppressed if it is used against a target in the sphere or wielded by an attacker in the sphere. If a magic weapon or a piece of magic ammunition fully leaves the sphere (for example, if you fire a magic arrow or throw a magic spear at a target outside the sphere), the magic of the item ceases to be suppressed as soon as it exits.\",\n \"***Magical Travel.*** Teleportation and planar travel fail to work in the sphere, whether the sphere is the destination or the departure point for such magical travel. A portal to another location, world, or plane of existence, as well as an opening to an extradimensional space such as that created by the rope trick spell, temporarily closes while in the sphere.\",\n \"***Creatures and Objects.*** A creature or object summoned or created by magic temporarily winks out of existence in the sphere. Such a creature instantly reappears once the space the creature occupied is no longer within the sphere.\",\n \"***Dispel Magic.*** Spells and magical effects such as dispel magic have no effect on the sphere. Likewise, the spheres created by different antimagic field spells don't nullify each other.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of powdered iron or iron filings.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/antimagic-field\"\n },\n {\n \"index\": \"antipathy-sympathy\",\n \"name\": \"Antipathy/Sympathy\",\n \"desc\": [\n \"This spell attracts or repels creatures of your choice. You target something within range, either a Huge or smaller object or creature or an area that is no larger than a 200-foot cube. Then specify a kind of intelligent creature, such as red dragons, goblins, or vampires. You invest the target with an aura that either attracts or repels the specified creatures for the duration. Choose antipathy or sympathy as the aura's effect.\",\n \"***Antipathy.*** The enchantment causes creatures of the kind you designated to feel an intense urge to leave the area and avoid the target. When such a creature can see the target or comes within 60 feet of it, the creature must succeed on a wisdom saving throw or become frightened. The creature remains frightened while it can see the target or is within 60 feet of it. While frightened by the target, the creature must use its movement to move to the nearest safe spot from which it can't see the target. If the creature moves more than 60 feet from the target and can't see it, the creature is no longer frightened, but the creature becomes frightened again if it regains sight of the target or moves within 60 feet of it.\",\n \"***Sympathy.*** The enchantment causes the specified creatures to feel an intense urge to approach the target while within 60 feet of it or able to see it. When such a creature can see the target or comes within 60 feet of it, the creature must succeed on a wisdom saving throw or use its movement on each of its turns to enter the area or move within reach of the target. When the creature has done so, it can't willingly move away from the target.\",\n \"If the target damages or otherwise harms an affected creature, the affected creature can make a wisdom saving throw to end the effect, as described below.\",\n \"***Ending the Effect.*** If an affected creature ends its turn while not within 60 feet of the target or able to see it, the creature makes a wisdom saving throw. On a successful save, the creature is no longer affected by the target and recognizes the feeling of repugnance or attraction as magical. In addition, a creature affected by the spell is allowed another wisdom saving throw every 24 hours while the spell persists.\",\n \"A creature that successfully saves against this effect is immune to it for 1 minute, after which time it can be affected again.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Either a lump of alum soaked in vinegar for the antipathy effect or a drop of honey for the sympathy effect.\",\n \"ritual\": false,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 8,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 200\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/antipathy-sympathy\"\n },\n {\n \"index\": \"arcane-eye\",\n \"name\": \"Arcane Eye\",\n \"desc\": [\n \"You create an invisible, magical eye within range that hovers in the air for the duration.\",\n \"You mentally receive visual information from the eye, which has normal vision and darkvision out to 30 feet. The eye can look in every direction.\",\n \"As an action, you can move the eye up to 30 feet in any direction. There is no limit to how far away from you the eye can move, but it can't enter another plane of existence. A solid barrier blocks the eye's movement, but the eye can pass through an opening as small as 1 inch in diameter.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of bat fur.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/arcane-eye\"\n },\n {\n \"index\": \"arcane-hand\",\n \"name\": \"Arcane Hand\",\n \"desc\": [\n \"You create a Large hand of shimmering, translucent force in an unoccupied space that you can see within range. The hand lasts for the spell's duration, and it moves at your command, mimicking the movements of your own hand.\",\n \"The hand is an object that has AC 20 and hit points equal to your hit point maximum. If it drops to 0 hit points, the spell ends. It has a Strength of 26 (+8) and a Dexterity of 10 (+0). The hand doesn't fill its space.\",\n \"When you cast the spell and as a bonus action on your subsequent turns, you can move the hand up to 60 feet and then cause one of the following effects with it.\",\n \"***Clenched Fist.*** The hand strikes one creature or object within 5 feet of it. Make a melee spell attack for the hand using your game statistics. On a hit, the target takes 4d8 force damage.\",\n \"***Forceful Hand.*** The hand attempts to push a creature within 5 feet of it in a direction you choose. Make a check with the hand's Strength contested by the Strength (Athletics) check of the target. If the target is Medium or smaller, you have advantage on the check. If you succeed, the hand pushes the target up to 5 feet plus a number of feet equal to five times your spellcasting ability modifier. The hand moves with the target to remain within 5 feet of it.\",\n \"***Grasping Hand.*** The hand attempts to grapple a Huge or smaller creature within 5 feet of it. You use the hand's Strength score to resolve the grapple. If the target is Medium or smaller, you have advantage on the check. While the hand is grappling the target, you can use a bonus action to have the hand crush it. When you do so, the target takes bludgeoning damage equal to 2d6 + your spellcasting ability modifier.\",\n \"***Interposing Hand.*** The hand interposes itself between you and a creature you choose until you give the hand a different command. The hand moves to stay between you and the target, providing you with half cover against the target. The target can't move through the hand's space if its Strength score is less than or equal to the hand's Strength score. If its Strength score is higher than the hand's Strength score, the target can move toward you through the hand's space, but that space is difficult terrain for the target.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the damage from the clenched fist option increases by 2d8 and the damage from the grasping hand increases by 2d6 for each slot level above 5th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An eggshell and a snakeskin glove.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/arcane-hand\"\n },\n {\n \"index\": \"arcane-lock\",\n \"name\": \"Arcane Lock\",\n \"desc\": [\n \"You touch a closed door, window, gate, chest, or other entryway, and it becomes locked for the duration. You and the creatures you designate when you cast this spell can open the object normally. You can also set a password that, when spoken within 5 feet of the object, suppresses this spell for 1 minute. Otherwise, it is impassable until it is broken or the spell is dispelled or suppressed. Casting knock on the object suppresses arcane lock for 10 minutes.\",\n \"While affected by this spell, the object is more difficult to break or force open; the DC to break it or pick any locks on it increases by 10.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Gold dust worth at least 25gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/arcane-lock\"\n },\n {\n \"index\": \"arcane-sword\",\n \"name\": \"Arcane Sword\",\n \"desc\": [\n \"You create a sword-shaped plane of force that hovers within range. It lasts for the duration.\",\n \"When the sword appears, you make a melee spell attack against a target of your choice within 5 feet of the sword. On a hit, the target takes 3d10 force damage. Until the spell ends, you can use a bonus action on each of your turns to move the sword up to 20 feet to a spot you can see and repeat this attack against the same target or a different one.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A miniature platinum sword with a grip and pommel of copper and zinc, worth 250 gp.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"7\": \"3d10\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/arcane-sword\"\n },\n {\n \"index\": \"arcanists-magic-aura\",\n \"name\": \"Arcanist's Magic Aura\",\n \"desc\": [\n \"You place an illusion on a creature or an object you touch so that divination spells reveal false information about it. The target can be a willing creature or an object that isn't being carried or worn by another creature.\",\n \"When you cast the spell, choose one or both of the following effects. The effect lasts for the duration. If you cast this spell on the same creature or object every day for 30 days, placing the same effect on it each time, the illusion lasts until it is dispelled.\",\n \"***False Aura.*** You change the way the target appears to spells and magical effects, such as detect magic, that detect magical auras. You can make a nonmagical object appear magical, a magical object appear nonmagical, or change the object's magical aura so that it appears to belong to a specific school of magic that you choose. When you use this effect on an object, you can make the false magic apparent to any creature that handles the item.\",\n \"***Mask.*** You change the way the target appears to spells and magical effects that detect creature types, such as a paladin's Divine Sense or the trigger of a symbol spell. You choose a creature type and other spells and magical effects treat the target as if it were a creature of that type or of that alignment.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small square of silk.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/arcanists-magic-aura\"\n },\n {\n \"index\": \"astral-projection\",\n \"name\": \"Astral Projection\",\n \"desc\": [\n \"You and up to eight willing creatures within range project your astral bodies into the Astral Plane (the spell fails and the casting is wasted if you are already on that plane). The material body you leave behind is unconscious and in a state of suspended animation; it doesn't need food or air and doesn't age.\",\n \"Your astral body resembles your mortal form in almost every way, replicating your game statistics and possessions. The principal difference is the addition of a silvery cord that extends from between your shoulder blades and trails behind you, fading to invisibility after 1 foot. This cord is your tether to your material body. As long as the tether remains intact, you can find your way home. If the cord is cut--something that can happen only when an effect specifically states that it does--your soul and body are separated, killing you instantly.\",\n \"Your astral form can freely travel through the Astral Plane and can pass through portals there leading to any other plane. If you enter a new plane or return to the plane you were on when casting this spell, your body and possessions are transported along the silver cord, allowing you to re-enter your body as you enter the new plane. Your astral form is a separate incarnation. Any damage or other effects that apply to it have no effect on your physical body, nor do they persist when you return to it.\",\n \"The spell ends for you and your companions when you use your action to dismiss it. When the spell ends, the affected creature returns to its physical body, and it awakens.\",\n \"The spell might also end early for you or one of your companions. A successful dispel magic spell used against an astral or physical body ends the spell for that creature. If a creature's original body or its astral form drops to 0 hit points, the spell ends for that creature. If the spell ends and the silver cord is intact, the cord pulls the creature's astral form back to its body, ending its state of suspended animation.\",\n \"If you are returned to your body prematurely, your companions remain in their astral forms and must find their own way back to their bodies, usually by dropping to 0 hit points.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"For each creature you affect with this spell, you must provide one jacinth worth at least 1,000gp and one ornately carved bar of silver worth at least 100gp, all of which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Special\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 9,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/astral-projection\"\n },\n {\n \"index\": \"augury\",\n \"name\": \"Augury\",\n \"desc\": [\n \"By casting gem-inlaid sticks, rolling dragon bones, laying out ornate cards, or employing some other divining tool, you receive an omen from an otherworldly entity about the results of a specific course of action that you plan to take within the next 30 minutes. The GM chooses from the following possible omens:\",\n \"- Weal, for good results\",\n \"- Woe, for bad results\",\n \"- Weal and woe, for both good and bad results\",\n \"- Nothing, for results that aren't especially good or bad\",\n \"The spell doesn't take into account any possible circumstances that might change the outcome, such as the casting of additional spells or the loss or gain of a companion.\",\n \"If you cast the spell two or more times before completing your next long rest, there is a cumulative 25 percent chance for each casting after the first that you get a random reading. The GM makes this roll in secret.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Specially marked sticks, bones, or similar tokens worth at least 25gp.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/augury\"\n },\n {\n \"index\": \"awaken\",\n \"name\": \"Awaken\",\n \"desc\": [\n \"After spending the casting time tracing magical pathways within a precious gemstone, you touch a Huge or smaller beast or plant. The target must have either no Intelligence score or an Intelligence of 3 or less. The target gains an Intelligence of 10. The target also gains the ability to speak one language you know. If the target is a plant, it gains the ability to move its limbs, roots, vines, creepers, and so forth, and it gains senses similar to a human's. Your GM chooses statistics appropriate for the awakened plant, such as the statistics for the awakened shrub or the awakened tree.\",\n \"The awakened beast or plant is charmed by you for 30 days or until you or your companions do anything harmful to it. When the charmed condition ends, the awakened creature chooses whether to remain friendly to you, based on how you treated it while it was charmed.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An agate worth at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"8 hours\",\n \"level\": 5,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/awaken\"\n },\n {\n \"index\": \"bane\",\n \"name\": \"Bane\",\n \"desc\": [\n \"Up to three creatures of your choice that you can see within range must make charisma saving throws. Whenever a target that fails this saving throw makes an attack roll or a saving throw before the spell ends, the target must roll a d4 and subtract the number rolled from the attack roll or saving throw.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can target one additional creature for each slot level above 1st.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of blood.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/bane\"\n },\n {\n \"index\": \"banishment\",\n \"name\": \"Banishment\",\n \"desc\": [\n \"You attempt to send one creature that you can see within range to another plane of existence. The target must succeed on a charisma saving throw or be banished.\",\n \"If the target is native to the plane of existence you're on, you banish the target to a harmless demiplane. While there, the target is incapacitated. The target remains there until the spell ends, at which point the target reappears in the space it left or in the nearest unoccupied space if that space is occupied.\",\n \"If the target is native to a different plane of existence than the one you're on, the target is banished with a faint popping noise, returning to its home plane. If the spell ends before 1 minute has passed, the target reappears in the space it left or in the nearest unoccupied space if that space is occupied. Otherwise, the target doesn't return.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, you can target one additional creature for each slot level above 4th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An item distasteful to the target.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/banishment\"\n },\n {\n \"index\": \"barkskin\",\n \"name\": \"Barkskin\",\n \"desc\": [\n \"You touch a willing creature. Until the spell ends, the target's skin has a rough, bark-like appearance, and the target's AC can't be less than 16, regardless of what kind of armor it is wearing.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A handful of oak bark.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/barkskin\"\n },\n {\n \"index\": \"beacon-of-hope\",\n \"name\": \"Beacon of Hope\",\n \"desc\": [\n \"This spell bestows hope and vitality. Choose any number of creatures within range. For the duration, each target has advantage on wisdom saving throws and death saving throws, and regains the maximum number of hit points possible from any healing.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/beacon-of-hope\"\n },\n {\n \"index\": \"bestow-curse\",\n \"name\": \"Bestow Curse\",\n \"desc\": [\n \"You touch a creature, and that creature must succeed on a wisdom saving throw or become cursed for the duration of the spell. When you cast this spell, choose the nature of the curse from the following options:\",\n \"- Choose one ability score. While cursed, the target has disadvantage on ability checks and saving throws made with that ability score.\",\n \"- While cursed, the target has disadvantage on attack rolls against you.\",\n \"- While cursed, the target must make a wisdom saving throw at the start of each of its turns. If it fails, it wastes its action that turn doing nothing.\",\n \"- While the target is cursed, your attacks and spells deal an extra 1d8 necrotic damage to the target.\",\n \"A remove curse spell ends this effect. At the GM's option, you may choose an alternative curse effect, but it should be no more powerful than those described above. The GM has final say on such a curse's effect.\"\n ],\n \"higher_level\": [\n \"If you cast this spell using a spell slot of 4th level or higher, the duration is concentration, up to 10 minutes. If you use a spell slot of 5th level or higher, the duration is 8 hours. If you use a spell slot of 7th level or higher, the duration is 24 hours. If you use a 9th level spell slot, the spell lasts until it is dispelled. Using a spell slot of 5th level or higher grants a duration that doesn't require concentration.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On fail, become cursed for the duration of the spell.\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/bestow-curse\"\n },\n {\n \"index\": \"black-tentacles\",\n \"name\": \"Black Tentacles\",\n \"desc\": [\n \"Squirming, ebony tentacles fill a 20-foot square on ground that you can see within range. For the duration, these tentacles turn the ground in the area into difficult terrain.\",\n \"When a creature enters the affected area for the first time on a turn or starts its turn there, the creature must succeed on a Dexterity saving throw or take 3d6 bludgeoning damage and be restrained by the tentacles until the spell ends. A creature that starts its turn in the area and is already restrained by the tentacles takes 3d6 bludgeoning damage.\",\n \"A creature restrained by the tentacles can use its action to make a Strength or Dexterity check (its choice) against your spell save DC. On a success, it frees itself.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of tentacle from a giant octopus or a giant squid\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"bludgeoning\",\n \"name\": \"Bludgeoning\",\n \"url\": \"/api/damage-types/bludgeoning\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"3d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"A creature restrained by the tentacles can use its action to make a Strength or Dexterity check (its choice) against your spell save DC. On a success, it frees itself.\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/black-tentacles\"\n },\n {\n \"index\": \"blade-barrier\",\n \"name\": \"Blade Barrier\",\n \"desc\": [\n \"You create a vertical wall of whirling, razor-sharp blades made of magical energy. The wall appears within range and lasts for the duration. You can make a straight wall up to 100 feet long, 20 feet high, and 5 feet thick, or a ringed wall up to 60 feet in diameter, 20 feet high, and 5 feet thick. The wall provides three-quarters cover to creatures behind it, and its space is difficult terrain.\",\n \"When a creature enters the wall's area for the first time on a turn or starts its turn there, the creature must make a dexterity saving throw. On a failed save, the creature takes 6d10 slashing damage. On a successful save, the creature takes half as much damage.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"slashing\",\n \"name\": \"Slashing\",\n \"url\": \"/api/damage-types/slashing\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"6d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/blade-barrier\"\n },\n {\n \"index\": \"bless\",\n \"name\": \"Bless\",\n \"desc\": [\n \"You bless up to three creatures of your choice within range. Whenever a target makes an attack roll or a saving throw before the spell ends, the target can roll a d4 and add the number rolled to the attack roll or saving throw.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can target one additional creature for each slot level above 1st.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sprinkling of holy water.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/bless\"\n },\n {\n \"index\": \"blight\",\n \"name\": \"Blight\",\n \"desc\": [\n \"Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a constitution saving throw. The target takes 8d8 necrotic damage on a failed save, or half as much damage on a successful one. The spell has no effect on undead or constructs.\",\n \"If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.\",\n \"If you target a nonmagical plant that isn't a creature, such as a tree or shrub, it doesn't make a saving throw; it simply withers and dies.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level of higher, the damage increases by 1d8 for each slot level above 4th.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"8d8\",\n \"5\": \"9d8\",\n \"6\": \"10d8\",\n \"7\": \"11d8\",\n \"8\": \"12d8\",\n \"9\": \"13d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/blight\"\n },\n {\n \"index\": \"blindness-deafness\",\n \"name\": \"Blindness/Deafness\",\n \"desc\": [\n \"You can blind or deafen a foe. Choose one creature that you can see within range to make a constitution saving throw. If it fails, the target is either blinded or deafened (your choice) for the duration. At the end of each of its turns, the target can make a constitution saving throw. On a success, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you can target one additional creature for each slot level above 2nd.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/blindness-deafness\"\n },\n {\n \"index\": \"blink\",\n \"name\": \"Blink\",\n \"desc\": [\n \"Roll a d20 at the end of each of your turns for the duration of the spell. On a roll of 11 or higher, you vanish from your current plane of existence and appear in the Ethereal Plane (the spell fails and the casting is wasted if you were already on that plane). At the start of your next turn, and when the spell ends if you are on the Ethereal Plane, you return to an unoccupied space of your choice that you can see within 10 feet of the space you vanished from. If no unoccupied space is available within that range, you appear in the nearest unoccupied space (chosen at random if more than one space is equally near). You can dismiss this spell as an action.\",\n \"While on the Ethereal Plane, you can see and hear the plane you originated from, which is cast in shades of gray, and you can't see anything there more than 60 feet away. You can only affect and be affected by other creatures on the Ethereal Plane. Creatures that aren't there can't perceive you or interact with you, unless they have the ability to do so.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/blink\"\n },\n {\n \"index\": \"blur\",\n \"name\": \"Blur\",\n \"desc\": [\n \"Your body becomes blurred, shifting and wavering to all who can see you. For the duration, any creature has disadvantage on attack rolls against you. An attacker is immune to this effect if it doesn't rely on sight, as with blindsight, or can see through illusions, as with truesight.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/blur\"\n },\n {\n \"index\": \"branding-smite\",\n \"name\": \"Branding Smite\",\n \"desc\": [\n \"The next time you hit a creature with a weapon attack before this spell ends, the weapon gleams with astral radiance as you strike. The attack deals an extra 2d6 radiant damage to the target, which becomes visible if it's invisible, and the target sheds dim light in a 5-foot radius and can't become invisible until the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the extra damage increases by 1d6 for each slot level above 2nd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d6\",\n \"3\": \"3d6\",\n \"4\": \"4d6\",\n \"5\": \"5d6\",\n \"6\": \"6d6\",\n \"7\": \"7d6\",\n \"8\": \"8d6\",\n \"9\": \"9d6\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/branding-smite\"\n },\n {\n \"index\": \"burning-hands\",\n \"name\": \"Burning Hands\",\n \"desc\": [\n \"As you hold your hands with thumbs touching and fingers spread, a thin sheet of flames shoots forth from your outstretched fingertips. Each creature in a 15-foot cone must make a dexterity saving throw. A creature takes 3d6 fire damage on a failed save, or half as much damage on a successful one.\",\n \"The fire ignites any flammable objects in the area that aren't being worn or carried.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d6 for each slot level above 1st.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"3d6\",\n \"2\": \"4d6\",\n \"3\": \"5d6\",\n \"4\": \"6d6\",\n \"5\": \"7d6\",\n \"6\": \"8d6\",\n \"7\": \"9d6\",\n \"8\": \"10d6\",\n \"9\": \"11d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/burning-hands\"\n },\n {\n \"index\": \"call-lightning\",\n \"name\": \"Call Lightning\",\n \"desc\": [\n \"A storm cloud appears in the shape of a cylinder that is 10 feet tall with a 60-foot radius, centered on a point you can see 100 feet directly above you. The spell fails if you can't see a point in the air where the storm cloud could appear (for example, if you are in a room that can't accommodate the cloud).\",\n \"When you cast the spell, choose a point you can see within range. A bolt of lightning flashes down from the cloud to that point. Each creature within 5 feet of that point must make a dexterity saving throw. A creature takes 3d10 lightning damage on a failed save, or half as much damage on a successful one. On each of your turns until the spell ends, you can use your action to call down lightning in this way again, targeting the same point or a different one.\",\n \"If you are outdoors in stormy conditions when you cast this spell, the spell gives you control over the existing storm instead of creating a new one. Under such conditions, the spell's damage increases by 1d10.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th or higher level, the damage increases by 1d10 for each slot level above 3rd.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"lightning\",\n \"name\": \"Lightning\",\n \"url\": \"/api/damage-types/lightning\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"3d10\",\n \"4\": \"4d10\",\n \"5\": \"5d10\",\n \"6\": \"6d10\",\n \"7\": \"7d10\",\n \"8\": \"8d10\",\n \"9\": \"9d10\"\n }\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/call-lightning\"\n },\n {\n \"index\": \"calm-emotions\",\n \"name\": \"Calm Emotions\",\n \"desc\": [\n \"You attempt to suppress strong emotions in a group of people. Each humanoid in a 20-foot-radius sphere centered on a point you choose within range must make a charisma saving throw; a creature can choose to fail this saving throw if it wishes. If a creature fails its saving throw, choose one of the following two effects. You can suppress any effect causing a target to be charmed or frightened. When this spell ends, any suppressed effect resumes, provided that its duration has not expired in the meantime.\",\n \"Alternatively, you can make a target indifferent about creatures of your choice that it is hostile toward. This indifference ends if the target is attacked or harmed by a spell or if it witnesses any of its friends being harmed. When the spell ends, the creature becomes hostile again, unless the GM rules otherwise.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/calm-emotions\"\n },\n {\n \"index\": \"chain-lightning\",\n \"name\": \"Chain Lightning\",\n \"desc\": [\n \"You create a bolt of lightning that arcs toward a target of your choice that you can see within range. Three bolts then leap from that target to as many as three other targets, each of which must be within 30 feet of the first target. A target can be a creature or an object and can be targeted by only one of the bolts.\",\n \"A target must make a dexterity saving throw. The target takes 10d8 lightning damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, one additional bolt leaps from the first target to another target for each slot level above 6th.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fur; a piece of amber, glass, or a crystal rod; and three silver pins.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"lightning\",\n \"name\": \"Lightning\",\n \"url\": \"/api/damage-types/lightning\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/chain-lightning\"\n },\n {\n \"index\": \"charm-person\",\n \"name\": \"Charm Person\",\n \"desc\": [\n \"You attempt to charm a humanoid you can see within range. It must make a wisdom saving throw, and does so with advantage if you or your companions are fighting it. If it fails the saving throw, it is charmed by you until the spell ends or until you or your companions do anything harmful to it. The charmed creature regards you as a friendly acquaintance. When the spell ends, the creature knows it was charmed by you.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can target one additional creature for each slot level above 1st. The creatures must be within 30 feet of each other when you target them.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/charm-person\"\n },\n {\n \"index\": \"chill-touch\",\n \"name\": \"Chill Touch\",\n \"desc\": [\n \"You create a ghostly, skeletal hand in the space of a creature within range. Make a ranged spell attack against the creature to assail it with the chill of the grave. On a hit, the target takes 1d8 necrotic damage, and it can't regain hit points until the start of your next turn. Until then, the hand clings to the target.\",\n \"If you hit an undead target, it also has disadvantage on attack rolls against you until the end of your next turn.\",\n \"This spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/chill-touch\"\n },\n {\n \"index\": \"circle-of-death\",\n \"name\": \"Circle of Death\",\n \"desc\": [\n \"A sphere of negative energy ripples out in a 60-foot radius sphere from a point within range. Each creature in that area must make a constitution saving throw. A target takes 8d6 necrotic damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the damage increases by 2d6 for each slot level above 6th.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"The powder of a crushed black pearl worth at least 500 gp.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"8d6\",\n \"7\": \"10d6\",\n \"8\": \"12d6\",\n \"9\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/circle-of-death\"\n },\n {\n \"index\": \"clairvoyance\",\n \"name\": \"Clairvoyance\",\n \"desc\": [\n \"You create an invisible sensor within range in a location familiar to you (a place you have visited or seen before) or in an obvious location that is unfamiliar to you (such as behind a door, around a corner, or in a grove of trees). The sensor remains in place for the duration, and it can't be attacked or otherwise interacted with.\",\n \"When you cast the spell, you choose seeing or hearing. You can use the chosen sense through the sensor as if you were in its space. As your action, you can switch between seeing and hearing.\",\n \"A creature that can see the sensor (such as a creature benefiting from see invisibility or truesight) sees a luminous, intangible orb about the size of your fist.\"\n ],\n \"range\": \"1 mile\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A focus worth at least 100gp, either a jeweled horn for hearing or a glass eye for seeing.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"10 minutes\",\n \"level\": 3,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/clairvoyance\"\n },\n {\n \"index\": \"clone\",\n \"name\": \"Clone\",\n \"desc\": [\n \"This spell grows an inert duplicate of a living creature as a safeguard against death. This clone forms inside a sealed vessel and grows to full size and maturity after 120 days; you can also choose to have the clone be a younger version of the same creature. It remains inert and endures indefinitely, as long as its vessel remains undisturbed.\",\n \"At any time after the clone matures, if the original creature dies, its soul transfers to the clone, provided that the soul is free and willing to return. The clone is physically identical to the original and has the same personality, memories, and abilities, but none of the original's equipment. The original creature's physical remains, if they still exist, become inert and can't thereafter be restored to life, since the creature's soul is elsewhere.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A diamond worth at least 1,000 gp and at least 1 cubic inch of flesh of the creature that is to be cloned, which the spell consumes, and a vessel worth at least 2,000 gp that has a sealable lid and is large enough to hold a Medium creature, such as a huge urn, coffin, mud-filled cyst in the ground, or crystal container filled with salt water.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 8,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/clone\"\n },\n {\n \"index\": \"cloudkill\",\n \"name\": \"Cloudkill\",\n \"desc\": [\n \"You create a 20-foot-radius sphere of poisonous, yellow-green fog centered on a point you choose within range. The fog spreads around corners. It lasts for the duration or until strong wind disperses the fog, ending the spell. Its area is heavily obscured.\",\n \"When a creature enters the spell's area for the first time on a turn or starts its turn there, that creature must make a constitution saving throw. The creature takes 5d8 poison damage on a failed save, or half as much damage on a successful one. Creatures are affected even if they hold their breath or don't need to breathe.\",\n \"The fog moves 10 feet away from you at the start of each of your turns, rolling along the surface of the ground. The vapors, being heavier than air, sink to the lowest level of the land, even pouring down openings.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the damage increases by 1d8 for each slot level above 5th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"poison\",\n \"name\": \"Poison\",\n \"url\": \"/api/damage-types/poison\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"5d8\",\n \"6\": \"6d8\",\n \"7\": \"7d8\",\n \"8\": \"8d8\",\n \"9\": \"9d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\",\n \"desc\": \"Creatures are affected even if they hold their breath or don't need to breathe.\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/cloudkill\"\n },\n {\n \"index\": \"color-spray\",\n \"name\": \"Color Spray\",\n \"desc\": [\n \"A dazzling array of flashing, colored light springs from your hand. Roll 6d10; the total is how many hit points of creatures this spell can effect. Creatures in a 15-foot cone originating from you are affected in ascending order of their current hit points (ignoring unconscious creatures and creatures that can't see).\",\n \"Starting with the creature that has the lowest current hit points, each creature affected by this spell is blinded until the spell ends. Subtract each creature's hit points from the total before moving on to the creature with the next lowest hit points. A creature's hit points must be equal to or less than the remaining total for that creature to be affected.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, roll an additional 2d10 for each slot level above 1st.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of powder or sand that is colored red, yellow, and blue.\",\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/color-spray\"\n },\n {\n \"index\": \"command\",\n \"name\": \"Command\",\n \"desc\": [\n \"You speak a one-word command to a creature you can see within range. The target must succeed on a wisdom saving throw or follow the command on its next turn. The spell has no effect if the target is undead, if it doesn't understand your language, or if your command is directly harmful to it.\",\n \"Some typical commands and their effects follow. You might issue a command other than one described here. If you do so, the GM determines how the target behaves. If the target can't follow your command, the spell ends.\",\n \"***Approach.*** The target moves toward you by the shortest and most direct route, ending its turn if it moves within 5 feet of you.\",\n \"***Drop.*** The target drops whatever it is holding and then ends its turn.\",\n \"***Flee.*** The target spends its turn moving away from you by the fastest available means.\",\n \"***Grovel.*** The target falls prone and then ends its turn.\",\n \"***Halt.*** The target doesn't move and takes no actions. A flying creature stays aloft, provided that it is able to do so. If it must move to stay aloft, it flies the minimum distance needed to remain in the air.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can affect one additional creature for each slot level above 1st. The creatures must be within 30 feet of each other when you target them.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/command\"\n },\n {\n \"index\": \"commune\",\n \"name\": \"Commune\",\n \"desc\": [\n \"You contact your deity or a divine proxy and ask up to three questions that can be answered with a yes or no. You must ask your questions before the spell ends. You receive a correct answer for each question.\",\n \"Divine beings aren't necessarily omniscient, so you might receive \\\"unclear\\\" as an answer if a question pertains to information that lies beyond the deity's knowledge. In a case where a one-word answer could be misleading or contrary to the deity's interests, the GM might offer a short phrase as an answer instead.\",\n \"If you cast the spell two or more times before finishing your next long rest, there is a cumulative 25 percent chance for each casting after the first that you get no answer. The GM makes this roll in secret.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Incense and a vial of holy or unholy water.\",\n \"ritual\": true,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/commune\"\n },\n {\n \"index\": \"commune-with-nature\",\n \"name\": \"Commune With Nature\",\n \"desc\": [\n \"You briefly become one with nature and gain knowledge of the surrounding territory. In the outdoors, the spell gives you knowledge of the land within 3 miles of you. In caves and other natural underground settings, the radius is limited to 300 feet. The spell doesn't function where nature has been replaced by construction, such as in dungeons and towns.\",\n \"You instantly gain knowledge of up to three facts of your choice about any of the following subjects as they relate to the area:\",\n \"- terrain and bodies of water\",\n \"- prevalent plants, minerals, animals, or peoples\",\n \"- powerful celestials, fey, fiends, elementals, or undead\",\n \"- influence from other planes of existence\",\n \"- buildings\",\n \"For example, you could determine the location of powerful undead in the area, the location of major sources of safe drinking water, and the location of any nearby towns.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/commune-with-nature\"\n },\n {\n \"index\": \"comprehend-languages\",\n \"name\": \"Comprehend Languages\",\n \"desc\": [\n \"For the duration, you understand the literal meaning of any spoken language that you hear. You also understand any written language that you see, but you must be touching the surface on which the words are written. It takes about 1 minute to read one page of text.\",\n \"This spell doesn't decode secret messages in a text or a glyph, such as an arcane sigil, that isn't part of a written language.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of soot and salt.\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/comprehend-languages\"\n },\n {\n \"index\": \"compulsion\",\n \"name\": \"Compulsion\",\n \"desc\": [\n \"Creatures of your choice that you can see within range and that can hear you must make a wisdom saving throw. A target automatically succeeds on this saving throw if it can't be charmed. On a failed save, a target is affected by this spell. Until the spell ends, you can use a bonus action on each of your turns to designate a direction that is horizontal to you. Each affected target must use as much of its movement as possible to move in that direction on its next turn. It can take any action before it moves. After moving in this way, it can make another Wisdom save to try to end the effect.\",\n \"A target isn't compelled to move into an obviously deadly hazard, such as a fire or a pit, but it will provoke opportunity attacks to move in the designated direction.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/compulsion\"\n },\n {\n \"index\": \"cone-of-cold\",\n \"name\": \"Cone of Cold\",\n \"desc\": [\n \"A blast of cold air erupts from your hands. Each creature in a 60-foot cone must make a constitution saving throw. A creature takes 8d8 cold damage on a failed save, or half as much damage on a successful one.\",\n \"A creature killed by this spell becomes a frozen statue until it thaws.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the damage increases by 1d8 for each slot level above 5th.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small crystal or glass cone.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"cold\",\n \"name\": \"Cold\",\n \"url\": \"/api/damage-types/cold\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"8d8\",\n \"6\": \"9d8\",\n \"7\": \"10d8\",\n \"8\": \"11d8\",\n \"9\": \"12d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\",\n \"desc\": \"A creature killed by this spell becomes a frozen statue until it thaws.\"\n },\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/cone-of-cold\"\n },\n {\n \"index\": \"confusion\",\n \"name\": \"Confusion\",\n \"desc\": [\n \"This spell assaults and twists creatures' minds, spawning delusions and provoking uncontrolled action. Each creature in a 10-foot-radius sphere centered on a point you choose within range must succeed on a Wisdom saving throw when you cast this spell or be affected by it.\",\n \"An affected target can't take reactions and must roll a d10 at the start of each of its turns to determine its behavior for that turn.\",\n \"| d10 | Behavior |\",\n \"|---|---|\",\n \"| 1 | The creature uses all its movement to move in a random direction. To determine the direction, roll a d8 and assign a direction to each die face. The creature doesn't take an action this turn. |\",\n \"| 2-6 | The creature doesn't move or take actions this turn. |\",\n \"| 7-8 | The creature uses its action to make a melee attack against a randomly determined creature within its reach. If there is no creature within its reach, the creature does nothing this turn. |\",\n \"| 9-10 | The creature can act and move normally. |\",\n \"At the end of each of its turns, an affected target can make a Wisdom saving throw. If it succeeds, this effect ends for that target.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, the radius of the sphere increases by 5 feet for each slot level above 4th.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Three walnut shells.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/confusion\"\n },\n {\n \"index\": \"conjure-animals\",\n \"name\": \"Conjure Animals\",\n \"desc\": [\n \"You summon fey spirits that take the form of beasts and appear in unoccupied spaces that you can see within range. Choose one of the following options for what appears:\",\n \"- One beast of challenge rating 2 or lower\",\n \"- Two beasts of challenge rating 1 or lower\",\n \"- Four beasts of challenge rating 1/2 or lower\",\n \"- Eight beasts of challenge rating 1/4 or lower\",\n \"- Each beast is also considered fey, and it disappears when it drops to 0 hit points or when the spell ends.\",\n \"The summoned creatures are friendly to you and your companions. Roll initiative for the summoned creatures as a group, which has its own turns. They obey any verbal commands that you issue to them (no action required by you). If you don't issue any commands to them, they defend themselves from hostile creatures, but otherwise take no actions.\",\n \"The GM has the creatures' statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using certain higher-level spell slots, you choose one of the summoning options above, and more creatures appear: twice as many with a 5th-level slot, three times as many with a 7th-level.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/conjure-animals\"\n },\n {\n \"index\": \"conjure-celestial\",\n \"name\": \"Conjure Celestial\",\n \"desc\": [\n \"You summon a celestial of challenge rating 4 or lower, which appears in an unoccupied space that you can see within range. The celestial disappears when it drops to 0 hit points or when the spell ends.\",\n \"The celestial is friendly to you and your companions for the duration. Roll initiative for the celestial, which has its own turns. It obeys any verbal commands that you issue to it (no action required by you), as long as they don't violate its alignment. If you don't issue any commands to the celestial, it defends itself from hostile creatures but otherwise takes no actions.\",\n \"The GM has the celestial's statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 9th-level spell slot, you summon a celestial of challenge rating 5 or lower.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 7,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/conjure-celestial\"\n },\n {\n \"index\": \"conjure-elemental\",\n \"name\": \"Conjure Elemental\",\n \"desc\": [\n \"You call forth an elemental servant. Choose an area of air, earth, fire, or water that fills a 10-foot cube within range. An elemental of challenge rating 5 or lower appropriate to the area you chose appears in an unoccupied space within 10 feet of it. For example, a fire elemental emerges from a bonfire, and an earth elemental rises up from the ground. The elemental disappears when it drops to 0 hit points or when the spell ends.\",\n \"The elemental is friendly to you and your companions for the duration. Roll initiative for the elemental, which has its own turns. It obeys any verbal commands that you issue to it (no action required by you). If you don't issue any commands to the elemental, it defends itself from hostile creatures but otherwise takes no actions.\",\n \"If your concentration is broken, the elemental doesn't disappear. Instead, you lose control of the elemental, it becomes hostile toward you and your companions, and it might attack. An uncontrolled elemental can't be dismissed by you, and it disappears 1 hour after you summoned it.\",\n \"The GM has the elemental's statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the challenge rating increases by 1 for each slot level above 5th.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Burning incense for air, soft clay for earth, sulfur and phosphorus for fire, or water and sand for water.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/conjure-elemental\"\n },\n {\n \"index\": \"conjure-fey\",\n \"name\": \"Conjure Fey\",\n \"desc\": [\n \"You summon a fey creature of challenge rating 6 or lower, or a fey spirit that takes the form of a beast of challenge rating 6 or lower. It appears in an unoccupied space that you can see within range. The fey creature disappears when it drops to 0 hit points or when the spell ends.\",\n \"The fey creature is friendly to you and your companions for the duration. Roll initiative for the creature, which has its own turns. It obeys any verbal commands that you issue to it (no action required by you), as long as they don't violate its alignment. If you don't issue any commands to the fey creature, it defends itself from hostile creatures but otherwise takes no actions.\",\n \"If your concentration is broken, the fey creature doesn't disappear. Instead, you lose control of the fey creature, it becomes hostile toward you and your companions, and it might attack. An uncontrolled fey creature can't be dismissed by you, and it disappears 1 hour after you summoned it.\",\n \"The GM has the fey creature's statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the challenge rating increases by 1 for each slot level above 6th.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/conjure-fey\"\n },\n {\n \"index\": \"conjure-minor-elementals\",\n \"name\": \"Conjure Minor Elementals\",\n \"desc\": [\n \"You summon elementals that appear in unoccupied spaces that you can see within range. You choose one the following options for what appears:\",\n \"- One elemental of challenge rating 2 or lower\",\n \"- Two elementals of challenge rating 1 or lower\",\n \"- Four elementals of challenge rating 1/2 or lower\",\n \"- Eight elementals of challenge rating 1/4 or lower.\",\n \"An elemental summoned by this spell disappears when it drops to 0 hit points or when the spell ends.\",\n \"The summoned creatures are friendly to you and your companions. Roll initiative for the summoned creatures as a group, which has its own turns. They obey any verbal commands that you issue to them (no action required by you). If you don't issue any commands to them, they defend themselves from hostile creatures, but otherwise take no actions.\",\n \"The GM has the creatures' statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using certain higher-level spell slots, you choose one of the summoning options above, and more creatures appear: twice as many with a 6th-level slot and three times as many with an 8th-level slot.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 4,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/conjure-minor-elementals\"\n },\n {\n \"index\": \"conjure-woodland-beings\",\n \"name\": \"Conjure Woodland Beings\",\n \"desc\": [\n \"You summon fey creatures that appear in unoccupied spaces that you can see within range. Choose one of the following options for what appears:\",\n \"- One fey creature of challenge rating 2 or lower\",\n \"- Two fey creatures of challenge rating 1 or lower\",\n \"- Four fey creatures of challenge rating 1/2 or lower\",\n \"- Eight fey creatures of challenge rating 1/4 or lower\",\n \"A summoned creature disappears when it drops to 0 hit points or when the spell ends.\",\n \"The summoned creatures are friendly to you and your companions. Roll initiative for the summoned creatures as a group, which have their own turns. They obey any verbal commands that you issue to them (no action required by you). If you don't issue any commands to them, they defend themselves from hostile creatures, but otherwise take no actions.\",\n \"The GM has the creatures' statistics.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using certain higher-level spell slots, you choose one of the summoning options above, and more creatures appear: twice as many with a 6th-level slot and three times as many with an 8th-level slot.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"One holly berry per creature summoned.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/conjure-woodland-beings\"\n },\n {\n \"index\": \"contact-other-plane\",\n \"name\": \"Contact Other Plane\",\n \"desc\": [\n \"You mentally contact a demigod, the spirit of a long-dead sage, or some other mysterious entity from another plane. Contacting this extraplanar intelligence can strain or even break your mind. When you cast this spell, make a DC 15 intelligence saving throw. On a failure, you take 6d6 psychic damage and are insane until you finish a long rest. While insane, you can't take actions, can't understand what other creatures say, can't read, and speak only in gibberish. A greater restoration spell cast on you ends this effect.\",\n \"On a successful save, you can ask the entity up to five questions. You must ask your questions before the spell ends. The GM answers each question with one word, such as \\\"yes,\\\" \\\"no,\\\" \\\"maybe,\\\" \\\"never,\\\" \\\"irrelevant,\\\" or \\\"unclear\\\" (if the entity doesn't know the answer to the question). If a one-word answer would be misleading, the GM might instead offer a short phrase as an answer.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": true,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"int\",\n \"name\": \"INT\",\n \"url\": \"/api/ability-scores/int\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"On a failure, you take 6d6 psychic damage and are insane until you finish a long rest.\"\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/contact-other-plane\"\n },\n {\n \"index\": \"contagion\",\n \"name\": \"Contagion\",\n \"desc\": [\n \"Your touch inflicts disease. Make a melee spell attack against a creature within your reach. On a hit, you afflict the creature with a disease of your choice from any of the ones described below.\",\n \"At the end of each of the target's turns, it must make a constitution saving throw. After failing three of these saving throws, the disease's effects last for the duration, and the creature stops making these saves. After succeeding on three of these saving throws, the creature recovers from the disease, and the spell ends.\",\n \"Since this spell induces a natural disease in its target, any effect that removes a disease or otherwise ameliorates a disease's effects apply to it.\",\n \"***Blinding Sickness.*** Pain grips the creature's mind, and its eyes turn milky white. The creature has disadvantage on wisdom checks and wisdom saving throws and is blinded.\",\n \"***Filth Fever.*** A raging fever sweeps through the creature's body. The creature has disadvantage on strength checks, strength saving throws, and attack rolls that use Strength.\",\n \"***Flesh Rot.*** The creature's flesh decays. The creature has disadvantage on Charisma checks and vulnerability to all damage.\",\n \"***Mindfire.*** The creature's mind becomes feverish. The creature has disadvantage on intelligence checks and intelligence saving throws, and the creature behaves as if under the effects of the confusion spell during combat.\",\n \"***Seizure.*** The creature is overcome with shaking. The creature has disadvantage on dexterity checks, dexterity saving throws, and attack rolls that use Dexterity.\",\n \"***Slimy Doom.*** The creature begins to bleed uncontrollably. The creature has disadvantage on constitution checks and constitution saving throws. In addition, whenever the creature takes damage, it is stunned until the end of its next turn.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"7 days\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"attack_type\": \"melee\",\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"After succeeding on three of these saving throws, the creature recovers from the disease, and the spell ends.\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/contagion\"\n },\n {\n \"index\": \"contingency\",\n \"name\": \"Contingency\",\n \"desc\": [\n \"Choose a spell of 5th level or lower that you can cast, that has a casting time of 1 action, and that can target you. You cast that spell--called the contingent spell--as part of casting contingency, expending spell slots for both, but the contingent spell doesn't come into effect. Instead, it takes effect when a certain circumstance occurs. You describe that circumstance when you cast the two spells. For example, a contingency cast with water breathing might stipulate that water breathing comes into effect when you are engulfed in water or a similar liquid.\",\n \"The contingent spell takes effect immediately after the circumstance is met for the first time, whether or not you want it to. and then contingency ends.\",\n \"The contingent spell takes effect only on you, even if it can normally target others. You can use only one contingency spell at a time. If you cast this spell again, the effect of another contingency spell on you ends. Also, contingency ends on you if its material component is ever not on your person.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A statuette of yourself carved from ivory and decorated with gems worth at least 1,500 gp.\",\n \"ritual\": false,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/contingency\"\n },\n {\n \"index\": \"continual-flame\",\n \"name\": \"Continual Flame\",\n \"desc\": [\n \"A flame, equivalent in brightness to a torch, springs forth from an object that you touch. The effect looks like a regular flame, but it creates no heat and doesn't use oxygen. A continual flame can be covered or hidden but not smothered or quenched.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Ruby dust worth 50 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/continual-flame\"\n },\n {\n \"index\": \"control-water\",\n \"name\": \"Control Water\",\n \"desc\": [\n \"Until the spell ends, you control any freestanding water inside an area you choose that is a cube up to 100 feet on a side. You can choose from any of the following effects when you cast this spell. As an action on your turn, you can repeat the same effect or choose a different one.\",\n \"***Flood.*** You cause the water level of all standing water in the area to rise by as much as 20 feet. If the area includes a shore, the flooding water spills over onto dry land.\",\n \"If you choose an area in a large body of water, you instead create a 20-foot tall wave that travels from one side of the area to the other and then crashes down. Any Huge or smaller vehicles in the wave's path are carried with it to the other side. Any Huge or smaller vehicles struck by the wave have a 25 percent chance of capsizing.\",\n \"The water level remains elevated until the spell ends or you choose a different effect. If this effect produced a wave, the wave repeats on the start of your next turn while the flood effect lasts.\",\n \"***Part Water.*** You cause water in the area to move apart and create a trench. The trench extends across the spell's area, and the separated water forms a wall to either side. The trench remains until the spell ends or you choose a different effect. The water then slowly fills in the trench over the course of the next round until the normal water level is restored.\",\n \"***Redirect Flow.*** You cause flowing water in the area to move in a direction you choose, even if the water has to flow over obstacles, up walls, or in other unlikely directions. The water in the area moves as you direct it, but once it moves beyond the spell's area, it resumes its flow based on the terrain conditions. The water continues to move in the direction you chose until the spell ends or you choose a different effect.\",\n \"***Whirlpool.*** This effect requires a body of water at least 50 feet square and 25 feet deep. You cause a whirlpool to form in the center of the area. The whirlpool forms a vortex that is 5 feet wide at the base, up to 50 feet wide at the top, and 25 feet tall. Any creature or object in the water and within 25 feet of the vortex is pulled 10 feet toward it. A creature can swim away from the vortex by making a Strength (Athletics) check against your spell save DC.\",\n \"When a creature enters the vortex for the first time on a turn or starts its turn there, it must make a strength saving throw. On a failed save, the creature takes 2d8 bludgeoning damage and is caught in the vortex until the spell ends. On a successful save, the creature takes half damage, and isn't caught in the vortex. A creature caught in the vortex can use its action to try to swim away from the vortex as described above, but has disadvantage on the Strength (Athletics) check to do so.\",\n \"The first time each turn that an object enters the vortex, the object takes 2d8 bludgeoning damage; this damage occurs each round it remains in the vortex.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of water and a pinch of dust.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"bludgeoning\",\n \"name\": \"Bludgeoning\",\n \"url\": \"/api/damage-types/bludgeoning\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"2d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"str\",\n \"name\": \"STR\",\n \"url\": \"/api/ability-scores/str\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/control-water\"\n },\n {\n \"index\": \"control-weather\",\n \"name\": \"Control Weather\",\n \"desc\": [\n \"You take control of the weather within 5 miles of you for the duration. You must be outdoors to cast this spell. Moving to a place where you don't have a clear path to the sky ends the spell early.\",\n \"When you cast the spell, you change the current weather conditions, which are determined by the GM based on the climate and season. You can change precipitation, temperature, and wind. It takes 1d4 x 10 minutes for the new conditions to take effect. Once they do so, you can change the conditions again. When the spell ends, the weather gradually returns to normal.\",\n \"When you change the weather conditions, find a current condition on the following tables and change its stage by one, up or down. When changing the wind, you can change its direction.\",\n \"##### Precipitation\",\n \"| Stage | Condition |\",\n \"|---|---|\",\n \"| 1 | Clear |\",\n \"| 2 | Light clouds |\",\n \"| 3 | Overcast or ground fog |\",\n \"| 4 | Rain, hail, or snow |\",\n \"| 5 | Torrential rain, driving hail, or blizzard |\",\n \"##### Temperature\",\n \"| Stage | Condition |\",\n \"|---|---|\",\n \"| 1 | Unbearable heat |\",\n \"| 2 | Hot |\",\n \"| 3 | Warm |\",\n \"| 4 | Cool |\",\n \"| 5 | Cold |\",\n \"| 6 | Arctic cold |\",\n \"##### Wind\",\n \"| Stage | Condition |\",\n \"|---|---|\",\n \"| 1 | Calm |\",\n \"| 2 | Moderate wind |\",\n \"| 3 | Strong wind |\",\n \"| 4 | Gale |\",\n \"| 5 | Storm |\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Burning incense and bits of earth and wood mixed in water.\",\n \"ritual\": false,\n \"duration\": \"Up to 8 hours\",\n \"concentration\": true,\n \"casting_time\": \"10 minutes\",\n \"level\": 8,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/control-weather\"\n },\n {\n \"index\": \"counterspell\",\n \"name\": \"Counterspell\",\n \"desc\": [\n \"You attempt to interrupt a creature in the process of casting a spell. If the creature is casting a spell of 3rd level or lower, its spell fails and has no effect. If it is casting a spell of 4th level or higher, make an ability check using your spellcasting ability. The DC equals 10 + the spell's level. On a success, the creature's spell fails and has no effect.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the interrupted spell has no effect if its level is less than or equal to the level of the spell slot you used.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 reaction\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/counterspell\"\n },\n {\n \"index\": \"create-food-and-water\",\n \"name\": \"Create Food and Water\",\n \"desc\": [\n \"You create 45 pounds of food and 30 gallons of water on the ground or in containers within range, enough to sustain up to fifteen humanoids or five steeds for 24 hours. The food is bland but nourishing, and spoils if uneaten after 24 hours. The water is clean and doesn't go bad.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/create-food-and-water\"\n },\n {\n \"index\": \"create-undead\",\n \"name\": \"Create Undead\",\n \"desc\": [\n \"You can cast this spell only at night. Choose up to three corpses of Medium or Small humanoids within range. Each corpse becomes a ghoul under your control. (The GM has game statistics for these creatures.)\",\n \"As a bonus action on each of your turns, you can mentally command any creature you animated with this spell if the creature is within 120 feet of you (if you control multiple creatures, you can command any or all of them at the same time, issuing the same command to each one). You decide what action the creature will take and where it will move during its next turn, or you can issue a general command, such as to guard a particular chamber or corridor. If you issue no commands, the creature only defends itself against hostile creatures. Once given an order, the creature continues to follow it until its task is complete.\",\n \"The creature is under your control for 24 hours, after which it stops obeying any command you have given it. To maintain control of the creature for another 24 hours, you must cast this spell on the creature before the current 24-hour period ends. This use of the spell reasserts your control over up to three creatures you have animated with this spell, rather than animating new ones.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 7th-level spell slot, you can animate or reassert control over four ghouls. When you cast this spell using an 8th-level spell slot, you can animate or reassert control over five ghouls or two ghasts or wights. When you cast this spell using a 9th-level spell slot, you can animate or reassert control over six ghouls, three ghasts or wights, or two mummies.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"One clay pot filled with grave dirt, one clay pot filled with brackish water, and one 150 gp black onyx stone for each corpse.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/create-undead\"\n },\n {\n \"index\": \"create-or-destroy-water\",\n \"name\": \"Create or Destroy Water\",\n \"desc\": [\n \"You either create or destroy water.\",\n \"***Create Water.*** You create up to 10 gallons of clean water within range in an open container. Alternatively, the water falls as rain in a 30-foot cube within range.\",\n \"***Destroy Water.*** You destroy up to 10 gallons of water in an open container within range. Alternatively, you destroy fog in a 30-foot cube within range.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you create or destroy 10 additional gallons of water, or the size of the cube increases by 5 feet, for each slot level above 1st.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of water if creating water, or a few grains of sand if destroying it.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/create-or-destroy-water\"\n },\n {\n \"index\": \"creation\",\n \"name\": \"Creation\",\n \"desc\": [\n \"You pull wisps of shadow material from the Shadowfell to create a nonliving object of vegetable matter within range: soft goods, rope, wood, or something similar. You can also use this spell to create mineral objects such as stone, crystal, or metal. The object created must be no larger than a 5-foot cube, and the object must be of a form and material that you have seen before.\",\n \"The duration depends on the object's material. If the object is composed of multiple materials, use the shortest duration.\",\n \"| Material | Duration |\",\n \"|---|---|\",\n \"| Vegetable matter | 1 day |\",\n \"| Stone or crystal | 12 hours |\",\n \"| Precious metals | 1 hour |\",\n \"| Gems | 10 minutes |\",\n \"| Adamantine or mithral | 1 minute |\",\n \"Using any material created by this spell as another spell's material component causes that spell to fail.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the cube increases by 5 feet for each slot level above 5th.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny piece of matter of the same type of the item you plan to create.\",\n \"ritual\": false,\n \"duration\": \"Special\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/creation\"\n },\n {\n \"index\": \"cure-wounds\",\n \"name\": \"Cure Wounds\",\n \"desc\": [\n \"A creature you touch regains a number of hit points equal to 1d8 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the healing increases by 1d8 for each slot level above 1st.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"heal_at_slot_level\": {\n \"1\": \"1d8 + MOD\",\n \"2\": \"2d8 + MOD\",\n \"3\": \"3d8 + MOD\",\n \"4\": \"4d8 + MOD\",\n \"5\": \"5d8 + MOD\",\n \"6\": \"6d8 + MOD\",\n \"7\": \"7d8 + MOD\",\n \"8\": \"8d8 + MOD\",\n \"9\": \"9d8 + MOD\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/cure-wounds\"\n },\n {\n \"index\": \"dancing-lights\",\n \"name\": \"Dancing Lights\",\n \"desc\": [\n \"You create up to four torch-sized lights within range, making them appear as torches, lanterns, or glowing orbs that hover in the air for the duration. You can also combine the four lights into one glowing vaguely humanoid form of Medium size. Whichever form you choose, each light sheds dim light in a 10-foot radius.\",\n \"As a bonus action on your turn, you can move the lights up to 60 feet to a new spot within range. A light must be within 20 feet of another light created by this spell, and a light winks out if it exceeds the spell's range.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of phosphorus or wychwood, or a glowworm.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/dancing-lights\"\n },\n {\n \"index\": \"darkness\",\n \"name\": \"Darkness\",\n \"desc\": [\n \"Magical darkness spreads from a point you choose within range to fill a 15-foot-radius sphere for the duration. The darkness spreads around corners. A creature with darkvision can't see through this darkness, and nonmagical light can't illuminate it.\",\n \"If the point you choose is on an object you are holding or one that isn't being worn or carried, the darkness emanates from the object and moves with it. Completely covering the source of the darkness with an opaque object, such as a bowl or a helm, blocks the darkness.\",\n \"If any of this spell's area overlaps with an area of light created by a spell of 2nd level or lower, the spell that created the light is dispelled.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"Bat fur and a drop of pitch or piece of coal.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/darkness\"\n },\n {\n \"index\": \"darkvision\",\n \"name\": \"Darkvision\",\n \"desc\": [\n \"You touch a willing creature to grant it the ability to see in the dark. For the duration, that creature has darkvision out to a range of 60 feet.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Either a pinch of dried carrot or an agate.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/darkvision\"\n },\n {\n \"index\": \"daylight\",\n \"name\": \"Daylight\",\n \"desc\": [\n \"A 60-foot-radius sphere of light spreads out from a point you choose within range. The sphere is bright light and sheds dim light for an additional 60 feet.\",\n \"If you chose a point on an object you are holding or one that isn't being worn or carried, the light shines from the object and moves with it. Completely covering the affected object with an opaque object, such as a bowl or a helm, blocks the light.\",\n \"If any of this spell's area overlaps with an area of darkness created by a spell of 3rd level or lower, the spell that created the darkness is dispelled.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/daylight\"\n },\n {\n \"index\": \"death-ward\",\n \"name\": \"Death Ward\",\n \"desc\": [\n \"You touch a creature and grant it a measure of protection from death.\",\n \"The first time the target would drop to 0 hit points as a result of taking damage, the target instead drops to 1 hit point, and the spell ends.\",\n \"If the spell is still in effect when the target is subjected to an effect that would kill it instantaneously without dealing damage, that effect is instead negated against the target, and the spell ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/death-ward\"\n },\n {\n \"index\": \"delayed-blast-fireball\",\n \"name\": \"Delayed Blast Fireball\",\n \"desc\": [\n \"A beam of yellow light flashes from your pointing finger, then condenses to linger at a chosen point within range as a glowing bead for the duration. When the spell ends, either because your concentration is broken or because you decide to end it, the bead blossoms with a low roar into an explosion of flame that spreads around corners. Each creature in a 20-foot-radius sphere centered on that point must make a dexterity saving throw. A creature takes fire damage equal to the total accumulated damage on a failed save, or half as much damage on a successful one.\",\n \"The spell's base damage is 12d6. If at the end of your turn the bead has not yet detonated, the damage increases by 1d6.\",\n \"If the glowing bead is touched before the interval has expired, the creature touching it must make a dexterity saving throw. On a failed save, the spell ends immediately, causing the bead to erupt in flame. On a successful save, the creature can throw the bead up to 40 feet. When it strikes a creature or a solid object, the spell ends, and the bead explodes.\",\n \"The fire damages objects in the area and ignites flammable objects that aren't being worn or carried.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 8th level or higher, the base damage increases by 1d6 for each slot level above 7th.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny ball of bat guano and sulfur.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"7\": \"12d6\",\n \"8\": \"13d6\",\n \"9\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/delayed-blast-fireball\"\n },\n {\n \"index\": \"demiplane\",\n \"name\": \"Demiplane\",\n \"desc\": [\n \"You create a shadowy door on a flat solid surface that you can see within range. The door is large enough to allow Medium creatures to pass through unhindered. When opened, the door leads to a demiplane that appears to be an empty room 30 feet in each dimension, made of wood or stone. When the spell ends, the door disappears, and any creatures or objects inside the demiplane remain trapped there, as the door also disappears from the other side.\",\n \"Each time you cast this spell, you can create a new demiplane, or have the shadowy door connect to a demiplane you created with a previous casting of this spell. Additionally, if you know the nature and contents of a demiplane created by a casting of this spell by another creature, you can have the shadowy door connect to its demiplane instead.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/demiplane\"\n },\n {\n \"index\": \"detect-evil-and-good\",\n \"name\": \"Detect Evil and Good\",\n \"desc\": [\n \"For the duration, you know if there is an aberration, celestial, elemental, fey, fiend, or undead within 30 feet of you, as well as where the creature is located. Similarly, you know if there is a place or object within 30 feet of you that has been magically consecrated or desecrated.\",\n \"The spell can penetrate most barriers, but it is blocked by 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/detect-evil-and-good\"\n },\n {\n \"index\": \"detect-magic\",\n \"name\": \"Detect Magic\",\n \"desc\": [\n \"For the duration, you sense the presence of magic within 30 feet of you. If you sense magic in this way, you can use your action to see a faint aura around any visible creature or object in the area that bears magic, and you learn its school of magic, if any.\",\n \"The spell can penetrate most barriers, but it is blocked by 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/detect-magic\"\n },\n {\n \"index\": \"detect-poison-and-disease\",\n \"name\": \"Detect Poison and Disease\",\n \"desc\": [\n \"For the duration, you can sense the presence and location of poisons, poisonous creatures, and diseases within 30 feet of you. You also identify the kind of poison, poisonous creature, or disease in each case.\",\n \"The spell can penetrate most barriers, but it is blocked by 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood or dirt.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A yew leaf.\",\n \"ritual\": true,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/detect-poison-and-disease\"\n },\n {\n \"index\": \"detect-thoughts\",\n \"name\": \"Detect Thoughts\",\n \"desc\": [\n \"For the duration, you can read the thoughts of certain creatures. When you cast the spell and as your action on each turn until the spell ends, you can focus your mind on any one creature that you can see within 30 feet of you. If the creature you choose has an Intelligence of 3 or lower or doesn't speak any language, the creature is unaffected.\",\n \"You initially learn the surface thoughts of the creature - what is most on its mind in that moment. As an action, you can either shift your attention to another creature's thoughts or attempt to probe deeper into the same creature's mind. If you probe deeper, the target must make a Wisdom saving throw. If it fails, you gain insight into its reasoning (if any), its emotional state, and something that looms large in its mind (such as something it worries over, loves, or hates). If it succeeds, the spell ends. Either way, the target knows that you are probing into its mind, and unless you shift your attention to another creature's thoughts, the creature can use its action on its turn to make an Intelligence check contested by your Intelligence check; if it succeeds, the spell ends.\",\n \"Questions verbally directed at the target creature naturally shape the course of its thoughts, so this spell is particularly effective as part of an interrogation.\",\n \"You can also use this spell to detect the presence of thinking creatures you can't see. When you cast the spell or as your action during the duration, you can search for thoughts within 30 feet of you. The spell can penetrate barriers, but 2 feet of rock, 2 inches of any metal other than lead, or a thin sheet of lead blocks you. You can't detect a creature with an Intelligence of 3 or lower or one that doesn't speak any language.\",\n \"Once you detect the presence of a creature in this way, you can read its thoughts for the rest of the duration as described above, even if you can't see it, but it must still be within range.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A copper coin.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/detect-thoughts\"\n },\n {\n \"index\": \"dimension-door\",\n \"name\": \"Dimension Door\",\n \"desc\": [\n \"You teleport yourself from your current location to any other spot within range. You arrive at exactly the spot desired. It can be a place you can see, one you can visualize, or one you can describe by stating distance and direction, such as \\\"200 feet straight downward\\\" or \\\"upward to the northwest at a 45-degree angle, 300 feet.\\\"\",\n \"You can bring along objects as long as their weight doesn't exceed what you can carry. You can also bring one willing creature of your size or smaller who is carrying gear up to its carrying capacity. The creature must be within 5 feet of you when you cast this spell.\",\n \"If you would arrive in a place already occupied by an object or a creature, you and any creature traveling with you each take 4d6 force damage, and the spell fails to teleport you.\"\n ],\n \"range\": \"500 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"4d6\"\n }\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dimension-door\"\n },\n {\n \"index\": \"disguise-self\",\n \"name\": \"Disguise Self\",\n \"desc\": [\n \"You make yourself--including your clothing, armor, weapons, and other belongings on your person--look different until the spell ends or until you use your action to dismiss it. You can seem 1 foot shorter or taller and can appear thin, fat, or in between. You can't change your body type, so you must adopt a form that has the same basic arrangement of limbs. Otherwise, the extent of the illusion is up to you.\",\n \"The changes wrought by this spell fail to hold up to physical inspection. For example, if you use this spell to add a hat to your outfit, objects pass through the hat, and anyone who touches it would feel nothing or would feel your head and hair. If you use this spell to appear thinner than you are, the hand of someone who reaches out to touch you would bump into you while it was seemingly still in midair.\",\n \"To discern that you are disguised, a creature can use its action to inspect your appearance and must succeed on an Intelligence (Investigation) check against your spell save DC.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/disguise-self\"\n },\n {\n \"index\": \"disintegrate\",\n \"name\": \"Disintegrate\",\n \"desc\": [\n \"A thin green ray springs from your pointing finger to a target that you can see within range. The target can be a creature, an object, or a creation of magical force, such as the wall created by wall of force.\",\n \"A creature targeted by this spell must make a dexterity saving throw. On a failed save, the target takes 10d6 + 40 force damage. If this damage reduces the target to 0 hit points, it is disintegrated.\",\n \"A disintegrated creature and everything it is wearing and carrying, except magic items, are reduced to a pile of fine gray dust. The creature can be restored to life only by means of a true resurrection or a wish spell.\",\n \"This spell automatically disintegrates a Large or smaller nonmagical object or a creation of magical force. If the target is a Huge or larger object or creation of force, this spell disintegrates a 10-foot-cube portion of it. A magic item is unaffected by this spell.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the damage increases by 3d6 for each slot level above 6th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A lodestone and a pinch of dust.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"10d6 + 40\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/disintegrate\"\n },\n {\n \"index\": \"dispel-evil-and-good\",\n \"name\": \"Dispel Evil and Good\",\n \"desc\": [\n \"Shimmering energy surrounds and protects you from fey, undead, and creatures originating from beyond the Material Plane. For the duration, celestials, elementals, fey, fiends, and undead have disadvantage on attack rolls against you.\",\n \"You can end the spell early by using either of the following special functions.\",\n \"***Break Enchantment.*** As your action, you touch a creature you can reach that is charmed, frightened, or possessed by a celestial, an elemental, a fey, a fiend, or an undead. The creature you touch is no longer charmed, frightened, or possessed by such creatures.\",\n \"***Dismissal.*** As your action, make a melee spell attack against a celestial, an elemental, a fey, a fiend, or an undead you can reach. On a hit, you attempt to drive the creature back to its home plane. The creature must succeed on a charisma saving throw or be sent back to its home plane (if it isn't there already). If they aren't on their home plane, undead are sent to the Shadowfell, and fey are sent to the Feywild.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Holy water or powdered silver and iron.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"The creature must succeed on a charisma saving throw or be sent back to its home plane (if it isn't there already)\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dispel-evil-and-good\"\n },\n {\n \"index\": \"dispel-magic\",\n \"name\": \"Dispel Magic\",\n \"desc\": [\n \"Choose one creature, object, or magical effect within range. Any spell of 3rd level or lower on the target ends. For each spell of 4th level or higher on the target, make an ability check using your spellcasting ability. The DC equals 10 + the spell's level. On a successful check, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, you automatically end the effects of a spell on the target if the spell's level is equal to or less than the level of the spell slot you used.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/dispel-magic\"\n },\n {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"desc\": [\n \"Your magic and an offering put you in contact with a god or a god's servants. You ask a single question concerning a specific goal, event, or activity to occur within 7 days. The GM offers a truthful reply. The reply might be a short phrase, a cryptic rhyme, or an omen.\",\n \"The spell doesn't take into account any possible circumstances that might change the outcome, such as the casting of additional spells or the loss or gain of a companion.\",\n \"If you cast the spell two or more times before finishing your next long rest, there is a cumulative 25 percent chance for each casting after the first that you get a random reading. The GM makes this roll in secret.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Incense and a sacrificial offering appropriate to your religion, together worth at least 25gp, which the spell consumes.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/divination\"\n },\n {\n \"index\": \"divine-favor\",\n \"name\": \"Divine Favor\",\n \"desc\": [\n \"Your prayer empowers you with divine radiance. Until the spell ends, your weapon attacks deal an extra 1d4 radiant damage on a hit.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"1d4\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/divine-favor\"\n },\n {\n \"index\": \"divine-word\",\n \"name\": \"Divine Word\",\n \"desc\": [\n \"You utter a divine word, imbued with the power that shaped the world at the dawn of creation. Choose any number of creatures you can see within range. Each creature that can hear you must make a Charisma saving throw. On a failed save, a creature suffers an effect based on its current hit points:\",\n \"- 50 hit points or fewer: deafened for 1 minute\",\n \"- 40 hit points or fewer: deafened and blinded for 10 minutes\",\n \"- 30 hit points or fewer: blinded, deafened, and stunned for 1 hour\",\n \"- 20 hit points or fewer: killed instantly\",\n \"Regardless of its current hit points, a celestial, an elemental, a fey, or a fiend that fails its save is forced back to its plane of origin (if it isn't there already) and can't return to your current plane for 24 hours by any means short of a wish spell.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 7,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, a creature suffers an effect based on its current hit points.\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/divine-word\"\n },\n {\n \"index\": \"dominate-beast\",\n \"name\": \"Dominate Beast\",\n \"desc\": [\n \"You attempt to beguile a creature that you can see within range. It must succeed on a wisdom saving throw or be charmed by you for the duration. If you or creatures that are friendly to you are fighting it, it has advantage on the saving throw.\",\n \"While the creature is charmed, you have a telepathic link with it as long as the two of you are on the same plane of existence. You can use this telepathic link to issue commands to the creature while you are conscious (no action required), which it does its best to obey. You can specify a simple and general course of action, such as \\\"Attack that creature,\\\" \\\"Run over there,\\\" or \\\"Fetch that object.\\\" If the creature completes the order and doesn't receive further direction from you, it defends and preserves itself to the best of its ability.\",\n \"You can use your action to take total and precise control of the target. Until the end of your next turn, the creature takes only the actions you choose, and doesn't do anything that you don't allow it to do. During this time, you can also cause the creature to use a reaction, but this requires you to use your own reaction as well. Each time the target takes damage, it makes a new wisdom saving throw against the spell. If the saving throw succeeds, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell with a 9th level spell slot, the duration is concentration, up to 8 hours.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dominate-beast\"\n },\n {\n \"index\": \"dominate-monster\",\n \"name\": \"Dominate Monster\",\n \"desc\": [\n \"You attempt to beguile a creature that you can see within range. It must succeed on a wisdom saving throw or be charmed by you for the duration. If you or creatures that are friendly to you are fighting it, it has advantage on the saving throw.\",\n \"While the creature is charmed, you have a telepathic link with it as long as the two of you are on the same plane of existence. You can use this telepathic link to issue commands to the creature while you are conscious (no action required), which it does its best to obey. You can specify a simple and general course of action, such as \\\"Attack that creature,\\\" \\\"Run over there,\\\" or \\\"Fetch that object.\\\" If the creature completes the order and doesn't receive further direction from you, it defends and preserves itself to the best of its ability.\",\n \"You can use your action to take total and precise control of the target. Until the end of your next turn, the creature takes only the actions you choose, and doesn't do anything that you don't allow it to do. During this time, you can also cause the creature to use a reaction, but this requires you to use your own reaction as well.\",\n \"Each time the target takes damage, it makes a new wisdom saving throw against the spell. If the saving throw succeeds, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell with a 9th-level spell slot, the duration is concentration, up to 8 hours.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On failure, the creature is charmed by you for the duration.\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dominate-monster\"\n },\n {\n \"index\": \"dominate-person\",\n \"name\": \"Dominate Person\",\n \"desc\": [\n \"You attempt to beguile a humanoid that you can see within range. It must succeed on a wisdom saving throw or be charmed by you for the duration. If you or creatures that are friendly to you are fighting it, it has advantage on the saving throw.\",\n \"While the target is charmed, you have a telepathic link with it as long as the two of you are on the same plane of existence. You can use this telepathic link to issue commands to the creature while you are conscious (no action required), which it does its best to obey. You can specify a simple and general course of action, such as \\\"Attack that creature,\\\" \\\"Run over there,\\\" or \\\"Fetch that object.\\\" If the creature completes the order and doesn't receive further direction from you, it defends and preserves itself to the best of its ability.\",\n \"You can use your action to take total and precise control of the target. Until the end of your next turn, the creature takes only the actions you choose, and doesn't do anything that you don't allow it to do. During this time you can also cause the creature to use a reaction, but this requires you to use your own reaction as well.\",\n \"Each time the target takes damage, it makes a new wisdom saving throw against the spell. If the saving throw succeeds, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 6th-level spell slot, the duration is concentration, up to 10 minutes. When you use a 7th-level spell slot, the duration is concentration, up to 1 hour. When you use a spell slot of 8th level or higher, the duration is concentration, up to 8 hours.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"Each time the target takes damage, it makes a new wisdom saving throw against the spell. If the saving throw succeeds, the spell ends.\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/dominate-person\"\n },\n {\n \"index\": \"dream\",\n \"name\": \"Dream\",\n \"desc\": [\n \"This spell shapes a creature's dreams. Choose a creature known to you as the target of this spell. The target must be on the same plane of existence as you. Creatures that don't sleep, such as elves, can't be contacted by this spell. You, or a willing creature you touch, enters a trance state, acting as a messenger.\",\n \"While in the trance, the messenger is aware of his or her surroundings, but can't take actions or move.\",\n \"If the target is asleep, the messenger appears in the target's dreams and can converse with the target as long as it remains asleep, through the duration of the spell. The messenger can also shape the environment of the dream, creating landscapes, objects, and other images. The messenger can emerge from the trance at any time, ending the effect of the spell early. The target recalls the dream perfectly upon waking. If the target is awake when you cast the spell, the messenger knows it, and can either end the trance (and the spell) or wait for the target to fall asleep, at which point the messenger appears in the target's dreams.\",\n \"You can make the messenger appear monstrous and terrifying to the target. If you do, the messenger can deliver a message of no more than ten words and then the target must make a wisdom saving throw. On a failed save, echoes of the phantasmal monstrosity spawn a nightmare that lasts the duration of the target's sleep and prevents the target from gaining any benefit from that rest. In addition, when the target wakes up, it takes 3d6 psychic damage.\",\n \"If you have a body part, lock of hair, clipping from a nail, or similar portion of the target's body, the target makes its saving throw with disadvantage.\"\n ],\n \"range\": \"Special\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A handful of sand, a dab of ink, and a writing quill plucked from a sleeping bird.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"psychic\",\n \"name\": \"Psychic\",\n \"url\": \"/api/damage-types/psychic\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"3d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, echoes of the phantasmal monstrosity spawn a nightmare that lasts the duration of the target's sleep and prevents the target from gaining any benefit from that rest.\"\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/dream\"\n },\n {\n \"index\": \"druidcraft\",\n \"name\": \"Druidcraft\",\n \"desc\": [\n \"Whispering to the spirits of nature, you create one of the following effects within 'range':\",\n \"- You create a tiny, harmless sensory effect that predicts what the weather will be at your location for the next 24 hours. The effect might manifest as a golden orb for clear skies, a cloud for rain, falling snowflakes for snow, and so on. This effect persists for 1 round.\",\n \"- You instantly make a flower bloom, a seed pod open, or a leaf bud bloom.\",\n \"- You create an instantaneous, harmless sensory effect, such as falling leaves, a puff of wind, the sound of a small animal, or the faint order of skunk. The effect must fit in a 5-foot cube.\",\n \"- You instantly light or snuff out a candle, a torch, or a small campfire.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/druidcraft\"\n },\n {\n \"index\": \"earthquake\",\n \"name\": \"Earthquake\",\n \"desc\": [\n \"You create a seismic disturbance at a point on the ground that you can see within range. For the duration, an intense tremor rips through the ground in a 100-foot-radius circle centered on that point and shakes creatures and structures in contact with the ground in that area.\",\n \"The ground in the area becomes difficult terrain. Each creature on the ground that is concentrating must make a constitution saving throw. On a failed save, the creature's concentration is broken.\",\n \"When you cast this spell and at the end of each turn you spend concentrating on it, each creature on the ground in the area must make a dexterity saving throw. On a failed save, the creature is knocked prone.\",\n \"This spell can have additional effects depending on the terrain in the area, as determined by the GM.\",\n \"Fissures. Fissures open throughout the spell's area at the start of your next turn after you cast the spell. A total of 1d6 such fissures open in locations chosen by the GM. Each is 1d10 x 10 feet deep, 10 feet wide, and extends from one edge of the spell's area to the opposite side. A creature standing on a spot where a fissure opens must succeed on a dexterity saving throw or fall in. A creature that successfully saves moves with the fissure's edge as it opens.\",\n \"A fissure that opens beneath a structure causes it to automatically collapse (see below).\",\n \"Structures. The tremor deals 50 bludgeoning damage to any structure in contact with the ground in the area when you cast the spell and at the start of each of your turns until the spell ends. If a structure drops to 0 hit points, it collapses and potentially damages nearby creatures. A creature within half the distance of a structure's height must make a dexterity saving throw. On a failed save, the creature takes 5d6 bludgeoning damage, is knocked prone, and is buried in the rubble, requiring a DC 20 Strength (Athletics) check as an action to escape. The GM can adjust the DC higher or lower, depending on the nature of the rubble. On a successful save, the creature takes half as much damage and doesn't fall prone or become buried.\"\n ],\n \"range\": \"500 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of dirt, a piece of rock, and a lump of clay.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/earthquake\"\n },\n {\n \"index\": \"eldritch-blast\",\n \"name\": \"Eldritch Blast\",\n \"desc\": [\n \"A beam of crackling energy streaks toward a creature within range. Make a ranged spell attack against the target. On a hit, the target takes 1d10 force damage. The spell creates more than one beam when you reach higher levels: two beams at 5th level, three beams at 11th level, and four beams at 17th level. You can direct the beams at the same target or at different ones. Make a separate attack roll for each beam.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d10\",\n \"5\": \"1d10\",\n \"11\": \"1d10\",\n \"17\": \"1d10\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/eldritch-blast\"\n },\n {\n \"index\": \"enhance-ability\",\n \"name\": \"Enhance Ability\",\n \"desc\": [\n \"You touch a creature and bestow upon it a magical enhancement. Choose one of the following effects; the target gains that effect until the spell ends.\",\n \"***Bear's Endurance.*** The target has advantage on constitution checks. It also gains 2d6 temporary hit points, which are lost when the spell ends.\",\n \"***Bull's Strength.*** The target has advantage on strength checks, and his or her carrying capacity doubles.\",\n \"***Cat's Grace.*** The target has advantage on dexterity checks. It also doesn't take damage from falling 20 feet or less if it isn't incapacitated.\",\n \"***Eagle's Splendor.*** The target has advantage on Charisma checks.\",\n \"***Fox's Cunning.*** The target has advantage on intelligence checks.\",\n \"***Owl's Wisdom.*** The target has advantage on wisdom checks.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you can target one additional creature for each slot level above 2nd.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Fur or a feather from a beast.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/enhance-ability\"\n },\n {\n \"index\": \"enlarge-reduce\",\n \"name\": \"Enlarge/Reduce\",\n \"desc\": [\n \"You cause a creature or an object you can see within range to grow larger or smaller for the duration. Choose either a creature or an object that is neither worn nor carried. If the target is unwilling, it can make a Constitution saving throw. On a success, the spell has no effect.\",\n \"If the target is a creature, everything it is wearing and carrying changes size with it. Any item dropped by an affected creature returns to normal size at once.\",\n \"***Enlarge.*** The target's size doubles in all dimensions, and its weight is multiplied by eight. This growth increases its size by one category-from Medium to Large, for example. If there isn't enough room for the target to double its size, the creature or object attains the maximum possible size in the space available. Until the spell ends, the target also has advantage on Strength checks and Strength saving throws. The target's weapons also grow to match its new size. While these weapons are enlarged, the target's attacks with them deal 1d4 extra damage.\",\n \"***Reduce.*** The target's size is halved in all dimensions, and its weight is reduced to one-eighth of normal. This reduction decreases its size by one category-from Medium to Small, for example. Until the spell ends, the target also has disadvantage on Strength checks and Strength saving throws. The target's weapons also shrink to match its new size. While these weapons are reduced, the target's attacks with them deal 1d4 less damage (this can't reduce the damage below 1).\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch iron powder.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/enlarge-reduce\"\n },\n {\n \"index\": \"entangle\",\n \"name\": \"Entangle\",\n \"desc\": [\n \"Grasping weeds and vines sprout from the ground in a 20-foot square starting form a point within range. For the duration, these plants turn the ground in the area into difficult terrain.\",\n \"A creature in the area when you cast the spell must succeed on a strength saving throw or be restrained by the entangling plants until the spell ends. A creature restrained by the plants can use its action to make a Strength check against your spell save DC. On a success, it frees itself.\",\n \"When the spell ends, the conjured plants wilt away.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"str\",\n \"name\": \"STR\",\n \"url\": \"/api/ability-scores/str\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/entangle\"\n },\n {\n \"index\": \"enthrall\",\n \"name\": \"Enthrall\",\n \"desc\": [\n \"You weave a distracting string of words, causing creatures of your choice that you can see within range and that can hear you to make a wisdom saving throw. Any creature that can't be charmed succeeds on this saving throw automatically, and if you or your companions are fighting a creature, it has advantage on the save. On a failed save, the target has disadvantage on Wisdom (Perception) checks made to perceive any creature other than you until the spell ends or until the target can no longer hear you. The spell ends if you are incapacitated or can no longer speak.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/enthrall\"\n },\n {\n \"index\": \"etherealness\",\n \"name\": \"Etherealness\",\n \"desc\": [\n \"You step into the border regions of the Ethereal Plane, in the area where it overlaps with your current plane. You remain in the Border Ethereal for the duration or until you use your action to dismiss the spell. During this time, you can move in any direction. If you move up or down, every foot of movement costs an extra foot. You can see and hear the plane you originated from, but everything there looks gray, and you can't see anything more than 60 feet away.\",\n \"While on the Ethereal Plane, you can only affect and be affected by other creatures on that plane. Creatures that aren't on the Ethereal Plane can't perceive you and can't interact with you, unless a special ability or magic has given them the ability to do so.\",\n \"You ignore all objects and effects that aren't on the Ethereal Plane, allowing you to move through objects you perceive on the plane you originated from.\",\n \"When the spell ends, you immediately return to the plane you originated from in the spot you currently occupy. If you occupy the same spot as a solid object or creature when this happens, you are immediately shunted to the nearest unoccupied space that you can occupy and take force damage equal to twice the number of feet you are moved.\",\n \"This spell has no effect if you cast it while you are on the Ethereal Plane or a plane that doesn't border it, such as one of the Outer Planes.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 8th level or higher, you can target up to three willing creatures (including you) for each slot level above 7th. The creatures must be within 10 feet of you when you cast the spell.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/etherealness\"\n },\n {\n \"index\": \"expeditious-retreat\",\n \"name\": \"Expeditious Retreat\",\n \"desc\": [\n \"This spell allows you to move at an incredible pace. When you cast this spell, and then as a bonus action on each of your turns until the spell ends, you can take the Dash action.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/expeditious-retreat\"\n },\n {\n \"index\": \"eyebite\",\n \"name\": \"Eyebite\",\n \"desc\": [\n \"For the spell's duration, your eyes become an inky void imbued with dread power. One creature of your choice within 60 feet of you that you can see must succeed on a wisdom saving throw or be affected by one of the following effects of your choice for the duration. On each of your turns until the spell ends, you can use your action to target another creature but can't target a creature again if it has succeeded on a saving throw against this casting of eyebite.\",\n \"***Asleep.*** The target falls unconscious. It wakes up if it takes any damage or if another creature uses its action to shake the sleeper awake.\",\n \"***Panicked.*** The target is frightened of you. On each of its turns, the frightened creature must take the Dash action and move away from you by the safest and shortest available route, unless there is nowhere to move. If the target moves to a place at least 60 feet away from you where it can no longer see you, this effect ends.\",\n \"***Sickened.*** The target has disadvantage on attack rolls and ability checks. At the end of each of its turns, it can make another wisdom saving throw. If it succeeds, the effect ends.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On failure, the target can be affected by one of the following effects of your choice for the duration. [Asleep. The target falls unconscious. It wakes up if it takes any damage or if another creature uses its action to shake the sleeper awake.] [Panicked. The target is frightened of you. On each of its turns, the frightened creature must take the Dash action and move away from you by the safest and shortest available route, unless there is nowhere to move. If the target moves to a place at least 60 feet away from you where it can no longer see you, this effect ends.] [Sickened. The target has disadvantage on attack rolls and ability checks. At the end of each of its turns, it can make another wisdom saving throw. If it succeeds, the effect ends.]\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/eyebite\"\n },\n {\n \"index\": \"fabricate\",\n \"name\": \"Fabricate\",\n \"desc\": [\n \"You convert raw materials into products of the same material. For example, you can fabricate a wooden bridge from a clump of trees, a rope from a patch of hemp, and clothes from flax or wool.\",\n \"Choose raw materials that you can see within range. You can fabricate a Large or smaller object (contained within a 10-foot cube, or eight connected 5-foot cubes), given a sufficient quantity of raw material. If you are working with metal, stone, or another mineral substance, however, the fabricated object can be no larger than Medium (contained within a single 5-foot cube). The quality of objects made by the spell is commensurate with the quality of the raw materials.\",\n \"Creatures or magic items can't be created or transmuted by this spell. You also can't use it to create items that ordinarily require a high degree of craftsmanship, such as jewelry, weapons, glass, or armor, unless you have proficiency with the type of artisan's tools used to craft such objects.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 4,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/fabricate\"\n },\n {\n \"index\": \"faerie-fire\",\n \"name\": \"Faerie Fire\",\n \"desc\": [\n \"Each object in a 20-foot cube within range is outlined in blue, green, or violet light (your choice). Any creature in the area when the spell is cast is also outlined in light if it fails a dexterity saving throw. For the duration, objects and affected creatures shed dim light in a 10-foot radius.\",\n \"Any attack roll against an affected creature or object has advantage if the attacker can see it, and the affected creature or object can't benefit from being invisible.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/faerie-fire\"\n },\n {\n \"index\": \"faithful-hound\",\n \"name\": \"Faithful Hound\",\n \"desc\": [\n \"You conjure a phantom watchdog in an unoccupied space that you can see within range, where it remains for the duration, until you dismiss it as an action, or until you move more than 100 feet away from it.\",\n \"The hound is invisible to all creatures except you and can't be harmed. When a Small or larger creature comes within 30 feet of it without first speaking the password that you specify when you cast this spell, the hound starts barking loudly. The hound sees invisible creatures and can see into the Ethereal Plane. It ignores illusions.\",\n \"At the start of each of your turns, the hound attempts to bite one creature within 5 feet of it that is hostile to you. The hound's attack bonus is equal to your spellcasting ability modifier + your proficiency bonus. On a hit, it deals 4d8 piercing damage.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny silver whistle, a piece of bone, and a thread\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"piercing\",\n \"name\": \"Piercing\",\n \"url\": \"/api/damage-types/piercing\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/faithful-hound\"\n },\n {\n \"index\": \"false-life\",\n \"name\": \"False Life\",\n \"desc\": [\n \"Bolstering yourself with a necromantic facsimile of life, you gain 1d4 + 4 temporary hit points for the duration.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you gain 5 additional temporary hit points for each slot level above 1st.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small amount of alcohol or distilled spirits.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"heal_at_slot_level\": {\n \"1\": \"1d4 + 4\",\n \"2\": \"1d4 + 9\",\n \"3\": \"1d4 + 14\",\n \"4\": \"1d4 + 19\",\n \"5\": \"1d4 + 24\",\n \"6\": \"1d4 + 29\",\n \"7\": \"1d4 + 34\",\n \"8\": \"1d4 + 39\",\n \"9\": \"1d4 + 44\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/false-life\"\n },\n {\n \"index\": \"fear\",\n \"name\": \"Fear\",\n \"desc\": [\n \"You project a phantasmal image of a creature's worst fears. Each creature in a 30-foot cone must succeed on a wisdom saving throw or drop whatever it is holding and become frightened for the duration.\",\n \"While frightened by this spell, a creature must take the Dash action and move away from you by the safest available route on each of its turns, unless there is nowhere to move. If the creature ends its turn in a location where it doesn't have line of sight to you, the creature can make a wisdom saving throw. On a successful save, the spell ends for that creature.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A white feather or the heart of a hen.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On fail, A creature drop whatever it is holding and become frightened for the duration.\"\n },\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/fear\"\n },\n {\n \"index\": \"feather-fall\",\n \"name\": \"Feather Fall\",\n \"desc\": [\n \"Choose up to five falling creatures within range. A falling creature's rate of descent slows to 60 feet per round until the spell ends. If the creature lands before the spell ends, it takes no falling damage and can land on its feet, and the spell ends for that creature.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A small feather or a piece of down.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 reaction\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/feather-fall\"\n },\n {\n \"index\": \"feeblemind\",\n \"name\": \"Feeblemind\",\n \"desc\": [\n \"You blast the mind of a creature that you can see within range, attempting to shatter its intellect and personality. The target takes 4d6 psychic damage and must make an intelligence saving throw.\",\n \"On a failed save, the creature's Intelligence and Charisma scores become 1. The creature can't cast spells, activate magic items, understand language, or communicate in any intelligible way. The creature can, however, identify its friends, follow them, and even protect them.\",\n \"At the end of every 30 days, the creature can repeat its saving throw against this spell. If it succeeds on its saving throw, the spell ends.\",\n \"The spell can also be ended by greater restoration, heal, or wish.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A handful of clay, crystal, glass, or mineral spheres.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"psychic\",\n \"name\": \"Psychic\",\n \"url\": \"/api/damage-types/psychic\"\n },\n \"damage_at_slot_level\": {\n \"8\": \"4d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"int\",\n \"name\": \"INT\",\n \"url\": \"/api/ability-scores/int\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"The target always takes the damage. On a failed save, the creature's Intelligence and Charisma scores become 1.\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/feeblemind\"\n },\n {\n \"index\": \"find-familiar\",\n \"name\": \"Find Familiar\",\n \"desc\": [\n \"You gain the service of a familiar, a spirit that takes an animal form you choose: bat, cat, crab, frog (toad), hawk, lizard, octopus, owl, poisonous snake, fish (quipper), rat, raven, sea horse, spider, or weasel. Appearing in an unoccupied space within range, the familiar has the statistics of the chosen form, though it is a celestial, fey, or fiend (your choice) instead of a beast.\",\n \"Your familiar acts independently of you, but it always obeys your commands. In combat, it rolls its own initiative and acts on its own turn. A familiar can't attack, but it can take other actions as normal.\",\n \"When the familiar drops to 0 hit points, it disappears, leaving behind no physical form. It reappears after you cast this spell again.\",\n \"While your familiar is within 100 feet of you, you can communicate with it telepathically. Additionally, as an action, you can see through your familiar's eyes and hear what it hears until the start of your next turn, gaining the benefits of any special senses that the familiar has. During this time, you are deaf and blind with regard to your own senses.\",\n \"As an action, you can temporarily dismiss your familiar. It disappears into a pocket dimension where it awaits your summons. Alternatively, you can dismiss it forever. As an action while it is temporarily dismissed, you can cause it to reappear in any unoccupied space within 30 feet of you.\",\n \"You can't have more than one familiar at a time. If you cast this spell while you already have a familiar, you instead cause it to adopt a new form. Choose one of the forms from the above list. Your familiar transforms into the chosen creature.\",\n \"Finally, when you cast a spell with a range of touch, your familiar can deliver the spell as if it had cast the spell. Your familiar must be within 100 feet of you, and it must use its reaction to deliver the spell when you cast it. If the spell requires an attack roll, you use your action modifier for the roll.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"10gp worth of charcoal, incense, and herbs that must be consumed by fire in a brass brazier.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 1,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/find-familiar\"\n },\n {\n \"index\": \"find-steed\",\n \"name\": \"Find Steed\",\n \"desc\": [\n \"You summon a spirit that assumes the form of an unusually intelligent, strong, and loyal steed, creating a long-lasting bond with it. Appearing in an unoccupied space within range, the steed takes on a form that you choose, such as a warhorse, a pony, a camel, an elk, or a mastiff. (Your GM might allow other animals to be summoned as steeds.) The steed has the statistics of the chosen form, though it is a celestial, fey, or fiend (your choice) instead of its normal type. Additionally, if your steed has an Intelligence of 5 or less, its Intelligence becomes 6, and it gains the ability to understand one language of your choice that you speak.\",\n \"Your steed serves you as a mount, both in combat and out, and you have an instinctive bond with it that allows you to fight as a seamless unit. While mounted on your steed, you can make any spell you cast that targets only you also target your steed.\",\n \"When the steed drops to 0 hit points, it disappears, leaving behind no physical form. You can also dismiss your steed at any time as an action, causing it to disappear. In either case, casting this spell again summons the same steed, restored to its hit point maximum.\",\n \"While your steed is within 1 mile of you, you can communicate with it telepathically.\",\n \"You can't have more than one steed bonded by this spell at a time. As an action, you can release the steed from its bond at any time, causing it to disappear.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 2,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/find-steed\"\n },\n {\n \"index\": \"find-traps\",\n \"name\": \"Find Traps\",\n \"desc\": [\n \"You sense the presence of any trap within range that is within line of sight. A trap, for the purpose of this spell, includes anything that would inflict a sudden or unexpected effect you consider harmful or undesirable, which was specifically intended as such by its creator. Thus, the spell would sense an area affected by the alarm spell, a glyph of warding, or a mechanical pit trap, but it would not reveal a natural weakness in the floor, an unstable ceiling, or a hidden sinkhole.\",\n \"This spell merely reveals that a trap is present. You don't learn the location of each trap, but you do learn the general nature of the danger posed by a trap you sense.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/find-traps\"\n },\n {\n \"index\": \"find-the-path\",\n \"name\": \"Find the Path\",\n \"desc\": [\n \"This spell allows you to find the shortest, most direct physical route to a specific fixed location that you are familiar with on the same plane of existence. If you name a destination on another plane of existence, a destination that moves (such as a mobile fortress), or a destination that isn't specific (such as \\\"a green dragon's lair\\\"), the spell fails.\",\n \"For the duration, as long as you are on the same plane of existence as the destination, you know how far it is and in what direction it lies. While you are traveling there, whenever you are presented with a choice of paths along the way, you automatically determine which path is the shortest and most direct route (but not necessarily the safest route) to the destination.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A set of divinatory tools--such as bones, ivory sticks, cards, teeth, or carved runes--worth 100gp and an object from the location you wish to find.\",\n \"ritual\": false,\n \"duration\": \"Up to 24 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/find-the-path\"\n },\n {\n \"index\": \"finger-of-death\",\n \"name\": \"Finger of Death\",\n \"desc\": [\n \"You send negative energy coursing through a creature that you can see within range, causing it searing pain. The target must make a constitution saving throw. It takes 7d8 + 30 necrotic damage on a failed save, or half as much damage on a successful one.\",\n \"A humanoid killed by this spell rises at the start of your next turn as a zombie that is permanently under your command, following your verbal orders to the best of its ability.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"7\": \"7d8 + 30\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/finger-of-death\"\n },\n {\n \"index\": \"fire-bolt\",\n \"name\": \"Fire Bolt\",\n \"desc\": [\n \"You hurl a mote of fire at a creature or object within range. Make a ranged spell attack against the target. On a hit, the target takes 1d10 fire damage. A flammable object hit by this spell ignites if it isn't being worn or carried.\",\n \"This spell's damage increases by 1d10 when you reach 5th level (2d10), 11th level (3d10), and 17th level (4d10).\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d10\",\n \"5\": \"2d10\",\n \"11\": \"3d10\",\n \"17\": \"4d10\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/fire-bolt\"\n },\n {\n \"index\": \"fire-shield\",\n \"name\": \"Fire Shield\",\n \"desc\": [\n \"Thin and vaporous flame surround your body for the duration of the spell, radiating a bright light bright light in a 10-foot radius and dim light for an additional 10 feet. You can end the spell using an action to make it disappear.\",\n \"The flames are around you a heat shield or cold, your choice. The heat shield gives you cold damage resistance and the cold resistance to fire damage.\",\n \"In addition, whenever a creature within 5 feet of you hits you with a melee attack, flames spring from the shield. The attacker then suffers 2d8 points of fire damage or cold, depending on the model.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A little phosphorus or a firefly.\",\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"2d8\"\n }\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/fire-shield\"\n },\n {\n \"index\": \"fire-storm\",\n \"name\": \"Fire Storm\",\n \"desc\": [\n \"A storm made up of sheets of roaring flame appears in a location you choose within range. The area of the storm consists of up to ten 10-foot cubes, which you can arrange as you wish. Each cube must have at least one face adjacent to the face of another cube. Each creature in the area must make a dexterity saving throw. It takes 7d10 fire damage on a failed save, or half as much damage on a successful one.\",\n \"The fire damages objects in the area and ignites flammable objects that aren't being worn or carried. If you choose, plant life in the area is unaffected by this spell.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"7\": \"7d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/fire-storm\"\n },\n {\n \"index\": \"fireball\",\n \"name\": \"Fireball\",\n \"desc\": [\n \"A bright streak flashes from your pointing finger to a point you choose within range and then blossoms with a low roar into an explosion of flame. Each creature in a 20-foot-radius sphere centered on that point must make a dexterity saving throw. A target takes 8d6 fire damage on a failed save, or half as much damage on a successful one.\",\n \"The fire spreads around corners. It ignites flammable objects in the area that aren't being worn or carried.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d6 for each slot level above 3rd.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny ball of bat guano and sulfur.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"8d6\",\n \"4\": \"9d6\",\n \"5\": \"10d6\",\n \"6\": \"11d6\",\n \"7\": \"12d6\",\n \"8\": \"13d6\",\n \"9\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/fireball\"\n },\n {\n \"index\": \"flame-blade\",\n \"name\": \"Flame Blade\",\n \"desc\": [\n \"You evoke a fiery blade in your free hand. The blade is similar in size and shape to a scimitar, and it lasts for the duration. If you let go of the blade, it disappears, but you can evoke the blade again as a bonus action.\",\n \"You can use your action to make a melee spell attack with the fiery blade. On a hit, the target takes 3d6 fire damage.\",\n \"The flaming blade sheds bright light in a 10-foot radius and dim light for an additional 10 feet.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d6 for every two slot levels above 2nd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Leaf of sumac.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"3d6\",\n \"4\": \"4d6\",\n \"6\": \"5d6\",\n \"8\": \"6d6\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/flame-blade\"\n },\n {\n \"index\": \"flame-strike\",\n \"name\": \"Flame Strike\",\n \"desc\": [\n \"A vertical column of divine fire roars down from the heavens in a location you specify. Each creature in a 10-foot-radius, 40-foot-high cylinder centered on a point within range must make a dexterity saving throw. A creature takes 4d6 fire damage and 4d6 radiant damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the fire damage or the radiant damage (your choice) increases by 1d6 for each slot level above 5th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Pinch of sulfur.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"4d6 + 4d6\",\n \"6\": \"4d6 + 5d6\",\n \"7\": \"4d6 + 6d6\",\n \"8\": \"4d6 + 7d6\",\n \"9\": \"4d6 + 8d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/flame-strike\"\n },\n {\n \"index\": \"flaming-sphere\",\n \"name\": \"Flaming Sphere\",\n \"desc\": [\n \"A 5-foot-diameter sphere of fire appears in an unoccupied space of your choice within range and lasts for the duration. Any creature that ends its turn within 5 feet of the sphere must make a dexterity saving throw. The creature takes 2d6 fire damage on a failed save, or half as much damage on a successful one.\",\n \"As a bonus action, you can move the sphere up to 30 feet. If you ram the sphere into a creature, that creature must make the saving throw against the sphere's damage, and the sphere stops moving this turn.\",\n \"When you move the sphere, you can direct it over barriers up to 5 feet tall and jump it across pits up to 10 feet wide. The sphere ignites flammable objects not being worn or carried, and it sheds bright light in a 20-foot radius and dim light for an additional 20 feet.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage increases by 1d6 for each slot level above 2nd.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of tallow, a pinch of brimstone, and a dusting of powdered iron.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d6\",\n \"3\": \"3d6\",\n \"4\": \"4d6\",\n \"5\": \"5d6\",\n \"6\": \"6d6\",\n \"7\": \"7d6\",\n \"8\": \"8d6\",\n \"9\": \"9d6\"\n }\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/flaming-sphere\"\n },\n {\n \"index\": \"flesh-to-stone\",\n \"name\": \"Flesh to Stone\",\n \"desc\": [\n \"You attempt to turn one creature that you can see within range into stone. If the target's body is made of flesh, the creature must make a constitution saving throw. On a failed save, it is restrained as its flesh begins to harden. On a successful save, the creature isn't affected.\",\n \"A creature restrained by this spell must make another constitution saving throw at the end of each of its turns. If it successfully saves against this spell three times, the spell ends. If it fails its saves three times, it is turned to stone and subjected to the petrified condition for the duration. The successes and failures don't need to be consecutive; keep track of both until the target collects three of a kind.\",\n \"If the creature is physically broken while petrified, it suffers from similar deformities if it reverts to its original state.\",\n \"If you maintain your concentration on this spell for the entire possible duration, the creature is turned to stone until the effect is removed.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of lime, water, and earth.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, the target is restrained as its flesh begins to harden.\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/flesh-to-stone\"\n },\n {\n \"index\": \"floating-disk\",\n \"name\": \"Floating Disk\",\n \"desc\": [\n \"This spell creates a circular, horizontal plane of force, 3 feet in diameter and 1 inch thick, that floats 3 feet above the ground in an unoccupied space of your choice that you can see within range. The disk remains for the duration, and can hold up to 500 pounds. If more weight is placed on it, the spell ends, and everything on the disk falls to the ground.\",\n \"The disk is immobile while you are within 20 feet of it. If you move more than 20 feet away from it, the disk follows you so that it remains within 20 feet of you. If can move across uneven terrain, up or down stairs, slopes and the like, but it can't cross an elevation change of 10 feet or more. For example, the disk can't move across a 10-foot-deep pit, nor could it leave such a pit if it was created at the bottom.\",\n \"If you move more than 100 feet away from the disk (typically because it can't move around an obstacle to follow you), the spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of mercury.\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/floating-disk\"\n },\n {\n \"index\": \"fly\",\n \"name\": \"Fly\",\n \"desc\": [\n \"You touch a willing creature. The target gains a flying speed of 60 feet for the duration. When the spell ends, the target falls if it is still aloft, unless it can stop the fall.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, you can target one additional creature for each slot level above 3rd.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A wing feather from any bird.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/fly\"\n },\n {\n \"index\": \"fog-cloud\",\n \"name\": \"Fog Cloud\",\n \"desc\": [\n \"You create a 20-foot-radius sphere of fog centered on a point within range. The sphere spreads around corners, and its area is heavily obscured. It lasts for the duration or until a wind of moderate or greater speed (at least 10 miles per hour) disperses it.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the radius of the fog increases by 20 feet for each slot level above 1st.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/fog-cloud\"\n },\n {\n \"index\": \"forbiddance\",\n \"name\": \"Forbiddance\",\n \"desc\": [\n \"You create a ward against magical travel that protects up to 40,000 square feet of floor space to a height of 30 feet above the floor. For the duration, creatures can't teleport into the area or use portals, such as those created by the gate spell, to enter the area. The spell proofs the area against planar travel, and therefore prevents creatures from accessing the area by way of the Astral Plane, Ethereal Plane, Feywild, Shadowfell, or the plane shift spell.\",\n \"In addition, the spell damages types of creatures that you choose when you cast it. Choose one or more of the following: celestials, elementals, fey, fiends, and undead. When a chosen creature enters the spell's area for the first time on a turn or starts its turn there, the creature takes 5d10 radiant or necrotic damage (your choice when you cast this spell).\",\n \"When you cast this spell, you can designate a password. A creature that speaks the password as it enters the area takes no damage from the spell.\",\n \"The spell's area can't overlap with the area of another forbiddance spell. If you cast forbiddance every day for 30 days in the same location, the spell lasts until it is dispelled, and the material components are consumed on the last casting.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sprinkling of holy water, rare incense, and powdered ruby worth at least 1,000 gp.\",\n \"ritual\": true,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 40000\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/forbiddance\"\n },\n {\n \"index\": \"forcecage\",\n \"name\": \"Forcecage\",\n \"desc\": [\n \"An immobile, invisible, cube-shaped prison composed of magical force springs into existence around an area you choose within range. The prison can be a cage or a solid box, as you choose.\",\n \"A prison in the shape of a cage can be up to 20 feet on a side and is made from 1/2-inch diameter bars spaced 1/2 inch apart.\",\n \"A prison in the shape of a box can be up to 10 feet on a side, creating a solid barrier that prevents any matter from passing through it and blocking any spells cast into or out from the area.\",\n \"When you cast the spell, any creature that is completely inside the cage's area is trapped. Creatures only partially within the area, or those too large to fit inside the area, are pushed away from the center of the area until they are completely outside the area.\",\n \"A creature inside the cage can't leave it by nonmagical means. If the creature tries to use teleportation or interplanar travel to leave the cage, it must first make a charisma saving throw. On a success, the creature can use that magic to exit the cage. On a failure, the creature can't exit the cage and wastes the use of the spell or effect. The cage also extends into the Ethereal Plane, blocking ethereal travel.\",\n \"This spell can't be dispelled by dispel magic.\"\n ],\n \"range\": \"100 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Ruby dust worth 1,500 gp.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/forcecage\"\n },\n {\n \"index\": \"foresight\",\n \"name\": \"Foresight\",\n \"desc\": [\n \"You touch a willing creature and bestow a limited ability to see into the immediate future. For the duration, the target can't be surprised and has advantage on attack rolls, ability checks, and saving throws. Additionally, other creatures have disadvantage on attack rolls against the target for the duration.\",\n \"This spell immediately ends if you cast it again before its duration ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A hummingbird feather.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 9,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/foresight\"\n },\n {\n \"index\": \"freedom-of-movement\",\n \"name\": \"Freedom of Movement\",\n \"desc\": [\n \"You touch a willing creature. For the duration, the target's movement is unaffected by difficult terrain, and spells and other magical effects can neither reduce the target's speed nor cause the target to be paralyzed or restrained.\",\n \"The target can also spend 5 feet of movement to automatically escape from nonmagical restraints, such as manacles or a creature that has it grappled. Finally, being underwater imposes no penalties on the target's movement or attacks.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A leather strap, bound around the arm or a similar appendage.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/freedom-of-movement\"\n },\n {\n \"index\": \"freezing-sphere\",\n \"name\": \"Freezing Sphere\",\n \"desc\": [\n \"A frigid globe of cold energy streaks from your fingertips to a point of your choice within range, where it explodes in a 60-foot-radius sphere. Each creature within the area must make a constitution saving throw. On a failed save, a creature takes 10d6 cold damage. On a successful save, it takes half as much damage.\",\n \"If the globe strikes a body of water or a liquid that is principally water (not including water-based creatures), it freezes the liquid to a depth of 6 inches over an area 30 feet square. This ice lasts for 1 minute. Creatures that were swimming on the surface of frozen water are trapped in the ice. A trapped creature can use an action to make a Strength check against your spell save DC to break free.\",\n \"You can refrain from firing the globe after completing the spell, if you wish. A small globe about the size of a sling stone, cool to the touch, appears in your hand. At any time, you or a creature you give the globe to can throw the globe (to a range of 40 feet) or hurl it with a sling (to the sling's normal range). It shatters on impact, with the same effect as the normal casting of the spell. You can also set the globe down without shattering it. After 1 minute, if the globe hasn't already shattered, it explodes.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the damage increases by 1d6 for each slot level above 6th.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small crystal sphere.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"cold\",\n \"name\": \"Cold\",\n \"url\": \"/api/damage-types/cold\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"10d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/freezing-sphere\"\n },\n {\n \"index\": \"gaseous-form\",\n \"name\": \"Gaseous Form\",\n \"desc\": [\n \"You transform a willing creature you touch, along with everything it's wearing and carrying, into a misty cloud for the duration. The spell ends if the creature drops to 0 hit points. An incorporeal creature isn't affected.\",\n \"While in this form, the target's only method of movement is a flying speed of 10 feet. The target can enter and occupy the space of another creature. The target has resistance to nonmagical damage, and it has advantage on Strength, Dexterity, and constitution saving throws. The target can pass through small holes, narrow openings, and even mere cracks, though it treats liquids as though they were solid surfaces. The target can't fall and remains hovering in the air even when stunned or otherwise incapacitated.\",\n \"While in the form of a misty cloud, the target can't talk or manipulate objects, and any objects it was carrying or holding can't be dropped, used, or otherwise interacted with. The target can't attack or cast spells.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of gauze and a wisp of smoke.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/gaseous-form\"\n },\n {\n \"index\": \"gate\",\n \"name\": \"Gate\",\n \"desc\": [\n \"You conjure a portal linking an unoccupied space you can see within range to a precise location on a different plane of existence. The portal is a circular opening, which you can make 5 to 20 feet in diameter. You can orient the portal in any direction you choose. The portal lasts for the duration.\",\n \"The portal has a front and a back on each plane where it appears. Travel through the portal is possible only by moving through its front. Anything that does so is instantly transported to the other plane, appearing in the unoccupied space nearest to the portal.\",\n \"Deities and other planar rulers can prevent portals created by this spell from opening in their presence or anywhere within their domains.\",\n \"When you cast this spell, you can speak the name of a specific creature (a pseudonym, title, or nickname doesn't work). If that creature is on a plane other than the one you are on, the portal opens in the named creature's immediate vicinity and draws the creature through it to the nearest unoccupied space on your side of the portal. You gain no special power over the creature, and it is free to act as the GM deems appropriate. It might leave, attack you, or help you.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A diamond worth at least 5,000gp.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/gate\"\n },\n {\n \"index\": \"geas\",\n \"name\": \"Geas\",\n \"desc\": [\n \"You place a magical command on a creature that you can see within range, forcing it to carry out some service or refrain from some action or course of activity as you decide. If the creature can understand you, it must succeed on a wisdom saving throw or become charmed by you for the duration. While the creature is charmed by you, it takes 5d10 psychic damage each time it acts in a manner directly counter to your instructions, but no more than once each day. A creature that can't understand you is unaffected by the spell.\",\n \"You can issue any command you choose, short of an activity that would result in certain death. Should you issue a suicidal command, the spell ends.\",\n \"You can end the spell early by using an action to dismiss it. A remove curse, greater restoration, or wish spell also ends it.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th or 8th level, the duration is 1 year. When you cast this spell using a spell slot of 9th level, the spell lasts until it is ended by one of the spells mentioned above.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"30 days\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/geas\"\n },\n {\n \"index\": \"gentle-repose\",\n \"name\": \"Gentle Repose\",\n \"desc\": [\n \"You touch a corpse or other remains. For the duration, the target is protected from decay and can't become undead.\",\n \"The spell also effectively extends the time limit on raising the target from the dead, since days spent under the influence of this spell don't count against the time limit of spells such as raise dead.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of salt and one copper piece placed on each of the corpse's eyes, which must remain there for the duration.\",\n \"ritual\": true,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/gentle-repose\"\n },\n {\n \"index\": \"giant-insect\",\n \"name\": \"Giant Insect\",\n \"desc\": [\n \"You transform up to ten centipedes, three spiders, five wasps, or one scorpion within range into giant versions of their natural forms for the duration. A centipede becomes a giant centipede, a spider becomes a giant spider, a wasp becomes a giant wasp, and a scorpion becomes a giant scorpion.\",\n \"Each creature obeys your verbal commands, and in combat, they act on your turn each round. The GM has the statistics for these creatures and resolves their actions and movement.\",\n \"A creature remains in its giant size for the duration, until it drops to 0 hit points, or until you use an action to dismiss the effect on it.\",\n \"The GM might allow you to choose different targets. For example, if you transform a bee, its giant version might have the same statistics as a giant wasp.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/giant-insect\"\n },\n {\n \"index\": \"glibness\",\n \"name\": \"Glibness\",\n \"desc\": [\n \"Until the spell ends, when you make a Charisma check, you can replace the number you roll with a 15. Additionally, no matter what you say, magic that would determine if you are telling the truth indicates that you are being truthful.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/glibness\"\n },\n {\n \"index\": \"globe-of-invulnerability\",\n \"name\": \"Globe of Invulnerability\",\n \"desc\": [\n \"An immobile, faintly shimmering barrier springs into existence in a 10-foot radius around you and remains for the duration.\",\n \"Any spell of 5th level or lower cast from outside the barrier can't affect creatures or objects within it, even if the spell is cast using a higher level spell slot. Such a spell can target creatures and objects within the barrier, but the spell has no effect on them. Similarly, the area within the barrier is excluded from the areas affected by such spells.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the barrier blocks spells of one level higher for each slot level above 6th.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A glass or crystal bead that shatters when the spell ends.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/globe-of-invulnerability\"\n },\n {\n \"index\": \"glyph-of-warding\",\n \"name\": \"Glyph of Warding\",\n \"desc\": [\n \"When you cast this spell, you inscribe a glyph that harms other creatures, either upon a surface (such as a table or a section of floor or wall) or within an object that can be closed (such as a book, a scroll, or a treasure chest) to conceal the glyph. If you choose a surface, the glyph can cover an area of the surface no larger than 10 feet in diameter. If you choose an object, that object must remain in its place; if the object is moved more than 10 feet from where you cast this spell, the glyph is broken, and the spell ends without being triggered.\",\n \"The glyph is nearly invisible and requires a successful Intelligence (Investigation) check against your spell save DC to be found.\",\n \"You decide what triggers the glyph when you cast the spell. For glyphs inscribed on a surface, the most typical triggers include touching or standing on the glyph, removing another object covering the glyph, approaching within a certain distance of the glyph, or manipulating the object on which the glyph is inscribed. For glyphs inscribed within an object, the most common triggers include opening that object, approaching within a certain distance of the object, or seeing or reading the glyph. Once a glyph is triggered, this spell ends.\",\n \"You can further refine the trigger so the spell activates only under certain circumstances or according to physical characteristics (such as height or weight), creature kind (for example, the ward could be set to affect aberrations or drow), or alignment. You can also set conditions for creatures that don't trigger the glyph, such as those who say a certain password.\",\n \"When you inscribe the glyph, choose *explosive runes* or a *spell glyph*.\",\n \"***Explosive Runes.*** When triggered, the glyph erupts with magical energy in a 20-foot-radius sphere centered on the glyph. The sphere spreads around corners. Each creature in the area must make a Dexterity saving throw. A creature takes 5d8 acid, cold, fire, lightning, or thunder damage on a failed saving throw (your choice when you create the glyph), or half as much damage on a successful one.\",\n \"***Spell Glyph.*** You can store a prepared spell of 3rd level or lower in the glyph by casting it as part of creating the glyph. The spell must target a single creature or an area. The spell being stored has no immediate effect when cast in this way. When the glyph is triggered, the stored spell is cast. If the spell has a target, it targets the creature that triggered the glyph. If the spell affects an area, the area is centered on that creature. If the spell summons hostile creatures or creates harmful objects or traps, they appear as close as possible to the intruder and attack it. If the spell requires concentration, it lasts until the end of its full duration.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage of an explosive runes glyph increases by 1d8 for each slot level above 3rd. If you create a spell glyph, you can store any spell of up to the same level as the slot you use for the glyph of warding.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Incense and powdered diamond worth at least 200 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/glyph-of-warding\"\n },\n {\n \"index\": \"goodberry\",\n \"name\": \"Goodberry\",\n \"desc\": [\n \"Up to ten berries appear in your hand and are infused with magic for the duration. A creature can use its action to eat one berry. Eating a berry restores 1 hit point, and the berry provides enough nourishment to sustain a creature for a day.\",\n \"The berries lose their potency if they have not been consumed within 24 hours of the casting of this spell.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sprig of mistletoe.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/goodberry\"\n },\n {\n \"index\": \"grease\",\n \"name\": \"Grease\",\n \"desc\": [\n \"Slick grease covers the ground in a 10-foot square centered on a point within range and turns it into difficult terrain for the duration.\",\n \"When the grease appears, each creature standing in its area must succeed on a dexterity saving throw or fall prone. A creature that enters the area or ends its turn there must also succeed on a dexterity saving throw or fall prone.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of pork rind or butter.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/grease\"\n },\n {\n \"index\": \"greater-invisibility\",\n \"name\": \"Greater Invisibility\",\n \"desc\": [\n \"You or a creature you touch becomes invisible until the spell ends. Anything the target is wearing or carrying is invisible as long as it is on the target's person.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/greater-invisibility\"\n },\n {\n \"index\": \"greater-restoration\",\n \"name\": \"Greater Restoration\",\n \"desc\": [\n \"You imbue a creature you touch with positive energy to undo a debilitating effect. You can reduce the target's exhaustion level by one, or end one of the following effects on the target:\",\n \"- One effect that charmed or petrified the target\",\n \"- One curse, including the target's attunement to a cursed magic item\",\n \"- Any reduction to one of the target's ability scores\",\n \"- One effect reducing the target's hit point maximum\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Diamond dust worth at least 100gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/greater-restoration\"\n },\n {\n \"index\": \"guardian-of-faith\",\n \"name\": \"Guardian of Faith\",\n \"desc\": [\n \"A Large spectral guardian appears and hovers for the duration in an unoccupied space of your choice that you can see within range. The guardian occupies that space and is indistinct except for a gleaming sword and shield emblazoned with the symbol of your deity.\",\n \"Any creature hostile to you that moves to a space within 10 feet of the guardian for the first time on a turn must succeed on a dexterity saving throw. The creature takes 20 radiant damage on a failed save, or half as much damage on a successful one. The guardian vanishes when it has dealt a total of 60 damage.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"20\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/guardian-of-faith\"\n },\n {\n \"index\": \"guards-and-wards\",\n \"name\": \"Guards and Wards\",\n \"desc\": [\n \"You create a ward that protects up to 2,500 square feet of floor space (an area 50 feet square, or one hundred 5-foot squares or twenty-five 10-foot squares). The warded area can be up to 20 feet tall, and shaped as you desire. You can ward several stories of a stronghold by dividing the area among them, as long as you can walk into each contiguous area while you are casting the spell.\",\n \"When you cast this spell, you can specify individuals that are unaffected by any or all of the effects that you choose. You can also specify a password that, when spoken aloud, makes the speaker immune to these effects.\",\n \"Guards and wards creates the following effects within the warded area.\",\n \"***Corridors.*** Fog fills all the warded corridors, making them heavily obscured. In addition, at each intersection or branching passage offering a choice of direction, there is a 50 percent chance that a creature other than you will believe it is going in the opposite direction from the one it chooses.\",\n \"***Doors.*** All doors in the warded area are magically locked, as if sealed by an arcane lock spell. In addition, you can cover up to ten doors with an illusion (equivalent to the illusory object function of the minor illusion spell) to make them appear as plain sections of wall.\",\n \"***Stairs.*** Webs fill all stairs in the warded area from top to bottom, as the web spell. These strands regrow in 10 minutes if they are burned or torn away while guards and wards lasts.\",\n \"***Other Spell Effect.*** You can place your choice of one of the following magical effects within the warded area of the stronghold.\",\n \"- Place dancing lights in four corridors. You can designate a simple program that the lights repeat as long as guards and wards lasts.\",\n \"- Place magic mouth in two locations.\",\n \"- Place stinking cloud in two locations. The vapors appear in the places you designate; they return within 10 minutes if dispersed by wind while guards and wards lasts.\",\n \"- Place a constant gust of wind in one corridor or room.\",\n \"- Place a suggestion in one location. You select an area of up to 5 feet square, and any creature that enters or passes through the area receives the suggestion mentally.\",\n \"The whole warded area radiates magic. A dispel magic cast on a specific effect, if successful, removes only that effect.\",\n \"You can create a permanently guarded and warded structure by casting this spell there every day for one year.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Burning incense, a small measure of brimstone and oil, a knotted string, a small amount of umber hulk blood, and a small silver rod worth at least 10 gp.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 2500\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/guards-and-wards\"\n },\n {\n \"index\": \"guidance\",\n \"name\": \"Guidance\",\n \"desc\": [\n \"You touch one willing creature. Once before the spell ends, the target can roll a d4 and add the number rolled to one ability check of its choice. It can roll the die before or after making the ability check. The spell then ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/guidance\"\n },\n {\n \"index\": \"guiding-bolt\",\n \"name\": \"Guiding Bolt\",\n \"desc\": [\n \"A flash of light streaks toward a creature of your choice within range. Make a ranged spell attack against the target. On a hit, the target takes 4d6 radiant damage, and the next attack roll made against this target before the end of your next turn has advantage, thanks to the mystical dim light glittering on the target until then.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d6 for each slot level above 1st.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"4d6\",\n \"2\": \"5d6\",\n \"3\": \"6d6\",\n \"4\": \"7d6\",\n \"5\": \"8d6\",\n \"6\": \"9d6\",\n \"7\": \"10d6\",\n \"8\": \"11d6\",\n \"9\": \"12d6\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/guiding-bolt\"\n },\n {\n \"index\": \"gust-of-wind\",\n \"name\": \"Gust of Wind\",\n \"desc\": [\n \"A line of strong wind 60 feet long and 10 feet wide blasts from you in a direction you choose for the spell's duration. Each creature that starts its turn in the line must succeed on a strength saving throw or be pushed 15 feet away from you in a direction following the line.\",\n \"Any creature in the line must spend 2 feet of movement for every 1 foot it moves when moving closer to you.\",\n \"The gust disperses gas or vapor, and it extinguishes candles, torches, and similar unprotected flames in the area. It causes protected flames, such as those of lanterns, to dance wildly and has a 50 percent chance to extinguish them.\",\n \"As a bonus action on each of your turns before the spell ends, you can change the direction in which the line blasts from you.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A legume seed.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"str\",\n \"name\": \"STR\",\n \"url\": \"/api/ability-scores/str\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/gust-of-wind\"\n },\n {\n \"index\": \"hallow\",\n \"name\": \"Hallow\",\n \"desc\": [\n \"You touch a point and infuse an area around it with holy (or unholy) power. The area can have a radius up to 60 feet, and the spell fails if the radius includes an area already under the effect a hallow spell. The affected area is subject to the following effects.\",\n \"First, celestials, elementals, fey, fiends, and undead can't enter the area, nor can such creatures charm, frighten, or possess creatures within it. Any creature charmed, frightened, or possessed by such a creature is no longer charmed, frightened, or possessed upon entering the area. You can exclude one or more of those types of creatures from this effect.\",\n \"Second, you can bind an extra effect to the area. Choose the effect from the following list, or choose an effect offered by the GM. Some of these effects apply to creatures in the area; you can designate whether the effect applies to all creatures, creatures that follow a specific deity or leader, or creatures of a specific sort, such as ores or trolls. When a creature that would be affected enters the spell's area for the first time on a turn or starts its turn there, it can make a charisma saving throw. On a success, the creature ignores the extra effect until it leaves the area.\",\n \"***Courage.*** Affected creatures can't be frightened while in the area.\",\n \"***Darkness.*** Darkness fills the area. Normal light, as well as magical light created by spells of a lower level than the slot you used to cast this spell, can't illuminate the area.\",\n \"***Daylight.*** Bright light fills the area. Magical darkness created by spells of a lower level than the slot you used to cast this spell can't extinguish the light.\",\n \"***Energy Protection.*** Affected creatures in the area have resistance to one damage type of your choice, except for bludgeoning, piercing, or slashing.\",\n \"***Energy Vulnerability.*** Affected creatures in the area have vulnerability to one damage type of your choice, except for bludgeoning, piercing, or slashing.\",\n \"***Everlasting Rest.*** Dead bodies interred in the area can't be turned into undead.\",\n \"***Extradimensional Interference.*** Affected creatures can't move or travel using teleportation or by extradimensional or interplanar means.\",\n \"***Fear.*** Affected creatures are frightened while in the area.\",\n \"***Silence.*** No sound can emanate from within the area, and no sound can reach into it.\",\n \"***Tongues.*** Affected creatures can communicate with any other creature in the area, even if they don't share a common language.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Herbs, oils, and incense worth at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"24 hours\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/hallow\"\n },\n {\n \"index\": \"hallucinatory-terrain\",\n \"name\": \"Hallucinatory Terrain\",\n \"desc\": [\n \"You make natural terrain in a 150-foot cube in range look, sound, and smell like some other sort of natural terrain. Thus, open fields or a road can be made to resemble a swamp, hill, crevasse, or some other difficult or impassable terrain. A pond can be made to seem like a grassy meadow, a precipice like a gentle slope, or a rock-strewn gully like a wide and smooth road. Manufactured structures, equipment, and creatures within the area aren't changed in appearance.\",\n \"The tactile characteristics of the terrain are unchanged, so creatures entering the area are likely to see through the illusion. If the difference isn't obvious by touch, a creature carefully examining the illusion can attempt an Intelligence (Investigation) check against your spell save DC to disbelieve it. A creature who discerns the illusion for what it is, sees it as a vague image superimposed on the terrain.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A stone, a twig, and a bit of green plant.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 4,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 150\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/hallucinatory-terrain\"\n },\n {\n \"index\": \"harm\",\n \"name\": \"Harm\",\n \"desc\": [\n \"You unleash a virulent disease on a creature that you can see within range. The target must make a constitution saving throw. On a failed save, it takes 14d6 necrotic damage, or half as much damage on a successful save. The damage can't reduce the target's hit points below 1. If the target fails the saving throw, its hit point maximum is reduced for 1 hour by an amount equal to the necrotic damage it took. Any effect that removes a disease allows a creature's hit point maximum to return to normal before that time passes.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/harm\"\n },\n {\n \"index\": \"haste\",\n \"name\": \"Haste\",\n \"desc\": [\n \"Choose a willing creature that you can see within range. Until the spell ends, the target's speed is doubled, it gains a +2 bonus to AC, it has advantage on dexterity saving throws, and it gains an additional action on each of its turns. That action can be used only to take the Attack (one weapon attack only), Dash, Disengage, Hide, or Use an Object action.\",\n \"When the spell ends, the target can't move or take actions until after its next turn, as a wave of lethargy sweeps over it.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A shaving of licorice root.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/haste\"\n },\n {\n \"index\": \"heal\",\n \"name\": \"Heal\",\n \"desc\": [\n \"Choose a creature that you can see within range. A surge of positive energy washes through the creature, causing it to regain 70 hit points. This spell also ends blindness, deafness, and any diseases affecting the target. This spell has no effect on constructs or undead.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the amount of healing increases by 10 for each slot level above 6th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"heal_at_slot_level\": {\n \"6\": \"70\",\n \"7\": \"80\",\n \"8\": \"90\",\n \"9\": \"100\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/heal\"\n },\n {\n \"index\": \"healing-word\",\n \"name\": \"Healing Word\",\n \"desc\": [\n \"A creature of your choice that you can see within range regains hit points equal to 1d4 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the healing increases by 1d4 for each slot level above 1st.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"heal_at_slot_level\": {\n \"1\": \"1d4 + MOD\",\n \"2\": \"2d4 + MOD\",\n \"3\": \"3d4 + MOD\",\n \"4\": \"4d4 + MOD\",\n \"5\": \"5d4 + MOD\",\n \"6\": \"6d4 + MOD\",\n \"7\": \"7d4 + MOD\",\n \"8\": \"8d4 + MOD\",\n \"9\": \"9d4 + MOD\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/healing-word\"\n },\n {\n \"index\": \"heat-metal\",\n \"name\": \"Heat Metal\",\n \"desc\": [\n \"Choose a manufactured metal object, such as a metal weapon or a suit of heavy or medium metal armor, that you can see within range. You cause the object to glow red-hot. Any creature in physical contact with the object takes 2d8 fire damage when you cast the spell. Until the spell ends, you can use a bonus action on each of your subsequent turns to cause this damage again.\",\n \"If a creature is holding or wearing the object and takes the damage from it, the creature must succeed on a constitution saving throw or drop the object if it can. If it doesn't drop the object, it has disadvantage on attack rolls and ability checks until the start of your next turn.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage increases by 1d8 for each slot level above 2nd.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of iron and a flame.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d8\",\n \"3\": \"3d8\",\n \"4\": \"4d8\",\n \"5\": \"5d8\",\n \"6\": \"6d8\",\n \"7\": \"7d8\",\n \"8\": \"8d8\",\n \"9\": \"9d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"Can choose to not drop the object\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/heat-metal\"\n },\n {\n \"index\": \"hellish-rebuke\",\n \"name\": \"Hellish Rebuke\",\n \"desc\": [\n \"You point your finger, and the creature that damaged you is momentarily surrounded by hellish flames. The creature must make a dexterity saving throw. It takes 2d10 fire damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d10 for each slot level above 1st.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 reaction\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"2d10\",\n \"2\": \"3d10\",\n \"3\": \"4d10\",\n \"4\": \"5d10\",\n \"5\": \"6d10\",\n \"6\": \"7d10\",\n \"7\": \"8d10\",\n \"8\": \"9d10\",\n \"9\": \"10d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/hellish-rebuke\"\n },\n {\n \"index\": \"heroes-feast\",\n \"name\": \"Heroes' Feast\",\n \"desc\": [\n \"You bring forth a great feast, including magnificent food and drink. The feast takes 1 hour to consume and disappears at the end of that time, and the beneficial effects don't set in until this hour is over. Up to twelve other creatures can partake of the feast.\",\n \"A creature that partakes of the feast gains several benefits. The creature is cured of all diseases and poison, becomes immune to poison and being frightened, and makes all wisdom saving throws with advantage. Its hit point maximum also increases by 2d10, and it gains the same number of hit points. These benefits last for 24 hours.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A gem-encrusted bowl worth at least 1,000gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/heroes-feast\"\n },\n {\n \"index\": \"heroism\",\n \"name\": \"Heroism\",\n \"desc\": [\n \"A willing creature you touch is imbued with bravery. Until the spell ends, the creature is immune to being frightened and gains temporary hit points equal to your spellcasting ability modifier at the start of each of its turns. When the spell ends, the target loses any remaining temporary hit points from this spell.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/heroism\"\n },\n {\n \"index\": \"hideous-laughter\",\n \"name\": \"Hideous Laughter\",\n \"desc\": [\n \"A creature of your choice that you can see within range perceives everything as hilariously funny and falls into fits of laughter if this spell affects it. The target must succeed on a wisdom saving throw or fall prone, becoming incapacitated and unable to stand up for the duration. A creature with an Intelligence score of 4 or less isn't affected.\",\n \"At the end of each of its turns, and each time it takes damage, the target can make another wisdom saving throw. The target had advantage on the saving throw if it's triggered by damage. On a success, the spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Tiny tarts and a feather that is waved in the air.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/hideous-laughter\"\n },\n {\n \"index\": \"hold-monster\",\n \"name\": \"Hold Monster\",\n \"desc\": [\n \"Choose a creature you can see and reach. The target must make a saving throw of Wisdom or be paralyzed for the duration of the spell. This spell has no effect against the undead. At the end of each round, the target can make a new saving throw of Wisdom. If successful, the spell ends for the creature.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a level 6 or higher location, you can target an additional creature for each level of location beyond the fifth. The creatures must be within 30 feet o f each other when you target them.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small piece of iron.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/hold-monster\"\n },\n {\n \"index\": \"hold-person\",\n \"name\": \"Hold Person\",\n \"desc\": [\n \"Choose a humanoid that you can see within range. The target must succeed on a wisdom saving throw or be paralyzed for the duration. At the end of each of its turns, the target can make another wisdom saving throw. On a success, the spell ends on the target.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you can target one additional humanoid for each slot level above 2nd. The humanoids must be within 30 feet of each other when you target them.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small, straight piece of iron.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/hold-person\"\n },\n {\n \"index\": \"holy-aura\",\n \"name\": \"Holy Aura\",\n \"desc\": [\n \"Divine light washes out from you and coalesces in a soft radiance in a 30-foot radius around you. Creatures of your choice in that radius when you cast this spell shed dim light in a 5-foot radius and have advantage on all saving throws, and other creatures have disadvantage on attack rolls against them until the spell ends. In addition, when a fiend or an undead hits an affected creature with a melee attack, the aura flashes with brilliant light. The attacker must succeed on a constitution saving throw or be blinded until the spell ends.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny reliquary worth at least 1,000gp containing a sacred relic, such as a scrap of cloth from a saint's robe or a piece of parchment from a religious text.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/holy-aura\"\n },\n {\n \"index\": \"hunters-mark\",\n \"name\": \"Hunter's Mark\",\n \"desc\": [\n \"You choose a creature you can see within range and mystically mark it as your quarry. Until the spell ends, you deal an extra 1d6 damage to the target whenever you hit it with a weapon attack, and you have advantage on any Wisdom (Perception) or Wisdom (Survival) check you make to find it. If the target drops to 0 hit points before this spell ends, you can use a bonus action on a subsequent turn of yours to mark a new creature.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd or 4th level, you can maintain your concentration on the spell for up to 8 hours. When you use a spell slot of 5th level or higher, you can maintain your concentration on the spell for up to 24 hours.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/hunters-mark\"\n },\n {\n \"index\": \"hypnotic-pattern\",\n \"name\": \"Hypnotic Pattern\",\n \"desc\": [\n \"You create a twisting pattern of colors that weaves through the air inside a 30-foot cube within range. The pattern appears for a moment and vanishes. Each creature in the area who sees the pattern must make a wisdom saving throw. On a failed save, the creature becomes charmed for the duration. While charmed by this spell, the creature is incapacitated and has a speed of 0.\",\n \"The spell ends for an affected creature if it takes any damage or if someone else uses an action to shake the creature out of its stupor.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"S\", \"M\"],\n \"material\": \"A glowing stick of incense or a crystal vial filled with phosphorescent material.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, the creature becomes charmed for the duration.\"\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/hypnotic-pattern\"\n },\n {\n \"index\": \"ice-storm\",\n \"name\": \"Ice Storm\",\n \"desc\": [\n \"A hail of rock-hard ice pounds to the ground in a 20-foot-radius, 40-foot-high cylinder centered on a point within range. Each creature in the cylinder must make a dexterity saving throw. A creature takes 2d8 bludgeoning damage and 4d6 cold damage on a failed save, or half as much damage on a successful one.\",\n \"Hailstones turn the storm's area of effect into difficult terrain until the end of your next turn.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, the bludgeoning damage increases by 1d8 for each slot level above 4th.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of dust and a few drops of water.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"bludgeoning\",\n \"name\": \"Bludgeoning\",\n \"url\": \"/api/damage-types/bludgeoning\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"2d8 + 4d6\",\n \"5\": \"3d8 + 4d6\",\n \"6\": \"4d8 + 4d6\",\n \"7\": \"5d8 + 4d6\",\n \"8\": \"6d8 + 4d6\",\n \"9\": \"7d8 + 4d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/ice-storm\"\n },\n {\n \"index\": \"identify\",\n \"name\": \"Identify\",\n \"desc\": [\n \"You choose one object that you must touch throughout the casting of the spell. If it is a magic item or some other magic-imbued object, you learn its properties and how to use them, whether it requires attunement to use, and how many charges it has, if any. You learn whether any spells are affecting the item and what they are. If the item was created by a spell, you learn which spell created it.\",\n \"If you instead touch a creature throughout the casting, you learn what spells, if any, are currently affecting it.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pearl worth at least 100gp and an owl feather.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 1,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/identify\"\n },\n {\n \"index\": \"illusory-script\",\n \"name\": \"Illusory Script\",\n \"desc\": [\n \"You write on parchment, paper, or some other suitable writing material and imbue it with a potent illusion that lasts for the duration.\",\n \"To you and any creatures you designate when you cast the spell, the writing appears normal, written in your hand, and conveys whatever meaning you intended when you wrote the text. To all others, the writing appears as if it were written in an unknown or magical script that is unintelligible. Alternatively, you can cause the writing to appear to be an entirely different message, written in a different hand and language, though the language must be one you know.\",\n \"Should the spell be dispelled, the original script and the illusion both disappear.\",\n \"A creature with truesight can read the hidden message.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"S\", \"M\"],\n \"material\": \"A lead-based ink worth at least 10gp, which this spell consumes.\",\n \"ritual\": true,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 1,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/illusory-script\"\n },\n {\n \"index\": \"imprisonment\",\n \"name\": \"Imprisonment\",\n \"desc\": [\n \"You create a magical restraint to hold a creature that you can see within range. The target must succeed on a wisdom saving throw or be bound by the spell; if it succeeds, it is immune to this spell if you cast it again. While affected by this spell, the creature doesn't need to breathe, eat, or drink, and it doesn't age. Divination spells can't locate or perceive the target.\",\n \"When you cast the spell, you choose one of the following forms of imprisonment.\",\n \"***Burial.*** The target is entombed far beneath the earth in a sphere of magical force that is just large enough to contain the target. Nothing can pass through the sphere, nor can any creature teleport or use planar travel to get into or out of it.\",\n \"The special component for this version of the spell is a small mithral orb.\",\n \"***Chaining.*** Heavy chains, firmly rooted in the ground, hold the target in place. The target is restrained until the spell ends, and it can't move or be moved by any means until then.\",\n \"The special component for this version of the spell is a fine chain of precious metal.\",\n \"***Hedged Prison.*** The spell transports the target into a tiny demiplane that is warded against teleportation and planar travel. The demiplane can be a labyrinth, a cage, a tower, or any similar confined structure or area of your choice.\",\n \"The special component for this version of the spell is a miniature representation of the prison made from jade.\",\n \"***Minimus Containment.*** The target shrinks to a height of 1 inch and is imprisoned inside a gemstone or similar object. Light can pass through the gemstone normally (allowing the target to see out and other creatures to see in), but nothing else can pass through, even by means of teleportation or planar travel. The gemstone can't be cut or broken while the spell remains in effect.\",\n \"The special component for this version of the spell is a large, transparent gemstone, such as a corundum, diamond, or ruby.\",\n \"***Slumber.*** The target falls asleep and can't be awoken.\",\n \"The special component for this version of the spell consists of rare soporific herbs.\",\n \"***Ending the Spell.*** During the casting of the spell, in any of its versions, you can specify a condition that will cause the spell to end and release the target. The condition can be as specific or as elaborate as you choose, but the GM must agree that the condition is reasonable and has a likelihood of coming to pass. The conditions can be based on a creature's name, identity, or deity but otherwise must be based on observable actions or qualities and not based on intangibles such as level, class, or hit points.\",\n \"A dispel magic spell can end the spell only if it is cast as a 9th-level spell, targeting either the prison or the special component used to create it.\",\n \"You can use a particular special component to create only one prison at a time. If you cast the spell again using the same component, the target of the first casting is immediately freed from its binding.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A vellum depiction or a carved statuette in the likeness of the target, and a special component that varies according to the version of the spell you choose, worth at least 500gp per Hit Die of the target.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 9,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"If the creature succeeds, it is immune to this spell if you cast it again\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/imprisonment\"\n },\n {\n \"index\": \"incendiary-cloud\",\n \"name\": \"Incendiary Cloud\",\n \"desc\": [\n \"A swirling cloud of smoke shot through with white-hot embers appears in a 20-foot-radius sphere centered on a point within range. The cloud spreads around corners and is heavily obscured. It lasts for the duration or until a wind of moderate or greater speed (at least 10 miles per hour) disperses it.\",\n \"When the cloud appears, each creature in it must make a dexterity saving throw. A creature takes 10d8 fire damage on a failed save, or half as much damage on a successful one. A creature must also make this saving throw when it enters the spell's area for the first time on a turn or ends its turn there.\",\n \"The cloud moves 10 feet directly away from you in a direction that you choose at the start of each of your turns.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"8\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/incendiary-cloud\"\n },\n {\n \"index\": \"inflict-wounds\",\n \"name\": \"Inflict Wounds\",\n \"desc\": [\n \"Make a melee spell attack against a creature you can reach. On a hit, the target takes 3d10 necrotic damage.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d10 for each slot level above 1st.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"3d10\",\n \"2\": \"4d10\",\n \"3\": \"5d10\",\n \"4\": \"6d10\",\n \"5\": \"7d10\",\n \"6\": \"8d10\",\n \"7\": \"9d10\",\n \"8\": \"10d10\",\n \"9\": \"11d10\"\n }\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/inflict-wounds\"\n },\n {\n \"index\": \"insect-plague\",\n \"name\": \"Insect Plague\",\n \"desc\": [\n \"Swarming, biting locusts fill a 20-foot-radius sphere centered on a point you choose within range. The sphere spreads around corners. The sphere remains for the duration, and its area is lightly obscured. The sphere's area is difficult terrain.\",\n \"When the area appears, each creature in it must make a constitution saving throw. A creature takes 4d10 piercing damage on a failed save, or half as much damage on a successful one. A creature must also make this saving throw when it enters the spell's area for the first time on a turn or ends its turn there.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the damage increases by 1d10 for each slot level above 5th.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A few grains of sugar, some kernels of grain, and a smear of fat.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"piercing\",\n \"name\": \"Piercing\",\n \"url\": \"/api/damage-types/piercing\"\n },\n \"damage_at_slot_level\": {\n \"5\": \"4d10\",\n \"6\": \"5d10\",\n \"7\": \"6d10\",\n \"8\": \"7d10\",\n \"9\": \"8d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/insect-plague\"\n },\n {\n \"index\": \"instant-summons\",\n \"name\": \"Instant Summons\",\n \"desc\": [\n \"You touch an object weighing 10 pounds or less whose longest dimension is 6 feet or less. The spell leaves an invisible mark on its surface and invisibly inscribes the name of the item on the sapphire you use as the material component. Each time you cast this spell, you must use a different sapphire.\",\n \"At any time thereafter, you can use your action to speak the item's name and crush the sapphire. The item instantly appears in your hand regardless of physical or planar distances, and the spell ends.\",\n \"If another creature is holding or carrying the item, crushing the sapphire doesn't transport the item to you, but instead you learn who the creature possessing the object is and roughly where that creature is located at that moment.\",\n \"Dispel magic or a similar effect successfully applied to the sapphire ends this spell's effect.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sapphire worth 1,000 gp.\",\n \"ritual\": true,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/instant-summons\"\n },\n {\n \"index\": \"invisibility\",\n \"name\": \"Invisibility\",\n \"desc\": [\n \"A creature you touch becomes invisible until the spell ends. Anything the target is wearing or carrying is invisible as long as it is on the target's person. The spell ends for a target that attacks or casts a spell.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you can target one additional creature for each slot level above 2nd.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An eyelash encased in gum arabic.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/invisibility\"\n },\n {\n \"index\": \"irresistible-dance\",\n \"name\": \"Irresistible Dance\",\n \"desc\": [\n \"Choose one creature that you can see within range. The target begins a comic dance in place: shuffling, tapping its feet, and capering for the duration. Creatures that can't be charmed are immune to this spell.\",\n \"A dancing creature must use all its movement to dance without leaving its space and has disadvantage on dexterity saving throws and attack rolls. While the target is affected by this spell, other creatures have advantage on attack rolls against it. As an action, a dancing creature makes a wisdom saving throw to regain control of itself. On a successful save, the spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/irresistible-dance\"\n },\n {\n \"index\": \"jump\",\n \"name\": \"Jump\",\n \"desc\": [\n \"You touch a creature. The creature's jump distance is tripled until the spell ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A grasshopper's hind leg.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/jump\"\n },\n {\n \"index\": \"knock\",\n \"name\": \"Knock\",\n \"desc\": [\n \"Choose an object that you can see within range. The object can be a door, a box, a chest, a set of manacles, a padlock, or another object that contains a mundane or magical means that prevents access.\",\n \"A target that is held shut by a mundane lock or that is stuck or barred becomes unlocked, unstuck, or unbarred. If the object has multiple locks, only one of them is unlocked.\",\n \"If you choose a target that is held shut with arcane lock, that spell is suppressed for 10 minutes, during which time the target can be opened and shut normally.\",\n \"When you cast the spell, a loud knock, audible from as far away as 300 feet, emanates from the target object.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/knock\"\n },\n {\n \"index\": \"legend-lore\",\n \"name\": \"Legend Lore\",\n \"desc\": [\n \"Name or describe a person, place, or object. The spell brings to your mind a brief summary of the significant lore about the thing you named. The lore might consist of current tales, forgotten stories, or even secret lore that has never been widely known. If the thing you named isn't of legendary importance, you gain no information. The more information you already have about the thing, the more precise and detailed the information you receive is.\",\n \"The information you learn is accurate but might be couched in figurative language. For example, if you have a mysterious magic axe on hand the spell might yield this information: \\\"Woe to the evildoer whose hand touches the axe, for even the haft slices the hand of the evil ones. Only a true Child of Stone, lover and beloved of Moradin, may awaken the true powers of the axe, and only with the sacred word *Rudnogg* on the lips.\\\"\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Incense worth at least 250 gp, which the spell consumes, and four ivory strips worth at least 50 gp each.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 5,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/legend-lore\"\n },\n {\n \"index\": \"lesser-restoration\",\n \"name\": \"Lesser Restoration\",\n \"desc\": [\n \"You touch a creature and can end either one disease or one condition afflicting it. The condition can be blinded, deafened, paralyzed, or poisoned.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/lesser-restoration\"\n },\n {\n \"index\": \"levitate\",\n \"name\": \"Levitate\",\n \"desc\": [\n \"One creature or object of your choice that you can see within range rises vertically, up to 20 feet, and remains suspended there for the duration. The spell can levitate a target that weighs up to 500 pounds. An unwilling creature that succeeds on a constitution saving throw is unaffected.\",\n \"The target can move only by pushing or pulling against a fixed object or surface within reach (such as a wall or a ceiling), which allows it to move as if it were climbing. You can change the target's altitude by up to 20 feet in either direction on your turn. If you are the target, you can move up or down as part of your move. Otherwise, you can use your action to move the target, which must remain within the spell's range.\",\n \"When the spell ends, the target floats gently to the ground if it is still aloft.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Either a small leather loop or a piece of golden wire bent into a cup shape with a long shank on one end.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/levitate\"\n },\n {\n \"index\": \"light\",\n \"name\": \"Light\",\n \"desc\": [\n \"You touch one object that is no larger than 10 feet in any dimension. Until the spell ends, the object sheds bright light in a 20-foot radius and dim light for an additional 20 feet. The light can be colored as you like. Completely covering the object with something opaque blocks the light. The spell ends if you cast it again or dismiss it as an action.\",\n \"If you target an object held or worn by a hostile creature, that creature must succeed on a dexterity saving throw to avoid the spell.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A firefly or phosphorescent moss.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/light\"\n },\n {\n \"index\": \"lightning-bolt\",\n \"name\": \"Lightning Bolt\",\n \"desc\": [\n \"A stroke of lightning forming a line 100 feet long and 5 feet wide blasts out from you in a direction you choose. Each creature in the line must make a dexterity saving throw. A creature takes 8d6 lightning damage on a failed save, or half as much damage on a successful one.\",\n \"The lightning ignites flammable objects in the area that aren't being worn or carried.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d6 for each slot level above 3rd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fur and a rod of amber, crystal, or glass.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"lightning\",\n \"name\": \"Lightning\",\n \"url\": \"/api/damage-types/lightning\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"8d6\",\n \"4\": \"9d6\",\n \"5\": \"10d6\",\n \"6\": \"11d6\",\n \"7\": \"12d6\",\n \"8\": \"13d6\",\n \"9\": \"14d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/lightning-bolt\"\n },\n {\n \"index\": \"locate-animals-or-plants\",\n \"name\": \"Locate Animals or Plants\",\n \"desc\": [\n \"Describe or name a specific kind of beast or plant. Concentrating on the voice of nature in your surroundings, you learn the direction and distance to the closest creature or plant of that kind within 5 miles, if any are present.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fur from a bloodhound.\",\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/locate-animals-or-plants\"\n },\n {\n \"index\": \"locate-creature\",\n \"name\": \"Locate Creature\",\n \"desc\": [\n \"Describe or name a creature that is familiar to you. You sense the direction to the creature's location, as long as that creature is within 1,000 feet of you. If the creature is moving, you know the direction of its movement.\",\n \"The spell can locate a specific creature known to you, or the nearest creature of a specific kind (such as a human or a unicorn), so long as you have seen such a creature up close--within 30 feet--at least once. If the creature you described or named is in a different form, such as being under the effects of a polymorph spell, this spell doesn't locate the creature.\",\n \"This spell can't locate a creature if running water at least 10 feet wide blocks a direct path between you and the creature.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fur from a bloodhound.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/locate-creature\"\n },\n {\n \"index\": \"locate-object\",\n \"name\": \"Locate Object\",\n \"desc\": [\n \"Describe or name an object that is familiar to you. You sense the direction to the object's location, as long as that object is within 1,000 feet of you. If the object is in motion, you know the direction of its movement.\",\n \"The spell can locate a specific object known to you, as long as you have seen it up close--within 30 feet--at least once. Alternatively, the spell can locate the nearest object of a particular kind, such as a certain kind of apparel, jewelry, furniture, tool, or weapon.\",\n \"This spell can't locate an object if any thickness of lead, even a thin sheet, blocks a direct path between you and the object.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A forked twig.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/locate-object\"\n },\n {\n \"index\": \"longstrider\",\n \"name\": \"Longstrider\",\n \"desc\": [\n \"You touch a creature. The target's speed increases by 10 feet until the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, you can target one additional creature for each spell slot above 1st.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of dirt.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/longstrider\"\n },\n {\n \"index\": \"mage-armor\",\n \"name\": \"Mage Armor\",\n \"desc\": [\n \"You touch a willing creature who isn't wearing armor, and a protective magical force surrounds it until the spell ends. The target's base AC becomes 13 + its Dexterity modifier. The spell ends if the target dons armor or if you dismiss the spell as an action.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of cured leather.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/mage-armor\"\n },\n {\n \"index\": \"mage-hand\",\n \"name\": \"Mage Hand\",\n \"desc\": [\n \"A spectral, floating hand appears at a point you choose within range. The hand lasts for the duration or until you dismiss it as an action. The hand vanishes if it is ever more than 30 feet away from you or if you cast this spell again.\",\n \"You can use your action to control the hand. You can use the hand to manipulate an object, open an unlocked door or container, stow or retrieve an item from an open container, or pour the contents out of a vial. You can move the hand up to 30 feet each time you use it.\",\n \"The hand can't attack, activate magic items, or carry more than 10 pounds.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/mage-hand\"\n },\n {\n \"index\": \"magic-circle\",\n \"name\": \"Magic Circle\",\n \"desc\": [\n \"You create a 10-foot radius, 20-foot-tall cylinder of magical energy centered on a point on the ground that you can see within range. Glowing runes appear whetever the cylinder intersects with the floor or other surface.\",\n \"Choose one or more of the following types of creatures: celestials, elementals, fey, fiends, or undead. The circle affects a creature of the chosen type in the following ways:\",\n \"- The creature can't willingly enter the cylinder by nonmagical means. If the creature tries to use teleportation or interplanar travel to do so, it must first succeed on a charisma saving throw.\",\n \"- The creature has disadvantage on attack rolls against targets within the cylinder.\",\n \"- Targets within the cylinder can't be charmed, frightened, or possessed by the creature.\",\n \"When you cast this spell, you can elect to cause its magic to operate in the reverse direction, preventing a creature of the specified type from leaving the cylinder and protecting targets outside it.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the duration increases by 1 hour for each slot level above 3rd.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Holy water or powdered silver and iron worth at least 100 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 10\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"If the creature tries to use teleportation or interplanar travel to do so, it must first succeed on a Charisma saving throw.\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/magic-circle\"\n },\n {\n \"index\": \"magic-jar\",\n \"name\": \"Magic Jar\",\n \"desc\": [\n \"Your body falls into a catatonic state as your soul leaves it and enters the container you used for the spell's material component. While your soul inhabits the container, you are aware of your surroundings as if you were in the container's space. You can't move or use reactions. The only action you can take is to project your soul up to 100 feet out of the container, either returning to your living body (and ending the spell) or attempting to possess a humanoids body.\",\n \"You can attempt to possess any humanoid within 100 feet of you that you can see (creatures warded by a protection from evil and good or magic circle spell can't be possessed). The target must make a charisma saving throw. On a failure, your soul moves into the target's body, and the target's soul becomes trapped in the container. On a success, the target resists your efforts to possess it, and you can't attempt to possess it again for 24 hours.\",\n \"Once you possess a creature's body, you control it. Your game statistics are replaced by the statistics of the creature, though you retain your alignment and your Intelligence, Wisdom, and Charisma scores. You retain the benefit of your own class features. If the target has any class levels, you can't use any of its class features.\",\n \"Meanwhile, the possessed creature's soul can perceive from the container using its own senses, but it can't move or take actions at all.\",\n \"While possessing a body, you can use your action to return from the host body to the container if it is within 100 feet of you, returning the host creature's soul to its body. If the host body dies while you're in it, the creature dies, and you must make a charisma saving throw against your own spellcasting DC. On a success, you return to the container if it is within 100 feet of you. Otherwise, you die.\",\n \"If the container is destroyed or the spell ends, your soul immediately returns to your body. If your body is more than 100 feet away from you or if your body is dead when you attempt to return to it, you die. If another creature's soul is in the container when it is destroyed, the creature's soul returns to its body if the body is alive and within 100 feet. Otherwise, that creature dies.\",\n \"When the spell ends, the container is destroyed.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A gem, crystal, reliquary, or some other ornamental container worth at least 500 gp.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"On a failure, your soul moves into the target's body, and the target's soul becomes trapped in the container. On a success, the target resists your efforts to possess it, and you can't attempt to possess it again for 24 hours.\"\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/magic-jar\"\n },\n {\n \"index\": \"magic-missile\",\n \"name\": \"Magic Missile\",\n \"desc\": [\n \"You create three glowing darts of magical force. Each dart hits a creature of your choice that you can see within range. A dart deals 1d4 + 1 force damage to its target. The darts all strike simultaneously, and you can direct them to hit one creature or several.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the spell creates one more dart for each slot level above 1st.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"1d4 + 1\",\n \"2\": \"1d4 + 1\",\n \"3\": \"1d4 + 1\",\n \"4\": \"1d4 + 1\",\n \"5\": \"1d4 + 1\",\n \"6\": \"1d4 + 1\",\n \"7\": \"1d4 + 1\",\n \"8\": \"1d4 + 1\",\n \"9\": \"1d4 + 1\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/magic-missile\"\n },\n {\n \"index\": \"magic-mouth\",\n \"name\": \"Magic Mouth\",\n \"desc\": [\n \"You plant a message to an object in the range of the spell. The message is verbalized when the trigger conditions are met. Choose an object that you see, and that is not worn or carried by another creature. Then say the message, which should not exceed 25 words but listening can take up to 10 minutes. Finally, establish the circumstances that trigger the spell to deliver your message.\",\n \"When these conditions are satisfied, a magical mouth appears on the object and it articulates the message imitating your voice, the same tone used during implantation of the message. If the selected object has a mouth or something that approaches such as the mouth of a statue, the magic mouth come alive at this point, giving the illusion that the words come from the mouth of the object.\",\n \"When you cast this spell, you may decide that the spell ends when the message is delivered or it can persist and repeat the message whenever circumstances occur.\",\n \"The triggering circumstance can be as general or as detailed as you like, though it must be based on visual or audible conditions that occur within 30 feet of the object. For example, you could instruct the mouth to speak when any creature moves within 30 feet of the object or when a silver bell rings within 30 feet of it.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A honeycomb and jade dust of at least 10 inches, the spell consumes.\",\n \"ritual\": true,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/magic-mouth\"\n },\n {\n \"index\": \"magic-weapon\",\n \"name\": \"Magic Weapon\",\n \"desc\": [\n \"You touch a nonmagical weapon. Until the spell ends, that weapon becomes a magic weapon with a +1 bonus to attack rolls and damage rolls.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the bonus increases to +2. When you use a spell slot of 6th level or higher, the bonus increases to +3.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/magic-weapon\"\n },\n {\n \"index\": \"magnificent-mansion\",\n \"name\": \"Magnificent Mansion\",\n \"desc\": [\n \"You conjure an extradimensional dwelling in range that lasts for the duration. You choose where its one entrance is located. The entrance shimmers faintly and is 5 feet wide and 10 feet tall. You and any creature you designate when you cast the spell can enter the extradimensional dwelling as long as the portal remains open. You can open or close the portal if you are within 30 feet of it. While closed, the portal is invisible.\",\n \"Beyond the portal is a magnificent foyer with numerous chambers beyond. The atmosphere is clean, fresh, and warm.\",\n \"You can create any floor plan you like, but the space can't exceed 50 cubes, each cube being 10 feet on each side. The place is furnished and decorated as you choose. It contains sufficient food to serve a nine course banquet for up to 100 people. A staff of 100 near-transparent servants attends all who enter. You decide the visual appearance of these servants and their attire. They are completely obedient to your orders. Each servant can perform any task a normal human servant could perform, but they can't attack or take any action that would directly harm another creature. Thus the servants can fetch things, clean, mend, fold clothes, light fires, serve food, pour wine, and so on. The servants can go anywhere in the mansion but can't leave it. Furnishings and other objects created by this spell dissipate into smoke if removed from the mansion. When the spell ends, any creatures inside the extradimensional space are expelled into the open spaces nearest to the entrance.\"\n ],\n \"range\": \"300 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A miniature portal carved from ivory, a small piece of polished marble, and a tiny silver spoon, each item worth at least 5 gp.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/magnificent-mansion\"\n },\n {\n \"index\": \"major-image\",\n \"name\": \"Major Image\",\n \"desc\": [\n \"You create the image of an object, a creature, or some other visible phenomenon that is no larger than a 20-foot cube. The image appears at a spot that you can see within range and lasts for the duration. It seems completely real, including sounds, smells, and temperature appropriate to the thing depicted. You can't create sufficient heat or cold to cause damage, a sound loud enough to deal thunder damage or deafen a creature, or a smell that might sicken a creature (like a troglodyte's stench).\",\n \"As long as you are within range of the illusion, you can use your action to cause the image to move to any other spot within range. As the image changes location, you can alter its appearance so that its movements appear natural for the image. For example, if you create an image of a creature and move it, you can alter the image so that it appears to be walking. Similarly, you can cause the illusion to make different sounds at different times, even making it carry on a conversation, for example.\",\n \"Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image, and its other sensory qualities become faint to the creature.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the spell lasts until dispelled, without requiring your concentration.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fleece.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/major-image\"\n },\n {\n \"index\": \"mass-cure-wounds\",\n \"name\": \"Mass Cure Wounds\",\n \"desc\": [\n \"A wave of healing energy washes out from a point of your choice within range. Choose up to six creatures in a 30-foot-radius sphere centered on that point. Each target regains hit points equal to 3d8 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 6th level or higher, the healing increases by 1d8 for each slot level above 5th.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"heal_at_slot_level\": {\n \"5\": \"3d8 + MOD\",\n \"6\": \"4d8 + MOD\",\n \"7\": \"5d8 + MOD\",\n \"8\": \"6d8 + MOD\",\n \"9\": \"7d8 + MOD\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/mass-cure-wounds\"\n },\n {\n \"index\": \"mass-heal\",\n \"name\": \"Mass Heal\",\n \"desc\": [\n \"A flood of healing energy flows from you into injured creatures around you. You restore up to 700 hit points, divided as you choose among any number of creatures that you can see within range. Creatures healed by this spell are also cured of all diseases and any effect making them blinded or deafened. This spell has no effect on undead or constructs.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"heal_at_slot_level\": {\n \"9\": \"700\"\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mass-heal\"\n },\n {\n \"index\": \"mass-healing-word\",\n \"name\": \"Mass Healing Word\",\n \"desc\": [\n \"As you call out words of restoration, up to six creatures of your choice that you can see within range regain hit points equal to 1d4 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the healing increases by 1d4 for each slot level above 3rd.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 3,\n \"heal_at_slot_level\": {\n \"3\": \"1d4 + MOD\",\n \"4\": \"2d4 + MOD\",\n \"5\": \"3d4 + MOD\",\n \"6\": \"4d4 + MOD\",\n \"7\": \"5d4 + MOD\",\n \"8\": \"6d4 + MOD\",\n \"9\": \"7d4 + MOD\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/mass-healing-word\"\n },\n {\n \"index\": \"mass-suggestion\",\n \"name\": \"Mass Suggestion\",\n \"desc\": [\n \"You suggest a course of activity (limited to a sentence or two) and magically influence up to twelve creatures of your choice that you can see within range and that can hear and understand you. Creatures that can't be charmed are immune to this effect. The suggestion must be worded in such a manner as to make the course of action sound reasonable. Asking the creature to stab itself, throw itself onto a spear, immolate itself, or do some other obviously harmful act automatically negates the effect of the spell.\",\n \"Each target must make a wisdom saving throw. On a failed save, it pursues the course of action you described to the best of its ability. The suggested course of action can continue for the entire duration. If the suggested activity can be completed in a shorter time, the spell ends when the subject finishes what it was asked to do.\",\n \"You can also specify conditions that will trigger a special activity during the duration. For example, you might suggest that a group of soldiers give all their money to the first beggar they meet. If the condition isn't met before the spell ends, the activity isn't performed.\",\n \"If you or any of your companions damage a creature affected by this spell, the spell ends for that creature.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 7th-level spell slot, the duration is 10 days. When you use an 8th-level spell slot, the duration is 30 days. When you use a 9th-level spell slot, the duration is a year and a day.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A snake's tongue and either a bit of honeycomb or a drop of sweet oil.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mass-suggestion\"\n },\n {\n \"index\": \"maze\",\n \"name\": \"Maze\",\n \"desc\": [\n \"You banish a creature that you can see within range into a labyrinthine demiplane. The target remains there for the duration or until it escapes the maze.\",\n \"The target can use its action to attempt to escape. When it does so, it makes a DC 20 Intelligence check. If it succeeds, it escapes, and the spell ends (a minotaur or goristro demon automatically succeeds).\",\n \"When the spell ends, the target reappears in the space it left or, if that space is occupied, in the nearest unoccupied space.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/maze\"\n },\n {\n \"index\": \"meld-into-stone\",\n \"name\": \"Meld Into Stone\",\n \"desc\": [\n \"You step into a stone object or surface large enough to fully contain your body, melding yourself and all the equipment you carry with the stone for the duration. Using your movement, you step into the stone at a point you can touch. Nothing of your presence remains visible or otherwise detectable by nonmagical senses.\",\n \"While merged with the stone, you can't see what occurs outside it, and any Wisdom (Perception) checks you make to hear sounds outside it are made with disadvantage. You remain aware of the passage of time and can cast spells on yourself while merged in the stone. You can use your movement to leave the stone where you entered it, which ends the spell. You otherwise can't move.\",\n \"Minor physical damage to the stone doesn't harm you, but its partial destruction or a change in its shape (to the extent that you no longer fit within it) expels you and deals 6d6 bludgeoning damage to you. The stone's complete destruction (or transmutation into a different substance) expels you and deals 50 bludgeoning damage to you. If expelled, you fall prone in an unoccupied space closest to where you first entered.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/meld-into-stone\"\n },\n {\n \"index\": \"mending\",\n \"name\": \"Mending\",\n \"desc\": [\n \"This spell repairs a single break or tear in an object you touch, such as a broken key, a torn cloak, or a leaking wineskin. As long as the break or tear is no longer than 1 foot in any dimension, you mend it, leaving no trace of the former damage.\",\n \"This spell can physically repair a magic item or construct, but the spell can't restore magic to such an object.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Two lodestones.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/mending\"\n },\n {\n \"index\": \"message\",\n \"name\": \"Message\",\n \"desc\": [\n \"You point your finger toward a creature within range and whisper a message. The target (and only the target) hears the message and can reply in a whisper that only you can hear.\",\n \"You can cast this spell through solid objects if you are familiar with the target and know it is beyond the barrier. Magical silence, 1 foot of stone, 1 inch of common metal, a thin sheet of lead, or 3 feet of wood blocks the spell. The spell doesn't have to follow a straight line and can travel freely around corners or through openings.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A short piece of copper wire.\",\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/message\"\n },\n {\n \"index\": \"meteor-swarm\",\n \"name\": \"Meteor Swarm\",\n \"desc\": [\n \"Blazing orbs of fire plummet to the ground at four different points you can see within range. Each creature in a 40-foot-radius sphere centered on each point you choose must make a dexterity saving throw. The sphere spreads around corners. A creature takes 20d6 fire damage and 20d6 bludgeoning damage on a failed save, or half as much damage on a successful one. A creature in the area of more than one fiery burst is affected only once.\",\n \"The spell damages objects in the area and ignites flammable objects that aren't being worn or carried.\"\n ],\n \"range\": \"1 mile\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"9\": \"20d6 + 20d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/meteor-swarm\"\n },\n {\n \"index\": \"mind-blank\",\n \"name\": \"Mind Blank\",\n \"desc\": [\n \"Until the spell ends, one willing creature you touch is immune to psychic damage, any effect that would sense its emotions or read its thoughts, divination spells, and the charmed condition. The spell even foils wish spells and spells or effects of similar power used to affect the target's mind or to gain information about the target.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mind-blank\"\n },\n {\n \"index\": \"minor-illusion\",\n \"name\": \"Minor Illusion\",\n \"desc\": [\n \"You create a sound or an image of an object within range that lasts for the duration. The illusion also ends if you dismiss it as an action or cast this spell again.\",\n \"If you create a sound, its volume can range from a whisper to a scream. It can be your voice, someone else's voice, a lion's roar, a beating of drums, or any other sound you choose. The sound continues unabated throughout the duration, or you can make discrete sounds at different times before the spell ends.\",\n \"If you create an image of an object--such as a chair, muddy footprints, or a small chest--it must be no larger than a 5-foot cube. The image can't create sound, light, smell, or any other sensory effect. Physical interaction with the image reveals it to be an illusion, because things can pass through it.\",\n \"If a creature uses its action to examine the sound or image, the creature can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the illusion becomes faint to the creature.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"S\", \"M\"],\n \"material\": \"A bit of fleece.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/minor-illusion\"\n },\n {\n \"index\": \"mirage-arcane\",\n \"name\": \"Mirage Arcane\",\n \"desc\": [\n \"You make terrain in an area up to 1 mile square look, sound, smell, and even feel like some other sort of terrain. The terrain's general shape remains the same, however. Open fields or a road could be made to resemble a swamp, hill, crevasse, or some other difficult or impassable terrain. A pond can be made to seem like a grassy meadow, a precipice like a gentle slope, or a rock-strewn gully like a wide and smooth road.\",\n \"Similarly, you can alter the appearance of structures, or add them where none are present. The spell doesn't disguise, conceal, or add creatures.\",\n \"The illusion includes audible, visual, tactile, and olfactory elements, so it can turn clear ground into difficult terrain (or vice versa) or otherwise impede movement through the area. Any piece of the illusory terrain (such as a rock or stick) that is removed from the spell's area disappears immediately.\",\n \"Creatures with truesight can see through the illusion to the terrain's true form; however, all other elements of the illusion remain, so while the creature is aware of the illusion's presence, the creature can still physically interact with the illusion.\"\n ],\n \"range\": \"Sight\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 days\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 5280\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mirage-arcane\"\n },\n {\n \"index\": \"mirror-image\",\n \"name\": \"Mirror Image\",\n \"desc\": [\n \"Three illusory duplicates of yourself appear in your space. Until the spell ends, the duplicates move with you and mimic your actions, shifting position so it's impossible to track which image is real. You can use your action to dismiss the illusory duplicates.\",\n \"Each time a creature targets you with an attack during the spell's duration, roll a d20 to determine whether the attack instead targets one of your duplicates.\",\n \"If you have three duplicates, you must roll a 6 or higher to change the attack's target to a duplicate. With two duplicates, you must roll an 8 or higher. With one duplicate, you must roll an 11 or higher.\",\n \"A duplicate's AC equals 10 + your Dexterity modifier. If an attack hits a duplicate, the duplicate is destroyed. A duplicate can be destroyed only by an attack that hits it. It ignores all other damage and effects. The spell ends when all three duplicates are destroyed.\",\n \"A creature is unaffected by this spell if it can't see, if it relies on senses other than sight, such as blindsight, or if it can perceive illusions as false, as with truesight.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/mirror-image\"\n },\n {\n \"index\": \"mislead\",\n \"name\": \"Mislead\",\n \"desc\": [\n \"You become invisible at the same time that an illusory double of you appears where you are standing. The double lasts for the duration, but the invisibility ends if you attack or cast a spell.\",\n \"You can use your action to move your illusory double up to twice your speed and make it gesture, speak, and behave in whatever way you choose.\",\n \"You can see through its eyes and hear through its ears as if you were located where it is. On each of your turns as a bonus action, you can switch from using its senses to using your own, or back again. While you are using its senses, you are blinded and deafened in regard to your own surroundings.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/mislead\"\n },\n {\n \"index\": \"misty-step\",\n \"name\": \"Misty Step\",\n \"desc\": [\n \"Briefly surrounded by silvery mist, you teleport up to 30 feet to an unoccupied space that you can see.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/misty-step\"\n },\n {\n \"index\": \"modify-memory\",\n \"name\": \"Modify Memory\",\n \"desc\": [\n \"You attempt to reshape another creature's memories. One creature that you can see must make a wisdom saving throw. If you are fighting the creature, it has advantage on the saving throw. On a failed save, the target becomes charmed by you for the duration. The charmed target is incapacitated and unaware of its surroundings, though it can still hear you. If it takes any damage or is targeted by another spell, this spell ends, and none of the target's memories are modified.\",\n \"While this charm lasts, you can affect the target's memory of an event that it experienced within the last 24 hours and that lasted no more than 10 minutes. You can permanently eliminate all memory of the event, allow the target to recall the event with perfect clarity and exacting detail, change its memory of the details of the event, or create a memory of some other event.\",\n \"You must speak to the target to describe how its memories are affected, and it must be able to understand your language for the modified memories to take root. Its mind fills in any gaps in the details of your description. If the spell ends before you have finished describing the modified memories, the creature's memory isn't altered. Otherwise, the modified memories take hold when the spell ends.\",\n \"A modified memory doesn't necessarily affect how a creature behaves, particularly if the memory contradicts the creature's natural inclinations, alignment, or beliefs. An illogical modified memory, such as implanting a memory of how much the creature enjoyed dousing itself in acid, is dismissed, perhaps as a bad dream. The GM might deem a modified memory too nonsensical to affect a creature in a significant manner.\",\n \"A remove curse or greater restoration spell cast on the target restores the creature's true memory.\"\n ],\n \"higher_level\": [\n \"If you cast this spell using a spell slot of 6th level or higher, you can alter the target's memories of an event that took place up to 7 days ago (6th level), 30 days ago (7th level), 1 year ago (8th level), or any time in the creature's past (9th level).\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/modify-memory\"\n },\n {\n \"index\": \"moonbeam\",\n \"name\": \"Moonbeam\",\n \"desc\": [\n \"A silvery beam of pale light shines down in a 5-foot radius, 40-foot-high cylinder centered on a point within range. Until the spell ends, dim light fills the cylinder.\",\n \"When a creature enters the spell's area for the first time on a turn or starts its turn there, it is engulfed in ghostly flames that cause searing pain, and it must make a constitution saving throw. It takes 2d10 radiant damage on a failed save, or half as much damage on a successful one.\",\n \"A shapechanger makes its saving throw with disadvantage. If it fails, it also instantly reverts to its original form and can't assume a different form until it leaves the spell's light.\",\n \"On each of your turns after you cast this spell, you can use an action to move the beam 60 feet in any direction.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage increases by 1dl0 for each slot level above 2nd.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Several seeds of any moonseed plant and a piece of opalescent feldspar.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d10\",\n \"3\": \"3d10\",\n \"4\": \"4d10\",\n \"5\": \"5d10\",\n \"6\": \"6d10\",\n \"7\": \"7d10\",\n \"8\": \"8d10\",\n \"9\": \"9d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/moonbeam\"\n },\n {\n \"index\": \"move-earth\",\n \"name\": \"Move Earth\",\n \"desc\": [\n \"Choose an area of terrain no larger than 40 feet on a side within range. You can reshape dirt, sand, or clay in the area in any manner you choose for the duration. You can raise or lower the area's elevation, create or fill in a trench, erect or flatten a wall, or form a pillar. The extent of any such changes can't exceed half the area's largest dimension. So, if you affect a 40-foot square, you can create a pillar up to 20 feet high, raise or lower the square's elevation by up to 20 feet, dig a trench up to 20 feet deep, and so on. It takes 10 minutes for these changes to complete.\",\n \"At the end of every 10 minutes you spend concentrating on the spell, you can choose a new area of terrain to affect.\",\n \"Because the terrain's transformation occurs slowly, creatures in the area can't usually be trapped or injured by the ground's movement.\",\n \"This spell can't manipulate natural stone or stone construction. Rocks and structures shift to accommodate the new terrain. If the way you shape the terrain would make a structure unstable, it might collapse.\",\n \"Similarly, this spell doesn't directly affect plant growth. The moved earth carries any plants along with it.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An iron blade and a small bag containing a mixture of soils--clay, loam, and sand.\",\n \"ritual\": false,\n \"duration\": \"Up to 2 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/move-earth\"\n },\n {\n \"index\": \"nondetection\",\n \"name\": \"Nondetection\",\n \"desc\": [\n \"For the duration, you hide a target that you touch from divination magic. The target can be a willing creature or a place or an object no larger than 10 feet in any dimension. The target can't be targeted by any divination magic or perceived through magical scrying sensors.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of diamond dust worth 25 gp sprinkled over the target, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/nondetection\"\n },\n {\n \"index\": \"pass-without-trace\",\n \"name\": \"Pass Without Trace\",\n \"desc\": [\n \"A veil of shadows and silence radiates from you, masking you and your companions from detection. For the duration, each creature you choose within 30 feet of you (including you) has a +10 bonus to Dexterity (Stealth) checks and can't be tracked except by magical means. A creature that receives this bonus leaves behind no tracks or other traces of its passage.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Ashes from a burned leaf of mistletoe and a sprig of spruce.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/pass-without-trace\"\n },\n {\n \"index\": \"passwall\",\n \"name\": \"Passwall\",\n \"desc\": [\n \"A passage appears at a point of your choice that you can see on a wooden, plaster, or stone surface (such as a wall, a ceiling, or a floor) within range, and lasts for the duration. You choose the opening's dimensions: up to 5 feet wide, 8 feet tall, and 20 feet deep. The passage creates no instability in a structure surrounding it.\",\n \"When the opening disappears, any creatures or objects still in the passage created by the spell are safely ejected to an unoccupied space nearest to the surface on which you cast the spell.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of sesame seeds.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/passwall\"\n },\n {\n \"index\": \"phantasmal-killer\",\n \"name\": \"Phantasmal Killer\",\n \"desc\": [\n \"You tap into the nightmares of a creature you can see within range and create an illusory manifestation of its deepest fears, visible only to that creature. The target must make a wisdom saving throw. On a failed save, the target becomes frightened for the duration. At the start of each of the target's turns before the spell ends, the target must succeed on a wisdom saving throw or take 4d10 psychic damage. On a successful save, the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, the damage increases by 1d10 for each slot level above 4th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"psychic\",\n \"name\": \"Psychic\",\n \"url\": \"/api/damage-types/psychic\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"4d10\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/phantasmal-killer\"\n },\n {\n \"index\": \"phantom-steed\",\n \"name\": \"Phantom Steed\",\n \"desc\": [\n \"A Large quasi-real, horselike creature appears on the ground in an unoccupied space of your choice within range. You decide the creature's appearance, but it is equipped with a saddle, bit, and bridle. Any of the equipment created by the spell vanishes in a puff of smoke if it is carried more than 10 feet away from the steed.\",\n \"For the duration, you or a creature you choose can ride the steed. The creature uses the statistics for a riding horse, except it has a speed of 100 feet and can travel 10 miles in an hour, or 13 miles at a fast pace. When the spell ends, the steed gradually fades, giving the rider 1 minute to dismount. The spell ends if you use an action to dismiss it or if the steed takes any damage.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 3,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/phantom-steed\"\n },\n {\n \"index\": \"planar-ally\",\n \"name\": \"Planar Ally\",\n \"desc\": [\n \"You beseech an otherworldly entity for aid. The being must be known to you: a god, a primordial, a demon prince, or some other being of cosmic power. That entity sends a celestial, an elemental, or a fiend loyal to it to aid you, making the creature appear in an unoccupied space within range. If you know a specific creature's name, you can speak that name when you cast this spell to request that creature, though you might get a different creature anyway (GM's choice).\",\n \"When the creature appears, it is under no compulsion to behave in any particular way. You can ask the creature to perform a service in exchange for payment, but it isn't obliged to do so. The requested task could range from simple (fly us across the chasm, or help us fight a battle) to complex (spy on our enemies, or protect us during our foray into the dungeon). You must be able to communicate with the creature to bargain for its services.\",\n \"Payment can take a variety of forms. A celestial might require a sizable donation of gold or magic items to an allied temple, while a fiend might demand a living sacrifice or a gift of treasure. Some creatures might exchange their service for a quest undertaken by you.\",\n \"As a rule of thumb, a task that can be measured in minutes requires a payment worth 100 gp per minute. A task measured in hours requires 1,000 gp per hour. And a task measured in days (up to 10 days) requires 10,000 gp per day. The GM can adjust these payments based on the circumstances under which you cast the spell. If the task is aligned with the creature's ethos, the payment might be halved or even waived. Nonhazardous tasks typically require only half the suggested payment, while especially dangerous tasks might require a greater gift. Creatures rarely accept tasks that seem suicidal.\",\n \"After the creature completes the task, or when the agreed-upon duration of service expires, the creature returns to its home plane after reporting back to you, if appropriate to the task and if possible. If you are unable to agree on a price for the creature's service, the creature immediately returns to its home plane.\",\n \"A creature enlisted to join your group counts as a member of it, receiving a full share of experience points awarded.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/planar-ally\"\n },\n {\n \"index\": \"planar-binding\",\n \"name\": \"Planar Binding\",\n \"desc\": [\n \"With this spell, you attempt to bind a celestial, an elemental, a fey, or a fiend to your service. The creature must be within range for the entire casting of the spell. (Typically, the creature is first summoned into the center of an inverted magic circle in order to keep it trapped while this spell is cast.) At the completion of the casting, the target must make a charisma saving throw. On a failed save, it is bound to serve you for the duration. If the creature was summoned or created by another spell, that spell's duration is extended to match the duration of this spell.\",\n \"A bound creature must follow your instructions to the best of its ability. You might command the creature to accompany you on an adventure, to guard a location, or to deliver a message. The creature obeys the letter of your instructions, but if the creature is hostile to you, it strives to twist your words to achieve its own objectives. If the creature carries out your instructions completely before the spell ends, it travels to you to report this fact if you are on the same plane of existence. If you are on a different plane of existence, it returns to the place where you bound it and remains there until the spell ends.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of a higher level, the duration increases to 10 days with a 6th-level slot, to 30 days with a 7th-level slot, to 180 days with an 8th-level slot, and to a year and a day with a 9th-level spell slot.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A jewel worth at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/planar-binding\"\n },\n {\n \"index\": \"plane-shift\",\n \"name\": \"Plane Shift\",\n \"desc\": [\n \"You and up to eight willing creatures who link hands in a circle are transported to a different plane of existence. You can specify a target destination in general terms, such as the City of Brass on the Elemental Plane of Fire or the palace of Dispater on the second level of the Nine Hells, and you appear in or near that destination. If you are trying to reach the City of Brass, for example, you might arrive in its Street of Steel, before its Gate of Ashes, or looking at the city from across the Sea of Fire, at the GM's discretion.\",\n \"Alternatively, if you know the sigil sequence of a teleportation circle on another plane of existence, this spell can take you to that circle. If the teleportation circle is too small to hold all the creatures you transported, they appear in the closest unoccupied spaces next to the circle.\",\n \"You can use this spell to banish an unwilling creature to another plane. Choose a creature within your reach and make a melee spell attack against it. On a hit, the creature must make a charisma saving throw. If the creature fails this save, it is transported to a random location on the plane of existence you specify. A creature so transported must find its own way back to your current plane of existence.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A forked, metal rod worth at least 250 gp, attuned to a particular plane of existence.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"attack_type\": \"melee\",\n \"dc\": {\n \"dc_type\": {\n \"index\": \"cha\",\n \"name\": \"CHA\",\n \"url\": \"/api/ability-scores/cha\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"If the creature fails this save, it is transported to a random location on the plane of existence you specify. A creature so transported must find its own way back to your current plane of existence.\"\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/plane-shift\"\n },\n {\n \"index\": \"plant-growth\",\n \"name\": \"Plant Growth\",\n \"desc\": [\n \"This spell channels vitality into plants within a specific area. There are two possible uses for the spell, granting either immediate or long-term benefits.\",\n \"If you cast this spell using 1 action, choose a point within range. All normal plants in a 100-foot radius centered on that point become thick and overgrown. A creature moving through the area must spend 4 feet of movement for every 1 foot it moves.\",\n \"You can exclude one or more areas of any size within the spell's area from being affected.\",\n \"If you cast this spell over 8 hours, you enrich the land. All plants in a half-mile radius centered on a point within range become enriched for 1 year. The plants yield twice the normal amount of food when harvested.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/plant-growth\"\n },\n {\n \"index\": \"poison-spray\",\n \"name\": \"Poison Spray\",\n \"desc\": [\n \"You extend your hand toward a creature you can see within range and project a puff of noxious gas from your palm. The creature must succeed on a constitution saving throw or take 1d12 poison damage.\",\n \"This spell's damage increases by 1d12 when you reach 5th level (2d12), 11th level (3d12), and 17th level (4d12).\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"poison\",\n \"name\": \"Poison\",\n \"url\": \"/api/damage-types/poison\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d12\",\n \"5\": \"2d12\",\n \"11\": \"3d12\",\n \"17\": \"4d12\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/poison-spray\"\n },\n {\n \"index\": \"polymorph\",\n \"name\": \"Polymorph\",\n \"desc\": [\n \"This spell transforms a creature that you can see within range into a new form. An unwilling creature must make a wisdom saving throw to avoid the effect. A shapechanger automatically succeeds on this saving throw.\",\n \"The transformation lasts for the duration, or until the target drops to 0 hit points or dies. The new form can be any beast whose challenge rating is equal to or less than the target's (or the target's level, if it doesn't have a challenge rating). The target's game statistics, including mental ability scores, are replaced by the statistics of the chosen beast. It retains its alignment and personality.\",\n \"The target assumes the hit points of its new form. When it reverts to its normal form, the creature returns to the number of hit points it had before it transformed. If it reverts as a result of dropping to 0 hit points, any excess damage carries over to its normal form. As long as the excess damage doesn't reduce the creature's normal form to 0 hit points, it isn't knocked unconscious.\",\n \"The creature is limited in the actions it can perform by the nature of its new form, and it can't speak, cast spells, or take any other action that requires hands or speech.\",\n \"The target's gear melds into the new form. The creature can't activate, use, wield, or otherwise benefit from any of its equipment.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A caterpillar cocoon.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/polymorph\"\n },\n {\n \"index\": \"power-word-kill\",\n \"name\": \"Power Word Kill\",\n \"desc\": [\n \"You utter a word of power that can compel one creature you can see within range to die instantly. If the creature you choose has 100 hit points or fewer, it dies. Otherwise, the spell has no effect.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/power-word-kill\"\n },\n {\n \"index\": \"power-word-stun\",\n \"name\": \"Power Word Stun\",\n \"desc\": [\n \"You speak a word of power that can overwhelm the mind of one creature you can see within range, leaving it dumbfounded. If the target has 150 hit points or fewer, it is stunned. Otherwise, the spell has no effect.\",\n \"The stunned target must make a constitution saving throw at the end of each of its turns. On a successful save, this stunning effect ends.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/power-word-stun\"\n },\n {\n \"index\": \"prayer-of-healing\",\n \"name\": \"Prayer of Healing\",\n \"desc\": [\n \"Up to six creatures of your choice that you can see within range each regain hit points equal to 2d8 + your spellcasting ability modifier. This spell has no effect on undead or constructs.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the healing increases by 1d8 for each slot level above 2nd.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 2,\n \"heal_at_slot_level\": {\n \"2\": \"2d8 + MOD\",\n \"3\": \"3d8 + MOD\",\n \"4\": \"4d8 + MOD\",\n \"5\": \"5d8 + MOD\",\n \"6\": \"6d8 + MOD\",\n \"7\": \"7d8 + MOD\",\n \"8\": \"8d8 + MOD\",\n \"9\": \"9d8 + MOD\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/prayer-of-healing\"\n },\n {\n \"index\": \"prestidigitation\",\n \"name\": \"Prestidigitation\",\n \"desc\": [\n \"This spell is a minor magical trick that novice spellcasters use for practice. You create one of the following magical effects within 'range':\",\n \"You create an instantaneous, harmless sensory effect, such as a shower of sparks, a puff of wind, faint musical notes, or an odd odor.\",\n \"You instantaneously light or snuff out a candle, a torch, or a small campfire.\",\n \"You instantaneously clean or soil an object no larger than 1 cubic foot.\",\n \"You chill, warm, or flavor up to 1 cubic foot of nonliving material for 1 hour.\",\n \"You make a color, a small mark, or a symbol appear on an object or a surface for 1 hour.\",\n \"You create a nonmagical trinket or an illusory image that can fit in your hand and that lasts until the end of your next turn.\",\n \"If you cast this spell multiple times, you can have up to three of its non-instantaneous effects active at a time, and you can dismiss such an effect as an action.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/prestidigitation\"\n },\n {\n \"index\": \"prismatic-spray\",\n \"name\": \"Prismatic Spray\",\n \"desc\": [\n \"Eight multicolored rays of light flash from your hand. Each ray is a different color and has a different power and purpose. Each creature in a 60-foot cone must make a dexterity saving throw. For each target, roll a d8 to determine which color ray affects it.\",\n \"***1. Red.*** The target takes 10d6 fire damage on a failed save, or half as much damage on a successful one.\",\n \"***2. Orange.*** The target takes 10d6 acid damage on a failed save, or half as much damage on a successful one.\",\n \"***3. Yellow.*** The target takes 10d6 lightning damage on a failed save, or half as much damage on a successful one.\",\n \"***4. Green.*** The target takes 10d6 poison damage on a failed save, or half as much damage on a successful one.\",\n \"***5. Blue.*** The target takes 10d6 cold damage on a failed save, or half as much damage on a successful one.\",\n \"***6. Indigo.*** On a failed save, the target is restrained. It must then make a constitution saving throw at the end of each of its turns. If it successfully saves three times, the spell ends. If it fails its save three times, it permanently turns to stone and is subjected to the petrified condition. The successes and failures don't need to be consecutive; keep track of both until the target collects three of a kind.\",\n \"***7. Violet.*** On a failed save, the target is blinded. It must then make a wisdom saving throw at the start of your next turn. A successful save ends the blindness. If it fails that save, the creature is transported to another plane of existence of the GM's choosing and is no longer blinded. (Typically, a creature that is on a plane that isn't its home plane is banished home, while other creatures are usually cast into the Astral or Ethereal planes.)\",\n \"***8. Special.*** The target is struck by two rays. Roll twice more, rerolling any 8.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"damage\": {\n \"damage_at_slot_level\": {\n \"7\": \"10d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"For each target, roll a d8 to determine which color ray affects it.\"\n },\n \"area_of_effect\": {\n \"type\": \"cone\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/prismatic-spray\"\n },\n {\n \"index\": \"prismatic-wall\",\n \"name\": \"Prismatic Wall\",\n \"desc\": [\n \"A shimmering, multicolored plane of light forms a vertical opaque wall--up to 90 feet long, 30 feet high, and 1 inch thick--centered on a point you can see within range. Alternatively, you can shape the wall into a sphere up to 30 feet in diameter centered on a point you choose within range. The wall remains in place for the duration. If you position the wall so that it passes through a space occupied by a creature, the spell fails, and your action and the spell slot are wasted.\",\n \"The wall sheds bright light out to a range of 100 feet and dim light for an additional 100 feet. You and creatures you designate at the time you cast the spell can pass through and remain near the wall without harm. If another creature that can see the wall moves to within 20 feet of it or starts its turn there, the creature must succeed on a constitution saving throw or become blinded for 1 minute.\",\n \"The wall consists of seven layers, each with a different color. When a creature attempts to reach into or pass through the wall, it does so one layer at a time through all the wall's layers. As it passes or reaches through each layer, the creature must make a dexterity saving throw or be affected by that layer's properties as described below.\",\n \"The wall can be destroyed, also one layer at a time, in order from red to violet, by means specific to each layer. Once a layer is destroyed, it remains so for the duration of the spell. A rod of cancellation destroys a prismatic wall, but an antimagic field has no effect on it.\",\n \"***1. Red.*** The creature takes 10d6 fire damage on a failed save, or half as much damage on a successful one. While this layer is in place, nonmagical ranged attacks can't pass through the wall. The layer can be destroyed by dealing at least 25 cold damage to it.\",\n \"***2. Orange.*** The creature takes 10d6 acid damage on a failed save, or half as much damage on a successful one. While this layer is in place, magical ranged attacks can't pass through the wall. The layer is destroyed by a strong wind.\",\n \"***3. Yellow.*** The creature takes 10d6 lightning damage on a failed save, or half as much damage on a successful one. This layer can be destroyed by dealing at least 60 force damage to it.\",\n \"***4. Green.*** The creature takes 10d6 poison damage on a failed save, or half as much damage on a successful one. A passwall spell, or another spell of equal or greater level that can open a portal on a solid surface, destroys this layer.\",\n \"***5. Blue.*** The creature takes 10d6 cold damage on a failed save, or half as much damage on a successful one. This layer can be destroyed by dealing at least 25 fire damage to it.\",\n \"***6. Indigo.*** On a failed save, the creature is restrained. It must then make a constitution saving throw at the end of each of its turns. If it successfully saves three times, the spell ends. If it fails its save three times, it permanently turns to stone and is subjected to the petrified condition. The successes and failures don't need to be consecutive; keep track of both until the creature collects three of a kind.\",\n \"While this layer is in place, spells can't be cast through the wall. The layer is destroyed by bright light shed by a daylight spell or a similar spell of equal or higher level.\",\n \"***7. Violet.*** On a failed save, the creature is blinded. It must then make a wisdom saving throw at the start of your next turn. A successful save ends the blindness. If it fails that save, the creature is transported to another plane of the GM's choosing and is no longer blinded. (Typically, a creature that is on a plane that isn't its home plane is banished home, while other creatures are usually cast into the Astral or Ethereal planes.) This layer is destroyed by a dispel magic spell or a similar spell of equal or higher level that can end spells and magical effects.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 90\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/prismatic-wall\"\n },\n {\n \"index\": \"private-sanctum\",\n \"name\": \"Private Sanctum\",\n \"desc\": [\n \"You make an area within range magically secure. The area is a cube that can be as small as 5 feet to as large as 100 feet on each side. The spell lasts for the duration or until you use an action to dismiss it.\",\n \"When you cast the spell, you decide what sort of security the spell provides, choosing any or all of the following properties:\",\n \"- Sound can't pass through the barrier at the edge of the warded area.\",\n \"- The barrier of the warded area appears dark and foggy, preventing vision (including darkvision) through it.\",\n \"- Sensors created by divination spells can't appear inside the protected area or pass through the barrier at its perimeter.\",\n \"- Creatures in the area can't be targeted by divination spells.\",\n \"- Nothing can teleport into or out of the warded area.\",\n \"- Planar travel is blocked within the warded area.\",\n \"Casting this spell on the same spot every day for a year makes this effect permanent.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, you can increase the size of the cube by 100 feet for each slot level beyond 4th. Thus you could protect a cube that can be up to 200 feet on one side by using a spell slot of 5th level.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A thin sheet of lead, a piece of opaque glass, a wad of cotton or cloth, and powdered chrysolite.\",\n \"ritual\": false,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"10 minutes\",\n \"level\": 4,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 100\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/private-sanctum\"\n },\n {\n \"index\": \"produce-flame\",\n \"name\": \"Produce Flame\",\n \"desc\": [\n \"A flickering flame appears in your hand. The flame remains there for the duration and harms neither you nor your equipment. The flame sheds bright light in a 10-foot radius and dim light for an additional 10 feet. The spell ends if you dismiss it as an action or if you cast it again.\",\n \"You can also attack with the flame, although doing so ends the spell. When you cast this spell, or as an action on a later turn, you can hurl the flame at a creature within 30 feet of you. Make a ranged spell attack. On a hit, the target takes 1d8 fire damage.\",\n \"This spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/produce-flame\"\n },\n {\n \"index\": \"programmed-illusion\",\n \"name\": \"Programmed Illusion\",\n \"desc\": [\n \"You create an illusion of an object, a creature, or some other visible phenomenon within range that activates when a specific condition occurs. The illusion is imperceptible until then. It must be no larger than a 30-foot cube, and you decide when you cast the spell how the illusion behaves and what sounds it makes. This scripted performance can last up to 5 minutes.\",\n \"When the condition you specify occurs, the illusion springs into existence and performs in the manner you described. Once the illusion finishes performing, it disappears and remains dormant for 10 minutes. After this time, the illusion can be activated again.\",\n \"The triggering condition can be as general or as detailed as you like, though it must be based on visual or audible conditions that occur within 30 feet of the area. For example, you could create an illusion of yourself to appear and warn off others who attempt to open a trapped door, or you could set the illusion to trigger only when a creature says the correct word or phrase.\",\n \"Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image, and any noise it makes sounds hollow to the creature.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fleece and jade dust worth at least 25 gp.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/programmed-illusion\"\n },\n {\n \"index\": \"project-image\",\n \"name\": \"Project Image\",\n \"desc\": [\n \"You create an illusory copy of yourself that lasts for the duration. The copy can appear at any location within range that you have seen before, regardless of intervening obstacles. The illusion looks and sounds like you but is intangible. If the illusion takes any damage, it disappears, and the spell ends.\",\n \"You can use your action to move this illusion up to twice your speed, and make it gesture, speak, and behave in whatever way you choose. It mimics your mannerisms perfectly.\",\n \"You can see through its eyes and hear through its ears as if you were in its space. On your turn as a bonus action, you can switch from using its senses to using your own, or back again. While you are using its senses, you are blinded and deafened in regard to your own surroundings.\",\n \"Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image, and any noise it makes sounds hollow to the creature.\"\n ],\n \"range\": \"500 miles\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small replica of you made from materials worth at least 5 gp.\",\n \"ritual\": false,\n \"duration\": \"Up to 24 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/project-image\"\n },\n {\n \"index\": \"protection-from-energy\",\n \"name\": \"Protection From Energy\",\n \"desc\": [\n \"For the duration, the willing creature you touch has resistance to one damage type of your choice: acid, cold, fire, lightning, or thunder.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/protection-from-energy\"\n },\n {\n \"index\": \"protection-from-evil-and-good\",\n \"name\": \"Protection from Evil and Good\",\n \"desc\": [\n \"Until the spell ends, one willing creature you touch is protected against certain types of creatures: aberrations, celestials, elementals, fey, fiends, and undead.\",\n \"The protection grants several benefits. Creatures of those types have disadvantage on attack rolls against the target. The target also can't be charmed, frightened, or possessed by them. If the target is already charmed, frightened, or possessed by such a creature, the target has advantage on any new saving throw against the relevant effect.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Holy water or powdered silver and iron, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/protection-from-evil-and-good\"\n },\n {\n \"index\": \"protection-from-poison\",\n \"name\": \"Protection from Poison\",\n \"desc\": [\n \"You touch a creature. If it is poisoned, you neutralize the poison. If more than one poison afflicts the target, you neutralize one poison that you know is present, or you neutralize one at random.\",\n \"For the duration, the target has advantage on saving throws against being poisoned, and it has resistance to poison damage.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/protection-from-poison\"\n },\n {\n \"index\": \"purify-food-and-drink\",\n \"name\": \"Purify Food and Drink\",\n \"desc\": [\n \"All nonmagical food and drink within a 5-foot radius sphere centered on a point of your choice within range is purified and rendered free of poison and disease.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/purify-food-and-drink\"\n },\n {\n \"index\": \"raise-dead\",\n \"name\": \"Raise Dead\",\n \"desc\": [\n \"You return a dead creature you touch to life, provided that it has been dead no longer than 10 days. If the creature's soul is both willing and at liberty to rejoin the body, the creature returns to life with 1 hit point.\",\n \"This spell also neutralizes any poisons and cures nonmagical diseases that affected the creature at the time it died. This spell doesn't, however, remove magical diseases, curses, or similar effects; if these aren't first removed prior to casting the spell, they take effect when the creature returns to life. The spell can't return an undead creature to life.\",\n \"This spell closes all mortal wounds, but it doesn't restore missing body parts. If the creature is lacking body parts or organs integral for its survival--its head, for instance--the spell automatically fails.\",\n \"Coming back from the dead is an ordeal. The target takes a -4 penalty to all attack rolls, saving throws, and ability checks. Every time the target finishes a long rest, the penalty is reduced by 1 until it disappears.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A diamond worth at least 500gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 5,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/raise-dead\"\n },\n {\n \"index\": \"ray-of-enfeeblement\",\n \"name\": \"Ray of Enfeeblement\",\n \"desc\": [\n \"A black beam of enervating energy springs from your finger toward a creature within range. Make a ranged spell attack against the target. On a hit, the target deals only half damage with weapon attacks that use Strength until the spell ends.\",\n \"At the end of each of the target's turns, it can make a constitution saving throw against the spell. On a success, the spell ends.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\"\n },\n \"attack_type\": \"ranged\",\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/ray-of-enfeeblement\"\n },\n {\n \"index\": \"ray-of-frost\",\n \"name\": \"Ray of Frost\",\n \"desc\": [\n \"A frigid beam of blue-white light streaks toward a creature within range. Make a ranged spell attack against the target. On a hit, it takes 1d8 cold damage, and its speed is reduced by 10 feet until the start of your next turn.\",\n \"The spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"ranged\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"cold\",\n \"name\": \"Cold\",\n \"url\": \"/api/damage-types/cold\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/ray-of-frost\"\n },\n {\n \"index\": \"regenerate\",\n \"name\": \"Regenerate\",\n \"desc\": [\n \"You touch a creature and stimulate its natural healing ability. The target regains 4d8 + 15 hit points. For the duration of the spell, the target regains 1 hit point at the start of each of its turns (10 hit points each minute).\",\n \"The target's severed body members (fingers, legs, tails, and so on), if any, are restored after 2 minutes. If you have the severed part and hold it to the stump, the spell instantaneously causes the limb to knit to the stump.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A prayer wheel and holy water.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 7,\n \"heal_at_slot_level\": {\n \"7\": \"4d8 + 15\"\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/regenerate\"\n },\n {\n \"index\": \"reincarnate\",\n \"name\": \"Reincarnate\",\n \"desc\": [\n \"You touch a dead humanoid or a piece of a dead humanoid. Provided that the creature has been dead no longer than 10 days, the spell forms a new adult body for it and then calls the soul to enter that body. If the target's soul isn't free or willing to do so, the spell fails.\",\n \"The magic fashions a new body for the creature to inhabit, which likely causes the creature's race to change. The GM rolls a d 100 and consults the following table to determine what form the creature takes when restored to life, or the GM chooses a form.\",\n \"| d100 | Race |\",\n \"|---|---|\",\n \"| 01-04 | Dragonborn |\",\n \"| 05-13 | Dwarf, hill |\",\n \"| 14-21 | Dwarf, mountain |\",\n \"| 22-25 | Elf, dark |\",\n \"| 26-34 | Elf, high |\",\n \"| 35-42 | Elf, wood |\",\n \"| 43-46 | Gnome, forest |\",\n \"| 47-52 | Gnome, rock |\",\n \"| 53-56 | Half-elf |\",\n \"| 57-60 | Half-orc |\",\n \"| 61-68 | Halfling, lightfoot |\",\n \"| 69-76 | Halfling, stout |\",\n \"| 77-96 | Human |\",\n \"| 97-00 | Tiefling |\",\n \"The reincarnated creature recalls its former life and experiences. It retains the capabilities it had in its original form, except it exchanges its original race for the new one and changes its racial traits accordingly.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Rare oils and unguents worth at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 5,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/reincarnate\"\n },\n {\n \"index\": \"remove-curse\",\n \"name\": \"Remove Curse\",\n \"desc\": [\n \"At your touch, all curses affecting one creature or object end. If the object is a cursed magic item, its curse remains, but the spell breaks its owner's attunement to the object so it can be removed or discarded.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/remove-curse\"\n },\n {\n \"index\": \"resilient-sphere\",\n \"name\": \"Resilient Sphere\",\n \"desc\": [\n \"A sphere of shimmering force encloses a creature or object of Large size or smaller within range. An unwilling creature must make a dexterity saving throw. On a failed save, the creature is enclosed for the duration.\",\n \"Nothing--not physical objects, energy, or other spell effects--can pass through the barrier, in or out, though a creature in the sphere can breathe there. The sphere is immune to all damage, and a creature or object inside can't be damaged by attacks or effects originating from outside, nor can a creature inside the sphere damage anything outside it.\",\n \"The sphere is weightless and just large enough to contain the creature or object inside. An enclosed creature can use its action to push against the sphere's walls and thus roll the sphere at up to half the creature's speed. Similarly, the globe can be picked up and moved by other creatures.\",\n \"A disintegrate spell targeting the globe destroys it without harming anything inside it.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A hemispherical piece of clear crystal and a matching hemispherical piece of gum arabic.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/resilient-sphere\"\n },\n {\n \"index\": \"resistance\",\n \"name\": \"Resistance\",\n \"desc\": [\n \"You touch one willing creature. Once before the spell ends, the target can roll a d4 and add the number rolled to one saving throw of its choice. It can roll the die before or after making the saving throw. The spell then ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A miniature cloak.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/resistance\"\n },\n {\n \"index\": \"resurrection\",\n \"name\": \"Resurrection\",\n \"desc\": [\n \"You touch a dead creature that has been dead for no more than a century, that didn't die of old age, and that isn't undead. If its soul is free and willing, the target returns to life with all its hit points.\",\n \"This spell neutralizes any poisons and cures normal diseases afflicting the creature when it died. It doesn't, however, remove magical diseases, curses, and the like; if such effects aren't removed prior to casting the spell, they afflict the target on its return to life.\",\n \"This spell closes all mortal wounds and restores any missing body parts.\",\n \"Coming back from the dead is an ordeal. The target takes a -4 penalty to all attack rolls, saving throws, and ability checks. Every time the target finishes a long rest, the penalty is reduced by 1 until it disappears.\",\n \"Casting this spell to restore life to a creature that has been dead for one year or longer taxes you greatly. Until you finish a long rest, you can't cast spells again, and you have disadvantage on all attack rolls, ability checks, and saving throws.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A diamond worth at least 1,000gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 7,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/resurrection\"\n },\n {\n \"index\": \"reverse-gravity\",\n \"name\": \"Reverse Gravity\",\n \"desc\": [\n \"This spell reverses gravity in a 50-foot-radius, 100-foot high cylinder centered on a point within range. All creatures and objects that aren't somehow anchored to the ground in the area fall upward and reach the top of the area when you cast this spell. A creature can make a dexterity saving throw to grab onto a fixed object it can reach, thus avoiding the fall.\",\n \"If some solid object (such as a ceiling) is encountered in this fall, falling objects and creatures strike it just as they would during a normal downward fall. If an object or creature reaches the top of the area without striking anything, it remains there, oscillating slightly, for the duration.\",\n \"At the end of the duration, affected objects and creatures fall back down.\"\n ],\n \"range\": \"100 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A lodestone and iron filings.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"other\",\n \"desc\": \"A creature can make a dexterity saving throw to grab onto a fixed object it can reach, thus avoiding the fall.\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 50\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/reverse-gravity\"\n },\n {\n \"index\": \"revivify\",\n \"name\": \"Revivify\",\n \"desc\": [\n \"You touch a creature that has died within the last minute. That creature returns to life with 1 hit point. This spell can't return to life a creature that has died of old age, nor can it restore any missing body parts.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Diamonds worth 300gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/revivify\"\n },\n {\n \"index\": \"rope-trick\",\n \"name\": \"Rope Trick\",\n \"desc\": [\n \"You touch a length of rope that is up to 60 feet long. One end of the rope then rises into the air until the whole rope hangs perpendicular to the ground. At the upper end of the rope, an invisible entrance opens to an extradimensional space that lasts until the spell ends.\",\n \"The extradimensional space can be reached by climbing to the top of the rope. The space can hold as many as eight Medium or smaller creatures. The rope can be pulled into the space, making the rope disappear from view outside the space.\",\n \"Attacks and spells can't cross through the entrance into or out of the extradimensional space, but those inside can see out of it as if through a 3-foot-by-5-foot window centered on the rope.\",\n \"Anything inside the extradimensional space drops out when the spell ends.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Powdered corn extract and a twisted loop of parchment.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/rope-trick\"\n },\n {\n \"index\": \"sacred-flame\",\n \"name\": \"Sacred Flame\",\n \"desc\": [\n \"Flame-like radiance descends on a creature that you can see within range. The target must succeed on a dexterity saving throw or take 1d8 radiant damage. The target gains no benefit from cover for this saving throw.\",\n \"The spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/sacred-flame\"\n },\n {\n \"index\": \"sanctuary\",\n \"name\": \"Sanctuary\",\n \"desc\": [\n \"You ward a creature within range against attack. Until the spell ends, any creature who targets the warded creature with an attack or a harmful spell must first make a wisdom saving throw. On a failed save, the creature must choose a new target or lose the attack or spell. This spell doesn't protect the warded creature from area effects, such as the explosion of a fireball.\",\n \"If the warded creature makes an attack or casts a spell that affects an enemy creature, this spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small silver mirror.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/sanctuary\"\n },\n {\n \"index\": \"scorching-ray\",\n \"name\": \"Scorching Ray\",\n \"desc\": [\n \"You create three rays of fire and hurl them at targets within range. You can hurl them at one target or several.\",\n \"Make a ranged spell attack for each ray. On a hit, the target takes 2d6 fire damage.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, you create one additional ray for each slot level above 2nd.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"2d6\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/scorching-ray\"\n },\n {\n \"index\": \"scrying\",\n \"name\": \"Scrying\",\n \"desc\": [\n \"You can see and hear a particular creature you choose that is on the same plane of existence as you. The target must make a wisdom saving throw, which is modified by how well you know the target and the sort of physical connection you have to it. If a target knows you're casting this spell, it can fail the saving throw voluntarily if it wants to be observed.\",\n \"| Knowledge | Save Modifier |\",\n \"|---|---|\",\n \"| Secondhand (you have heard of the target) | +5 |\",\n \"| Firsthand (you have met the target) | +0 |\",\n \"| Familiar (you know the target well) | -5 |\",\n \"\",\n \"| Connection | Save Modifier |\",\n \"|---|---|\",\n \"| Likeness or picture | -2 |\",\n \"| Possession or garment | -4 |\",\n \"| Body part, lock of hair, bit of nail, or the like | -10 |\",\n \"On a successful save, the target isn't affected, and you can't use this spell against it again for 24 hours.\",\n \"On a failed save, the spell creates an invisible sensor within 10 feet of the target. You can see and hear through the sensor as if you were there. The sensor moves with the target, remaining within 10 feet of it for the duration. A creature that can see invisible objects sees the sensor as a luminous orb about the size of your fist.\",\n \"Instead of targeting a creature, you can choose a location you have seen before as the target of this spell. When you do, the sensor appears at that location and doesn't move.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A focus worth at least 1,000 gp, such as a crystal ball, a silver mirror, or a font filled with holy water.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"10 minutes\",\n \"level\": 5,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/scrying\"\n },\n {\n \"index\": \"secret-chest\",\n \"name\": \"Secret Chest\",\n \"desc\": [\n \"You hide a chest, and all its contents, on the Ethereal Plane. You must touch the chest and the miniature replica that serves as a material component for the spell. The chest can contain up to 12 cubic feet of nonliving material (3 feet by 2 feet by 2 feet).\",\n \"While the chest remains on the Ethereal Plane, you can use an action and touch the replica to recall the chest. It appears in an unoccupied space on the ground within 5 feet of you. You can send the chest back to the Ethereal Plane by using an action and touching both the chest and the replica.\",\n \"After 60 days, there is a cumulative 5 percent chance per day that the spell's effect ends. This effect ends if you cast this spell again, if the smaller replica chest is destroyed, or if you choose to end the spell as an action. If the spell ends and the larger chest is on the Ethereal Plane, it is irretrievably lost.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An exquisite chest, 3 feet by 2 feet by 2 feet, constructed from rare materials worth at least 5,000 gp, and a Tiny replica made from the same materials worth at least 50 gp.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/secret-chest\"\n },\n {\n \"index\": \"see-invisibility\",\n \"name\": \"See Invisibility\",\n \"desc\": [\n \"For the duration of the spell, you see invisible creatures and objects as if they were visible, and you can see through Ethereal. The ethereal objects and creatures appear ghostly translucent.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A dash of talc and a small amount of silver powder.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/see-invisibility\"\n },\n {\n \"index\": \"seeming\",\n \"name\": \"Seeming\",\n \"desc\": [\n \"This spell allows you to change the appearance of any number of creatures that you can see within range. You give each target you choose a new, illusory appearance. An unwilling target can make a charisma saving throw, and if it succeeds, it is unaffected by this spell.\",\n \"The spell disguises physical appearance as well as clothing, armor, weapons, and equipment. You can make each creature seem 1 foot shorter or taller and appear thin, fat, or in between. You can't change a target's body type, so you must choose a form that has the same basic arrangement of limbs. Otherwise, the extent of the illusion is up to you. The spell lasts for the duration, unless you use your action to dismiss it sooner.\",\n \"The changes wrought by this spell fail to hold up to physical inspection. For example, if you use this spell to add a hat to a creature's outfit, objects pass through the hat, and anyone who touches it would feel nothing or would feel the creature's head and hair. If you use this spell to appear thinner than you are, the hand of someone who reaches out to touch you would bump into you while it was seemingly still in midair.\",\n \"A creature can use its action to inspect a target and make an Intelligence (Investigation) check against your spell save DC. If it succeeds, it becomes aware that the target is disguised.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/seeming\"\n },\n {\n \"index\": \"sending\",\n \"name\": \"Sending\",\n \"desc\": [\n \"You send a short message of twenty-five words or less to a creature with which you are familiar. The creature hears the message in its mind, recognizes you as the sender if it knows you, and can answer in a like manner immediately. The spell enables creatures with Intelligence scores of at least 1 to understand the meaning of your message.\",\n \"You can send the message across any distance and even to other planes of existence, but if the target is on a different plane than you, there is a 5 percent chance that the message doesn't arrive.\"\n ],\n \"range\": \"Unlimited\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A short piece of fine copper wire.\",\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/sending\"\n },\n {\n \"index\": \"sequester\",\n \"name\": \"Sequester\",\n \"desc\": [\n \"By means of this spell, a willing creature or an object can be hidden away, safe from detection for the duration. When you cast the spell and touch the target, it becomes invisible and can't be targeted by divination spells or perceived through scrying sensors created by divination spells.\",\n \"If the target is a creature, it falls into a state of suspended animation. Time ceases to flow for it, and it doesn't grow older.\",\n \"You can set a condition for the spell to end early. The condition can be anything you choose, but it must occur or be visible within 1 mile of the target. Examples include \\\"after 1,000 years\\\" or \\\"when the tarrasque awakens.\\\" This spell also ends if the target takes any damage.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A powder composed of diamond, emerald, ruby, and sapphire dust worth at least 5,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/sequester\"\n },\n {\n \"index\": \"shapechange\",\n \"name\": \"Shapechange\",\n \"desc\": [\n \"You assume the form of a different creature for the duration. The new form can be of any creature with a challenge rating equal to your level or lower. The creature can't be a construct or an undead, and you must have seen the sort of creature at least once. You transform into an average example of that creature, one without any class levels or the Spellcasting trait.\",\n \"Your game statistics are replaced by the statistics of the chosen creature, though you retain your alignment and Intelligence, Wisdom, and Charisma scores. You also retain all of your skill and saving throw proficiencies, in addition to gaining those of the creature. If the creature has the same proficiency as you and the bonus listed in its statistics is higher than yours, use the creature's bonus in place of yours. You can't use any legendary actions or lair actions of the new form.\",\n \"You assume the hit points and Hit Dice of the new form. When you revert to your normal form, you return to the number of hit points you had before you transformed. If you revert as a result of dropping to 0 hit points, any excess damage carries over to your normal form. As long as the excess damage doesn't reduce your normal form to 0 hit points, you aren't knocked unconscious.\",\n \"You retain the benefit of any features from your class, race, or other source and can use them, provided that your new form is physically capable of doing so. You can't use any special senses you have (for example, darkvision) unless your new form also has that sense. You can only speak if the creature can normally speak.\",\n \"When you transform, you choose whether your equipment falls to the ground, merges into the new form, or is worn by it. Worn equipment functions as normal. The GM determines whether it is practical for the new form to wear a piece of equipment, based on the creature's shape and size. Your equipment doesn't change shape or size to match the new form, and any equipment that the new form can't wear must either fall to the ground or merge into your new form. Equipment that merges has no effect in that state.\",\n \"During this spell's duration, you can use your action to assume a different form following the same restrictions and rules for the original form, with one exception: if your new form has more hit points than your current one, your hit points remain at their current value.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A jade circlet worth at least 1,500 gp, which you must place on your head before you cast the spell.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/shapechange\"\n },\n {\n \"index\": \"shatter\",\n \"name\": \"Shatter\",\n \"desc\": [\n \"A sudden loud ringing noise, painfully intense, erupts from a point of your choice within range. Each creature in a 10-foot-radius sphere centered on that point must make a Constitution saving throw. A creature takes 3d8 thunder damage on a failed save, or half as much damage on a successful one. A creature made of inorganic material such as stone, crystal, or metal has disadvantage on this saving throw.\",\n \"A non-magical item that is not worn or carried also suffers damage if it is in the area of the spell.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a 3 or higher level spell slot, the damage of the spell increases by 1d8 for each level of higher spell slot 2.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A burst of mica.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"thunder\",\n \"name\": \"Thunder\",\n \"url\": \"/api/damage-types/thunder\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"3d8\",\n \"3\": \"4d8\",\n \"4\": \"5d8\",\n \"5\": \"6d8\",\n \"6\": \"7d8\",\n \"7\": \"8d8\",\n \"8\": \"9d8\",\n \"9\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shatter\"\n },\n {\n \"index\": \"shield\",\n \"name\": \"Shield\",\n \"desc\": [\n \"An invisible barrier of magical force appears and protects you. Until the start of your next turn, you have a +5 bonus to AC, including against the triggering attack, and you take no damage from magic missile.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 reaction\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shield\"\n },\n {\n \"index\": \"shield-of-faith\",\n \"name\": \"Shield of Faith\",\n \"desc\": [\n \"A shimmering field appears and surrounds a creature of your choice within range, granting it a +2 bonus to AC for the duration.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small parchment with a bit of holy text written on it.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 bonus action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shield-of-faith\"\n },\n {\n \"index\": \"shillelagh\",\n \"name\": \"Shillelagh\",\n \"desc\": [\n \"The wood of a club or a quarterstaff you are holding is imbued with nature's power. For the duration, you can use your spellcasting ability instead of Strength for the attack and damage rolls of melee attacks using that weapon, and the weapon's damage die becomes a d8. The weapon also becomes magical, if it isn't already. The spell ends if you cast it again or if you let go of the weapon.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Mistletoe, a shamrock leaf, and a club or quarterstaff.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shillelagh\"\n },\n {\n \"index\": \"shocking-grasp\",\n \"name\": \"Shocking Grasp\",\n \"desc\": [\n \"Lightning springs from your hand to deliver a shock to a creature you try to touch. Make a melee spell attack against the target. You have advantage on the attack roll if the target is wearing armor made of metal. On a hit, the target takes 1d8 lightning damage, and it can't take reactions until the start of its next turn.\",\n \"The spell's damage increases by 1d8 when you reach 5th level (2d8), 11th level (3d8), and 17th level (4d8).\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"lightning\",\n \"name\": \"Lightning\",\n \"url\": \"/api/damage-types/lightning\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d8\",\n \"5\": \"2d8\",\n \"11\": \"3d8\",\n \"17\": \"4d8\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/shocking-grasp\"\n },\n {\n \"index\": \"silence\",\n \"name\": \"Silence\",\n \"desc\": [\n \"For the duration, no sound can be created within or pass through a 20-foot-radius sphere centered on a point you choose within range. Any creature or object entirely inside the sphere is immune to thunder damage, and creatures are deafened while entirely inside it.\",\n \"Casting a spell that includes a verbal component is impossible there.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/silence\"\n },\n {\n \"index\": \"silent-image\",\n \"name\": \"Silent Image\",\n \"desc\": [\n \"You create the image of an object, a creature, or some other visible phenomenon that is no larger than a 15-foot cube. The image appears at a spot within range and lasts for the duration. The image is purely visual; it isn't accompanied by sound, smell, or other sensory effects.\",\n \"You can use your action to cause the image to move to any spot within range. As the image changes location, you can alter its appearance so that its movements appear natural for the image. For example, if you create an image of a creature and move it, you can alter the image so that it appears to be walking.\",\n \"Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of fleece.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/silent-image\"\n },\n {\n \"index\": \"simulacrum\",\n \"name\": \"Simulacrum\",\n \"desc\": [\n \"You shape an illusory duplicate of one beast or humanoid that is within range for the entire casting time of the spell. The duplicate is a creature, partially real and formed from ice or snow, and it can take actions and otherwise be affected as a normal creature. It appears to be the same as the original, but it has half the creature's hit point maximum and is formed without any equipment. Otherwise, the illusion uses all the statistics of the creature it duplicates.\",\n \"The simulacrum is friendly to you and creatures you designate. It obeys your spoken commands, moving and acting in accordance with your wishes and acting on your turn in combat. The simulacrum lacks the ability to learn or become more powerful, so it never increases its level or other abilities, nor can it regain expended spell slots.\",\n \"If the simulacrum is damaged, you can repair it in an alchemical laboratory, using rare herbs and minerals worth 100 gp per hit point it regains. The simulacrum lasts until it drops to 0 hit points, at which point it reverts to snow and melts instantly.\",\n \"If you cast this spell again, any currently active duplicates you created with this spell are instantly destroyed.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Snow or ice in quantities sufficient to made a life-size copy of the duplicated creature; some hair, fingernail clippings, or other piece of that creature's body placed inside the snow or ice; and powdered ruby worth 1,500 gp, sprinkled over the duplicate and consumed by the spell.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"12 hours\",\n \"level\": 7,\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/simulacrum\"\n },\n {\n \"index\": \"sleep\",\n \"name\": \"Sleep\",\n \"desc\": [\n \"This spell sends creatures into a magical slumber. Roll 5d8; the total is how many hit points of creatures this spell can affect. Creatures within 20 feet of a point you choose within range are affected in ascending order of their current hit points (ignoring unconscious creatures).\",\n \"Starting with the creature that has the lowest current hit points, each creature affected by this spell falls unconscious until the spell ends, the sleeper takes damage, or someone uses an action to shake or slap the sleeper awake. Subtract each creature's hit points from the total before moving on to the creature with the next lowest hit points. A creature's hit points must be equal to or less than the remaining total for that creature to be affected.\",\n \"Undead and creatures immune to being charmed aren't affected by this spell.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, roll an additional 2d8 for each slot level above 1st.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of fine sand, rose petals, or a cricket.\",\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"damage\": {\n \"damage_at_slot_level\": {\n \"1\": \"5d8\"\n }\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/sleep\"\n },\n {\n \"index\": \"sleet-storm\",\n \"name\": \"Sleet Storm\",\n \"desc\": [\n \"Until the spell ends, freezing rain and sleet fall in a 20-foot-tall cylinder with a 40-foot radius centered on a point you choose within range. The area is heavily obscured, and exposed flames in the area are doused.\",\n \"The ground in the area is covered with slick ice, making it difficult terrain. When a creature enters the spell's area for the first time on a turn or starts its turn there, it must make a dexterity saving throw. On a failed save, it falls prone.\",\n \"If a creature is concentrating in the spell's area, the creature must make a successful constitution saving throw against your spell save DC or lose concentration.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of dust and a few drops of water.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/sleet-storm\"\n },\n {\n \"index\": \"slow\",\n \"name\": \"Slow\",\n \"desc\": [\n \"You alter time around up to six creatures of your choice in a 40-foot cube within range. Each target must succeed on a wisdom saving throw or be affected by this spell for the duration.\",\n \"An affected target's speed is halved, it takes a -2 penalty to AC and dexterity saving throws, and it can't use reactions. On its turn, it can use either an action or a bonus action, not both. Regardless of the creature's abilities or magic items, it can't make more than one melee or ranged attack during its turn.\",\n \"If the creature attempts to cast a spell with a casting time of 1 action, roll a d20. On an 11 or higher, the spell doesn't take effect until the creature's next turn, and the creature must use its action on that turn to complete the spell. If it can't, the spell is wasted.\",\n \"A creature affected by this spell makes another wisdom saving throw at the end of its turn. On a successful save, the effect ends for it.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of molasses.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On failed save, the creature is slowed.\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 40\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/slow\"\n },\n {\n \"index\": \"spare-the-dying\",\n \"name\": \"Spare the Dying\",\n \"desc\": [\n \"You touch a living creature that has 0 hit points. The creature becomes stable. This spell has no effect on undead or constructs.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/spare-the-dying\"\n },\n {\n \"index\": \"speak-with-animals\",\n \"name\": \"Speak with Animals\",\n \"desc\": [\n \"You gain the ability to comprehend and verbally communicate with beasts for the duration. The knowledge and awareness of many beasts is limited by their intelligence, but at a minimum, beasts can give you information about nearby locations and monsters, including whatever they can perceive or have perceived within the past day. You might be able to persuade a beast to perform a small favor for you, at the GM's discretion.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": true,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/speak-with-animals\"\n },\n {\n \"index\": \"speak-with-dead\",\n \"name\": \"Speak with Dead\",\n \"desc\": [\n \"You grant the semblance of life and intelligence to a corpse of your choice within range, allowing it to answer the questions you pose. The corpse must still have a mouth and can't be undead. The spell fails if the corpse was the target of this spell within the last 10 days.\",\n \"Until the spell ends, you can ask the corpse up to five questions. The corpse knows only what it knew in life, including the languages it knew. Answers are usually brief, cryptic, or repetitive, and the corpse is under no compulsion to offer a truthful answer if you are hostile to it or it recognizes you as an enemy. This spell doesn't return the creature's soul to its body, only its animating spirit. Thus, the corpse can't learn new information, doesn't comprehend anything that has happened since it died, and can't speculate about future events.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Burning incense.\",\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/speak-with-dead\"\n },\n {\n \"index\": \"speak-with-plants\",\n \"name\": \"Speak with Plants\",\n \"desc\": [\n \"You imbue plants within 30 feet of you with limited sentience and animation, giving them the ability to communicate with you and follow your simple commands. You can question plants about events in the spell's area within the past day, gaining information about creatures that have passed, weather, and other circumstances.\",\n \"You can also turn difficult terrain caused by plant growth (such as thickets and undergrowth) into ordinary terrain that lasts for the duration. Or you can turn ordinary terrain where plants are present into difficult terrain that lasts for the duration, causing vines and branches to hinder pursuers, for example.\",\n \"Plants might be able to perform other tasks on your behalf, at the GM's discretion. The spell doesn't enable plants to uproot themselves and move about, but they can freely move branches, tendrils, and stalks.\",\n \"If a plant creature is in the area, you can communicate with it as if you shared a common language, but you gain no magical ability to influence it.\",\n \"This spell can cause the plants created by the entangle spell to release a restrained creature.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/speak-with-plants\"\n },\n {\n \"index\": \"spider-climb\",\n \"name\": \"Spider Climb\",\n \"desc\": [\n \"Until the spell ends, one willing creature you touch gains the ability to move up, down, and across vertical surfaces and upside down along ceilings, while leaving its hands free. The target also gains a climbing speed equal to its walking speed.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of bitumen and a spider.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/spider-climb\"\n },\n {\n \"index\": \"spike-growth\",\n \"name\": \"Spike Growth\",\n \"desc\": [\n \"The ground in a 20-foot radius centered on a point within range twists and sprouts hard spikes and thorns. The area becomes difficult terrain for the duration. When a creature moves into or within the area, it takes 2d4 piercing damage for every 5 feet it travels.\",\n \"The transformation of the ground is camouflaged to look natural. Any creature that can't see the area at the time the spell is cast can make a Wisdom (Perception) check against your spell save DC to recognize the terrain as hazardous before entering it.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Seven sharp thorns or seven small twigs, each sharpened to a point.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/spike-growth\"\n },\n {\n \"index\": \"spirit-guardians\",\n \"name\": \"Spirit Guardians\",\n \"desc\": [\n \"You call forth spirits to protect you. They flit around you to a distance of 15 feet for the duration. If you are good or neutral, their spectral form appears angelic or fey (your choice). If you are evil, they appear fiendish.\",\n \"When you cast this spell, you can designate any number of creatures you can see to be unaffected by it. An affected creature's speed is halved in the area, and when the creature enters the area for the first time on a turn or starts its turn there, it must make a wisdom saving throw. On a failed save, the creature takes 3d8 radiant damage (if you are good or neutral) or 3d8 necrotic damage (if you are evil). On a successful save, the creature takes half as much damage.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d8 for each slot level above 3rd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A holy symbol.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/spirit-guardians\"\n },\n {\n \"index\": \"spiritual-weapon\",\n \"name\": \"Spiritual Weapon\",\n \"desc\": [\n \"You create a floating, spectral weapon within range that lasts for the duration or until you cast this spell again. When you cast the spell, you can make a melee spell attack against a creature within 5 feet of the weapon. On a hit, the target takes force damage equal to 1d8 + your spellcasting ability modifier.\",\n \"As a bonus action on your turn, you can move the weapon up to 20 feet and repeat the attack against a creature within 5 feet of it.\",\n \"The weapon can take whatever form you choose. Clerics of deities who are associated with a particular weapon (as St. Cuthbert is known for his mace and Thor for his hammer) make this spell's effect resemble that weapon.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 3rd level or higher, the damage increases by 1d8 for every two slot levels above the 2nd.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 bonus action\",\n \"level\": 2,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"force\",\n \"name\": \"Force\",\n \"url\": \"/api/damage-types/force\"\n },\n \"damage_at_slot_level\": {\n \"2\": \"1d8 + MOD\",\n \"3\": \"1d8 + MOD\",\n \"4\": \"2d8 + MOD\",\n \"5\": \"2d8 + MOD\",\n \"6\": \"3d8 + MOD\",\n \"7\": \"3d8 + MOD\",\n \"8\": \"4d8 + MOD\",\n \"9\": \"4d8 + MOD\"\n }\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"life\",\n \"name\": \"Life\",\n \"url\": \"/api/subclasses/life\"\n }\n ],\n \"url\": \"/api/spells/spiritual-weapon\"\n },\n {\n \"index\": \"stinking-cloud\",\n \"name\": \"Stinking Cloud\",\n \"desc\": [\n \"You create a 20-foot-radius sphere of yellow, nauseating gas centered on a point within range. The cloud spreads around corners, and its area is heavily obscured. The cloud lingers in the air for the duration.\",\n \"Each creature that is completely within the cloud at the start of its turn must make a constitution saving throw against poison. On a failed save, the creature spends its action that turn retching and reeling. Creatures that don't need to breathe or are immune to poison automatically succeed on this saving throw.\",\n \"A moderate wind (at least 10 miles per hour) disperses the cloud after 4 rounds. A strong wind (at least 20 miles per hour) disperses it after 1 round.\"\n ],\n \"range\": \"90 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A rotten egg or several skunk cabbage leaves.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, the creature spends its action that turn retching and reeling.\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n },\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/stinking-cloud\"\n },\n {\n \"index\": \"stone-shape\",\n \"name\": \"Stone Shape\",\n \"desc\": [\n \"You touch a stone object of Medium size or smaller or a section of stone no more than 5 feet in any dimension and form it into any shape that suits your purpose. So, for example, you could shape a large rock into a weapon, idol, or coffer, or make a small passage through a wall, as long as the wall is less than 5 feet thick. You could also shape a stone door or its frame to seal the door shut. The object you create can have up to two hinges and a latch, but finer mechanical detail isn't possible.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Soft clay, to be crudely worked into the desired shape for the stone object.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/stone-shape\"\n },\n {\n \"index\": \"stoneskin\",\n \"name\": \"Stoneskin\",\n \"desc\": [\n \"This spell turns the flesh of a willing creature you touch as hard as stone. Until the spell ends, the target has resistance to nonmagical bludgeoning, piercing, and slashing damage.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Diamond dust worth 100 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/stoneskin\"\n },\n {\n \"index\": \"storm-of-vengeance\",\n \"name\": \"Storm of Vengeance\",\n \"desc\": [\n \"A churning storm cloud forms, centered on a point you can see and spreading to a radius of 360 feet. Lightning flashes in the area, thunder booms, and strong winds roar. Each creature under the cloud (no more than 5,000 feet beneath the cloud) when it appears must make a constitution saving throw. On a failed save, a creature takes 2d6 thunder damage and becomes deafened for 5 minutes.\",\n \"Each round you maintain concentration on this spell, the storm produces additional effects on your turn.\",\n \"***Round 2.*** Acidic rain falls from the cloud. Each creature and object under the cloud takes 1d6 acid damage.\",\n \"***Round 3.*** You call six bolts of lightning from the cloud to strike six creatures or objects of your choice beneath the cloud. A given creature or object can't be struck by more than one bolt. A struck creature must make a dexterity saving throw. The creature takes 10d6 lightning damage on a failed save, or half as much damage on a successful one.\",\n \"***Round 4.*** Hailstones rain down from the cloud. Each creature under the cloud takes 2d6 bludgeoning damage.\",\n \"***Round 5-10.*** Gusts and freezing rain assail the area under the cloud. The area becomes difficult terrain and is heavily obscured. Each creature there takes 1d6 cold damage. Ranged weapon attacks in the area are impossible. The wind and rain count as a severe distraction for the purposes of maintaining concentration on spells. Finally, gusts of strong wind (ranging from 20 to 50 miles per hour) automatically disperse fog, mists, and similar phenomena in the area, whether mundane or magical.\"\n ],\n \"range\": \"Sight\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"thunder\",\n \"name\": \"Thunder\",\n \"url\": \"/api/damage-types/thunder\"\n },\n \"damage_at_slot_level\": {\n \"9\": \"2d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"none\",\n \"desc\": \"On a failed save, a creature takes 2d6 thunder damage and becomes deafened for 5 minutes.\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 360\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/storm-of-vengeance\"\n },\n {\n \"index\": \"suggestion\",\n \"name\": \"Suggestion\",\n \"desc\": [\n \"You suggest a course of activity (limited to a sentence or two) and magically influence a creature you can see within range that can hear and understand you. Creatures that can't be charmed are immune to this effect. The suggestion must be worded in such a manner as to make the course of action sound reasonable. Asking the creature to stab itself, throw itself onto a spear, immolate itself, or do some other obviously harmful act ends the spell.\",\n \"The target must make a wisdom saving throw. On a failed save, it pursues the course of action you described to the best of its ability. The suggested course of action can continue for the entire duration. If the suggested activity can be completed in a shorter time, the spell ends when the subject finishes what it was asked to do.\",\n \"You can also specify conditions that will trigger a special activity during the duration. For example, you might suggest that a knight give her warhorse to the first beggar she meets. If the condition isn't met before the spell expires, the activity isn't performed.\",\n \"If you or any of your companions damage the target, the spell ends.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A snake's tongue and either a bit of honeycomb or a drop of sweet oil.\",\n \"ritual\": false,\n \"duration\": \"Up to 8 hours\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/suggestion\"\n },\n {\n \"index\": \"sunbeam\",\n \"name\": \"Sunbeam\",\n \"desc\": [\n \"A beam of brilliant light flashes out from your hand in a 5-foot-wide, 60-foot-long line. Each creature in the line must make a constitution saving throw. On a failed save, a creature takes 6d8 radiant damage and is blinded until your next turn. On a successful save, it takes half as much damage and isn't blinded by this spell. Undead and oozes have disadvantage on this saving throw.\",\n \"You can create a new line of radiance as your action on any turn until the spell ends.\",\n \"For the duration, a mote of brilliant radiance shines in your hand. It sheds bright light in a 30-foot radius and dim light for an additional 30 feet. This light is sunlight.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A magnifying glass.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"6d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\",\n \"desc\": \"On a failed save, the creature is blinded until your next turn. On a successful save, it isn't blinded by this spell.\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/sunbeam\"\n },\n {\n \"index\": \"sunburst\",\n \"name\": \"Sunburst\",\n \"desc\": [\n \"Brilliant sunlight flashes in a 60-foot radius centered on a point you choose within range. Each creature in that light must make a constitution saving throw. On a failed save, a creature takes 12d6 radiant damage and is blinded for 1 minute. On a successful save, it takes half as much damage and isn't blinded by this spell. Undead and oozes have disadvantage on this saving throw.\",\n \"A creature blinded by this spell makes another constitution saving throw at the end of each of its turns. On a successful save, it is no longer blinded.\",\n \"This spell dispels any darkness in its area that was created by a spell.\"\n ],\n \"range\": \"150 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Fire and a piece of sunstone.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 8,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"radiant\",\n \"name\": \"Radiant\",\n \"url\": \"/api/damage-types/radiant\"\n },\n \"damage_at_slot_level\": {\n \"8\": \"12d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\",\n \"desc\": \"On failure, the creature is also blinded for 1 minute.\"\n },\n \"area_of_effect\": {\n \"type\": \"cylinder\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/sunburst\"\n },\n {\n \"index\": \"symbol\",\n \"name\": \"Symbol\",\n \"desc\": [\n \"When you cast this spell, you inscribe a harmful glyph either on a surface (such as a section of floor, a wall, or a table) or within an object that can be closed to conceal the glyph (such as a book, a scroll, or a treasure chest). If you choose a surface, the glyph can cover an area of the surface no larger than 10 feet in diameter. If you choose an object, that object must remain in its place; if the object is moved more than 10 feet from where you cast this spell, the glyph is broken, and the spell ends without being triggered.\",\n \"The glyph is nearly invisible, requiring an Intelligence (Investigation) check against your spell save DC to find it.\",\n \"You decide what triggers the glyph when you cast the spell. For glyphs inscribed on a surface, the most typical triggers include touching or stepping on the glyph, removing another object covering it, approaching within a certain distance of it, or manipulating the object that holds it. For glyphs inscribed within an object, the most common triggers are opening the object, approaching within a certain distance of it, or seeing or reading the glyph.\",\n \"You can further refine the trigger so the spell is activated only under certain circumstances or according to a creature's physical characteristics (such as height or weight), or physical kind (for example, the ward could be set to affect hags or shapechangers). You can also specify creatures that don't trigger the glyph, such as those who say a certain password.\",\n \"When you inscribe the glyph, choose one of the options below for its effect. Once triggered, the glyph glows, filling a 60-foot-radius sphere with dim light for 10 minutes, after which time the spell ends. Each creature in the sphere when the glyph activates is targeted by its effect, as is a creature that enters the sphere for the first time on a turn or ends its turn there.\",\n \"***Death.*** Each target must make a constitution saving throw, taking 10d 10 necrotic damage on a failed save, or half as much damage on a successful save.\",\n \"***Discord.*** Each target must make a constitution saving throw. On a failed save, a target bickers and argues with other creatures for 1 minute. During this time, it is incapable of meaningful communication and has disadvantage on attack rolls and ability checks.\",\n \"***Fear.*** Each target must make a wisdom saving throw and becomes frightened for 1 minute on a failed save. While frightened, the target drops whatever it is holding and must move at least 30 feet away from the glyph on each of its turns, if able.\",\n \"***Hopelessness.*** Each target must make a charisma saving throw. On a failed save, the target is overwhelmed with despair for 1 minute. During this time, it can't attack or target any creature with harmful abilities, spells, or other magical effects.\",\n \"***Insanity.*** Each target must make an intelligence saving throw. On a failed save, the target is driven insane for 1 minute. An insane creature can't take actions, can't understand what other creatures say, can't read, and speaks only in gibberish. The GM controls its movement, which is erratic.\",\n \"***Pain.*** Each target must make a constitution saving throw and becomes incapacitated with excruciating pain for 1 minute on a failed save.\",\n \"***Sleep.*** Each target must make a wisdom saving throw and falls unconscious for 10 minutes on a failed save. A creature awakens if it takes damage or if someone uses an action to shake or slap it awake.\",\n \"***Stunning.*** Each target must make a wisdom saving throw and becomes stunned for 1 minute on a failed save.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Mercury, phosphorus, and powdered diamond and opal with a total value of at least 1,000 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Until dispelled\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/symbol\"\n },\n {\n \"index\": \"telekinesis\",\n \"name\": \"Telekinesis\",\n \"desc\": [\n \"You gain the ability to move or manipulate creatures or objects by thought. When you cast the spell, and as your action each round for the duration, you can exert your will on one creature or object that you can see within range, causing the appropriate effect below. You can affect the same target round after round, or choose a new one at any time. If you switch targets, the prior target is no longer affected by the spell.\",\n \"***Creature.*** You can try to move a Huge or smaller creature. Make an ability check with your spellcasting ability contested by the creature's Strength check. If you win the contest, you move the creature up to 30 feet in any direction, including upward but not beyond the range of this spell. Until the end of your next turn, the creature is restrained in your telekinetic grip. A creature lifted upward is suspended in mid-air.\",\n \"On subsequent rounds, you can use your action to attempt to maintain your telekinetic grip on the creature by repeating the contest.\",\n \"***Object.*** You can try to move an object that weighs up to 1,000 pounds. If the object isn't being worn or carried, you automatically move it up to 30 feet in any direction, but not beyond the range of this spell.\",\n \"If the object is worn or carried by a creature, you must make an ability check with your spellcasting ability contested by that creature's Strength check. If you succeed, you pull the object away from that creature and can move it up to 30 feet in any direction but not beyond the range of this spell.\",\n \"You can exert fine control on objects with your telekinetic grip, such as manipulating a simple tool, opening a door or a container, stowing or retrieving an item from an open container, or pouring the contents from a vial.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/telekinesis\"\n },\n {\n \"index\": \"telepathic-bond\",\n \"name\": \"Telepathic Bond\",\n \"desc\": [\n \"You forge a telepathic link among up to eight willing creatures of your choice within range, psychically linking each creature to all the others for the duration. Creatures with Intelligence scores of 2 or less aren't affected by this spell.\",\n \"Until the spell ends, the targets can communicate telepathically through the bond whether or not they have a common language. The communication is possible over any distance, though it can't extend to other planes of existence.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Pieces of eggshell from two different kinds of creatures\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/telepathic-bond\"\n },\n {\n \"index\": \"teleport\",\n \"name\": \"Teleport\",\n \"desc\": [\n \"This spell instantly transports you and up to eight willing creatures of your choice that you can see within range, or a single object that you can see within range, to a destination you select. If you target an object, it must be able to fit entirely inside a 10-foot cube, and it can't be held or carried by an unwilling creature.\",\n \"The destination you choose must be known to you, and it must be on the same plane of existence as you. Your familiarity with the destination determines whether you arrive there successfully. The GM rolls d100 and consults the table.\",\n \"| Familiarity | Mishap | Similar Area | Off Target | On Target |\",\n \"|---|---|---|---|---|\",\n \"| Permanent circle | -- | -- | -- | 01-100 |\",\n \"| Associated object | -- | -- | -- | 01-100 |\",\n \"| Very familiar | 01-05 | 06-13 | 14-24 | 25-100 |\",\n \"| Seen casually | 01-33 | 34-43 | 44-53 | 54-100 |\",\n \"| Viewed once | 01-43 | 44-53 | 54-73 | 74-100 |\",\n \"| Description | 01-43 | 44-53 | 54-73 | 74-100 |\",\n \"| False destination | 01-50 | 51-100 | -- | -- |\",\n \"***Familiarity.*** \\\"Permanent circle\\\" means a permanent teleportation circle whose sigil sequence you know.\",\n \"\\\"Associated object\\\" means that you possess an object taken from the desired destination within the last six months, such as a book from a wizard's library, bed linen from a royal suite, or a chunk of marble from a lich's secret tomb.\",\n \"\\\"Very familiar\\\" is a place you have been very often, a place you have carefully studied, or a place you can see when you cast the spell.\",\n \"\\\"Seen casually\\\" is someplace you have seen more than once but with which you aren't very familiar.\",\n \"\\\"Viewed once\\\" is a place you have seen once, possibly using magic.\",\n \"\\\"Description\\\" is a place whose location and appearance you know through someone else's description, perhaps from a map.\",\n \"\\\"False destination\\\" is a place that doesn't exist. Perhaps you tried to scry an enemy's sanctum but instead viewed an illusion, or you are attempting to teleport to a familiar location that no longer exists.\",\n \"***On Target.*** You and your group (or the target object) appear where you want to.\",\n \"***Off Target.*** You and your group (or the target object) appear a random distance away from the destination in a random direction. Distance off target is 1d10 x 1d10 percent of the distance that was to be traveled. For example, if you tried to travel 120 miles, landed off target, and rolled a 5 and 3 on the two d10s, then you would be off target by 15 percent, or 18 miles. The GM determines the direction off target randomly by rolling a d8 and designating 1 as north, 2 as northeast, 3 as east, and so on around the points of the compass. If you were teleporting to a coastal city and wound up 18 miles out at sea, you could be in trouble.\",\n \"***Similar Area.*** You and your group (or the target object) wind up in a different area that's visually or thematically similar to the target area. If you are heading for your home laboratory, for example, you might wind up in another wizard's laboratory or in an alchemical supply shop that has many of the same tools and implements as your laboratory. Generally, you appear in the closest similar place, but since the spell has no range limit, you could conceivably wind up anywhere on the plane.\",\n \"***Mishap.*** The spell's unpredictable magic results in a difficult journey. Each teleporting creature (or the target object) takes 3d10 force damage, and the GM rerolls on the table to see where you wind up (multiple mishaps can occur, dealing damage each time).\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 7,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/teleport\"\n },\n {\n \"index\": \"teleportation-circle\",\n \"name\": \"Teleportation Circle\",\n \"desc\": [\n \"As you cast the spell, you draw a 10-foot-diameter circle on the ground inscribed with sigils that link your location to a permanent teleportation circle of your choice whose sigil sequence you know and that is on the same plane of existence as you. A shimmering portal opens within the circle you drew and remains open until the end of your next turn. Any creature that enters the portal instantly appears within 5 feet of the destination circle or in the nearest unoccupied space if that space is occupied.\",\n \"Many major temples, guilds, and other important places have permanent teleportation circles inscribed somewhere within their confines. Each such circle includes a unique sigil sequence--a string of magical runes arranged in a particular pattern. When you first gain the ability to cast this spell, you learn the sigil sequences for two destinations on the Material Plane, determined by the GM. You can learn additional sigil sequences during your adventures. You can commit a new sigil sequence to memory after studying it for 1 minute.\",\n \"You can create a permanent teleportation circle by casting this spell in the same location every day for one year. You need not use the circle to teleport when you cast the spell in this way.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"Rare chalks and inks infused with precious gems with 50 gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 5,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/teleportation-circle\"\n },\n {\n \"index\": \"thaumaturgy\",\n \"name\": \"Thaumaturgy\",\n \"desc\": [\n \"You manifest a minor wonder, a sign of supernatural power, within range. You create one of the following magical effects within range.\",\n \"- Your voice booms up to three times as loud as normal for 1 minute.\",\n \"- You cause flames to flicker, brighten, dim, or change color for 1 minute.\",\n \"- You cause harmless tremors in the ground for 1 minute.\",\n \"- You create an instantaneous sound that originates from a point of your choice within range, such as a rumble of thunder, the cry of a raven, or ominous whispers.\",\n \"- You instantaneously cause an unlocked door or window to fly open or slam shut.\",\n \"- You alter the appearance of your eyes for 1 minute.\",\n \"If you cast this spell multiple times, you can have up to three of its 1-minute effects active at a time, and you can dismiss such an effect as an action.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"1 minute\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/thaumaturgy\"\n },\n {\n \"index\": \"thunderwave\",\n \"name\": \"Thunderwave\",\n \"desc\": [\n \"A wave of thunderous force sweeps out from you. Each creature in a 15-foot cube originating from you must make a constitution saving throw. On a failed save, a creature takes 2d8 thunder damage and is pushed 10 feet away from you. On a successful save, the creature takes half as much damage and isn't pushed.\",\n \"In addition, unsecured objects that are completely within the area of effect are automatically pushed 10 feet away from you by the spell's effect, and the spell emits a thunderous boom audible out to 300 feet.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d8 for each slot level above 1st.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"thunder\",\n \"name\": \"Thunder\",\n \"url\": \"/api/damage-types/thunder\"\n },\n \"damage_at_slot_level\": {\n \"1\": \"2d8\",\n \"2\": \"3d8\",\n \"3\": \"4d8\",\n \"4\": \"5d8\",\n \"5\": \"6d8\",\n \"6\": \"7d8\",\n \"7\": \"8d8\",\n \"8\": \"9d8\",\n \"9\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"con\",\n \"name\": \"CON\",\n \"url\": \"/api/ability-scores/con\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/thunderwave\"\n },\n {\n \"index\": \"time-stop\",\n \"name\": \"Time Stop\",\n \"desc\": [\n \"You briefly stop the flow of time for everyone but yourself. No time passes for other creatures, while you take 1d4 + 1 turns in a row, during which you can use actions and move as normal.\",\n \"This spell ends if one of the actions you use during this period, or any effects that you create during this period, affects a creature other than you or an object being worn or carried by someone other than you. In addition, the spell ends if you move to a place more than 1,000 feet from the location where you cast it.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/time-stop\"\n },\n {\n \"index\": \"tiny-hut\",\n \"name\": \"Tiny Hut\",\n \"desc\": [\n \"A 10-foot-radius immobile dome of force springs into existence around and above you and remains stationary for the duration. The spell ends if you leave its area.\",\n \"Nine creatures of Medium size or smaller can fit inside the dome with you. The spell fails if its area includes a larger creature or more than nine creatures. Creatures and objects within the dome when you cast this spell can move through it freely. All other creatures and objects are barred from passing through it. Spells and other magical effects can't extend through the dome or be cast through it. The atmosphere inside the space is comfortable and dry, regardless of the weather outside.\",\n \"Until the spell ends, you can command the interior to become dimly lit or dark. The dome is opaque from the outside, of any color you choose, but it is transparent from the inside.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small crystal bead.\",\n \"ritual\": true,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 3,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/tiny-hut\"\n },\n {\n \"index\": \"tongues\",\n \"name\": \"Tongues\",\n \"desc\": [\n \"This spell grants the creature you touch the ability to understand any spoken language it hears. Moreover, when the target speaks, any creature that knows at least one language and can hear the target understands what it says.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"M\"],\n \"material\": \"A small clay model of a ziggurat.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/tongues\"\n },\n {\n \"index\": \"transport-via-plants\",\n \"name\": \"Transport via Plants\",\n \"desc\": [\n \"This spell creates a magical link between a Large or larger inanimate plant within range and another plant, at any distance, on the same plane of existence. You must have seen or touched the destination plant at least once before. For the duration, any creature can step into the target plant and exit from the destination plant by using 5 feet of movement.\"\n ],\n \"range\": \"10 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"1 round\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/transport-via-plants\"\n },\n {\n \"index\": \"tree-stride\",\n \"name\": \"Tree Stride\",\n \"desc\": [\n \"You gain the ability to enter a tree and move from inside it to inside another tree of the same kind within 500 feet. Both trees must be living and at least the same size as you. You must use 5 feet of movement to enter a tree. You instantly know the location of all other trees of the same kind within 500 feet and, as part of the move used to enter the tree, can either pass into one of those trees or step out of the tree you're in. You appear in a spot of your choice within 5 feet of the destination tree, using another 5 feet of movement. If you have no movement left, you appear within 5 feet of the tree you entered.\",\n \"You can use this transportation ability once per round for the duration. You must end each turn outside a tree.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/tree-stride\"\n },\n {\n \"index\": \"true-polymorph\",\n \"name\": \"True Polymorph\",\n \"desc\": [\n \"Choose one creature or nonmagical object that you can see within range. You transform the creature into a different creature, the creature into an object, or the object into a creature (the object must be neither worn nor carried by another creature). The transformation lasts for the duration, or until the target drops to 0 hit points or dies. If you concentrate on this spell for the full duration, the transformation becomes permanent.\",\n \"Shapechangers aren't affected by this spell. An unwilling creature can make a wisdom saving throw, and if it succeeds, it isn't affected by this spell.\",\n \"***Creature into Creature.*** If you turn a creature into another kind of creature, the new form can be any kind you choose whose challenge rating is equal to or less than the target's (or its level, if the target doesn't have a challenge rating). The target's game statistics, including mental ability scores, are replaced by the statistics of the new form. It retains its alignment and personality.\",\n \"The target assumes the hit points of its new form, and when it reverts to its normal form, the creature returns to the number of hit points it had before it transformed. If it reverts as a result of dropping to 0 hit points, any excess damage carries over to its normal form. As long as the excess damage doesn't reduce the creature's normal form to 0 hit points, it isn't knocked unconscious.\",\n \"The creature is limited in the actions it can perform by the nature of its new form, and it can't speak, cast spells, or take any other action that requires hands or speech unless its new form is capable of such actions.\",\n \"The target's gear melds into the new form. The creature can't activate, use, wield, or otherwise benefit from any of its equipment.\",\n \"***Object into Creature.*** You can turn an object into any kind of creature, as long as the creature's size is no larger than the object's size and the creature's challenge rating is 9 or lower. The creature is friendly to you and your companions. It acts on each of your turns. You decide what action it takes and how it moves. The GM has the creature's statistics and resolves all of its actions and movement.\",\n \"If the spell becomes permanent, you no longer control the creature. It might remain friendly to you, depending on how you have treated it.\",\n \"***Creature into Object.*** If you turn a creature into an object, it transforms along with whatever it is wearing and carrying into that form. The creature's statistics become those of the object, and the creature has no memory of time spent in this form, after the spell ends and it returns to its normal form.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A drop of mercury, a dollop of gum arabic, and a wisp of smoke.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/true-polymorph\"\n },\n {\n \"index\": \"true-resurrection\",\n \"name\": \"True Resurrection\",\n \"desc\": [\n \"You touch a creature that has been dead for no longer than 200 years and that died for any reason except old age. If the creature's soul is free and willing, the creature is restored to life with all its hit points.\",\n \"This spell closes all wounds, neutralizes any poison, cures all diseases, and lifts any curses affecting the creature when it died. The spell replaces damaged or missing organs and limbs.\",\n \"The spell can even provide a new body if the original no longer exists, in which case you must speak the creature's name. The creature then appears in an unoccupied space you choose within 10 feet of you.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A sprinkle of holy water and diamonds worth at least 25,000gp, which the spell consumes.\",\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 hour\",\n \"level\": 9,\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/true-resurrection\"\n },\n {\n \"index\": \"true-seeing\",\n \"name\": \"True Seeing\",\n \"desc\": [\n \"This spell gives the willing creature you touch the ability to see things as they actually are. For the duration, the creature has truesight, notices secret doors hidden by magic, and can see into the Ethereal Plane, all out to a range of 120 feet.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"An ointment for the eyes that costs 25gp; is made from mushroom powder, saffron, and fat; and is consumed by the spell.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/true-seeing\"\n },\n {\n \"index\": \"true-strike\",\n \"name\": \"True Strike\",\n \"desc\": [\n \"You extend your hand and point a finger at a target in range. Your magic grants you a brief insight into the target's defenses. On your next turn, you gain advantage on your first attack roll against the target, provided that this spell hasn't ended.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 round\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"school\": {\n \"index\": \"divination\",\n \"name\": \"Divination\",\n \"url\": \"/api/magic-schools/divination\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/true-strike\"\n },\n {\n \"index\": \"unseen-servant\",\n \"name\": \"Unseen Servant\",\n \"desc\": [\n \"This spell creates an invisible, mindless, shapeless force that performs simple tasks at your command until the spell ends. The servant springs into existence in an unoccupied space on the ground within range. It has AC 10, 1 hit point, and a Strength of 2, and it can't attack. If it drops to 0 hit points, the spell ends.\",\n \"Once on each of your turns as a bonus action, you can mentally command the servant to move up to 15 feet and interact with an object. The servant can perform simple tasks that a human servant could do, such as fetching things, cleaning, mending, folding clothes, lighting fires, serving food, and pouring wine. Once you give the command, the servant performs the task to the best of its ability until it completes the task, then waits for your next command.\",\n \"If you command the servant to perform a task that would move it more than 60 feet away from you, the spell ends.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of string and a bit of wood.\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 1,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/unseen-servant\"\n },\n {\n \"index\": \"vampiric-touch\",\n \"name\": \"Vampiric Touch\",\n \"desc\": [\n \"The touch of your shadow-wreathed hand can siphon life force from others to heal your wounds. Make a melee spell attack against a creature within your reach. On a hit, the target takes 3d6 necrotic damage, and you regain hit points equal to half the amount of necrotic damage dealt. Until the spell ends, you can make the attack again on each of your turns as an action.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 4th level or higher, the damage increases by 1d6 for each slot level above 3rd.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"attack_type\": \"melee\",\n \"damage\": {\n \"damage_type\": {\n \"index\": \"necrotic\",\n \"name\": \"Necrotic\",\n \"url\": \"/api/damage-types/necrotic\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"3d6\",\n \"4\": \"4d6\",\n \"5\": \"5d6\",\n \"6\": \"6d6\",\n \"7\": \"7d6\",\n \"8\": \"8d6\",\n \"9\": \"9d6\"\n }\n },\n \"school\": {\n \"index\": \"necromancy\",\n \"name\": \"Necromancy\",\n \"url\": \"/api/magic-schools/necromancy\"\n },\n \"classes\": [\n {\n \"index\": \"warlock\",\n \"name\": \"Warlock\",\n \"url\": \"/api/classes/warlock\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/vampiric-touch\"\n },\n {\n \"index\": \"vicious-mockery\",\n \"name\": \"Vicious Mockery\",\n \"desc\": [\n \"You unleash a string of insults laced with subtle enchantments at a creature you can see within range. If the target can hear you (though it need not understand you), it must succeed on a wisdom saving throw or take 1d4 psychic damage and have disadvantage on the next attack roll it makes before the end of its next turn.\",\n \"This spell's damage increases by 1d4 when you reach 5th level (2d4), 11th level (3d4), and 17th level (4d4).\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 0,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"psychic\",\n \"name\": \"Psychic\",\n \"url\": \"/api/damage-types/psychic\"\n },\n \"damage_at_character_level\": {\n \"1\": \"1d4\",\n \"5\": \"2d4\",\n \"11\": \"3d4\",\n \"17\": \"4d4\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/vicious-mockery\"\n },\n {\n \"index\": \"wall-of-fire\",\n \"name\": \"Wall of Fire\",\n \"desc\": [\n \"You create a wall of fire on a solid surface within range. You can make the wall up to 60 feet long, 20 feet high, and 1 foot thick, or a ringed wall up to 20 feet in diameter, 20 feet high, and 1 foot thick. The wall is opaque and lasts for the duration.\",\n \"When the wall appears, each creature within its area must make a Dexterity saving throw. On a failed save, a creature takes 5d8 fire damage, or half as much damage on a successful save.\",\n \"One side of the wall, selected by you when you cast this spell, deals 5d8 fire damage to each creature that ends its turn within 10 feet o f that side or inside the wall. A creature takes the same damage when it enters the wall for the first time on a turn or ends its turn there. The other side of the wall deals no damage.\",\n \"The other side of the wall deals no damage.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 5th level or higher, the damage increases by 1d8 for each slot level above 4th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small piece of phosphorus.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 4,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"fire\",\n \"name\": \"Fire\",\n \"url\": \"/api/damage-types/fire\"\n },\n \"damage_at_slot_level\": {\n \"4\": \"5d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"fiend\",\n \"name\": \"Fiend\",\n \"url\": \"/api/subclasses/fiend\"\n }\n ],\n \"url\": \"/api/spells/wall-of-fire\"\n },\n {\n \"index\": \"wall-of-force\",\n \"name\": \"Wall of Force\",\n \"desc\": [\n \"An invisible wall of force springs into existence at a point you choose within range. The wall appears in any orientation you choose, as a horizontal or vertical barrier or at an angle. It can be free floating or resting on a solid surface. You can form it into a hemispherical dome or a sphere with a radius of up to 10 feet, or you can shape a flat surface made up of ten 10-foot-by-10-foot panels. Each panel must be contiguous with another panel. In any form, the wall is 1/4 inch thick. It lasts for the duration. If the wall cuts through a creature's space when it appears, the creature is pushed to one side of the wall (your choice which side).\",\n \"Nothing can physically pass through the wall. It is immune to all damage and can't be dispelled by dispel magic. A disintegrate spell destroys the wall instantly, however. The wall also extends into the Ethereal Plane, blocking ethereal travel through the wall.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pinch of powder made by crushing a clear gemstone.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wall-of-force\"\n },\n {\n \"index\": \"wall-of-ice\",\n \"name\": \"Wall of Ice\",\n \"desc\": [\n \"You create a wall of ice on a solid surface within range. You can form it into a hemispherical dome or a sphere with a radius of up to 10 feet, or you can shape a flat surface made up of ten 10-foot-square panels. Each panel must be contiguous with another panel. In any form, the wall is 1 foot thick and lasts for the duration.\",\n \"If the wall cuts through a creature's space when it appears, the creature within its area is pushed to one side of the wall and must make a dexterity saving throw. On a failed save, the creature takes 10d6 cold damage, or half as much damage on a successful save.\",\n \"The wall is an object that can be damaged and thus breached. It has AC 12 and 30 hit points per 10-foot section, and it is vulnerable to fire damage. Reducing a 10-foot section of wall to 0 hit points destroys it and leaves behind a sheet of frigid air in the space the wall occupied. A creature moving through the sheet of frigid air for the first time on a turn must make a constitution saving throw. That creature takes 5d6 cold damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, the damage the wall deals when it appears increases by 2d6, and the damage from passing through the sheet of frigid air increases by 1d6, for each slot level above 6th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small piece of quartz.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"cold\",\n \"name\": \"Cold\",\n \"url\": \"/api/damage-types/cold\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"10d6\",\n \"7\": \"12d6\",\n \"8\": \"14d6\",\n \"9\": \"16d6\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 10\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wall-of-ice\"\n },\n {\n \"index\": \"wall-of-stone\",\n \"name\": \"Wall of Stone\",\n \"desc\": [\n \"A nonmagical wall of solid stone springs into existence at a point you choose within range. The wall is 6 inches thick and is composed of ten 10-foot-by-10-foot panels. Each panel must be contiguous with at least one other panel. Alternatively, you can create 10-foot-by-20-foot panels that are only 3 inches thick.\",\n \"If the wall cuts through a creature's space when it appears, the creature is pushed to one side of the wall (your choice). If a creature would be surrounded on all sides by the wall (or the wall and another solid surface), that creature can make a dexterity saving throw. On a success, it can use its reaction to move up to its speed so that it is no longer enclosed by the wall.\",\n \"The wall can have any shape you desire, though it can't occupy the same space as a creature or object. The wall doesn't need to be vertical or rest on any firm foundation. It must, however, merge with and be solidly supported by existing stone. Thus, you can use this spell to bridge a chasm or create a ramp.\",\n \"If you create a span greater than 20 feet in length, you must halve the size of each panel to create supports. You can crudely shape the wall to create crenellations, battlements, and so on.\",\n \"The wall is an object made of stone that can be damaged and thus breached. Each panel has AC 15 and 30 hit points per inch of thickness. Reducing a panel to 0 hit points destroys it and might cause connected panels to collapse at the GM's discretion.\",\n \"If you maintain your concentration on this spell for its whole duration, the wall becomes permanent and can't be dispelled. Otherwise, the wall disappears when the spell ends.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A small block of granite.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 5,\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/wall-of-stone\"\n },\n {\n \"index\": \"wall-of-thorns\",\n \"name\": \"Wall of Thorns\",\n \"desc\": [\n \"You create a wall of tough, pliable, tangled brush bristling with needle-sharp thorns. The wall appears within range on a solid surface and lasts for the duration. You choose to make the wall up to 60 feet long, 10 feet high, and 5 feet thick or a circle that has a 20-foot diameter and is up to 20 feet high and 5 feet thick. The wall blocks line of sight.\",\n \"When the wall appears, each creature within its area must make a dexterity saving throw. On a failed save, a creature takes 7d8 piercing damage, or half as much damage on a successful save.\",\n \"A creature can move through the wall, albeit slowly and painfully. For every 1 foot a creature moves through the wall, it must spend 4 feet of movement. Furthermore, the first time a creature enters the wall on a turn or ends its turn there, the creature must make a dexterity saving throw. It takes 7d8 slashing damage on a failed save, or half as much damage on a successful one.\"\n ],\n \"higher_level\": [\n \"When you cast this spell using a spell slot of 7th level or higher, both types of damage increase by 1d8 for each slot level above 6th.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A handful of thorns.\",\n \"ritual\": false,\n \"duration\": \"Up to 10 minutes\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"piercing\",\n \"name\": \"Piercing\",\n \"url\": \"/api/damage-types/piercing\"\n },\n \"damage_at_slot_level\": {\n \"6\": \"7d8\",\n \"7\": \"8d8\",\n \"8\": \"9d8\",\n \"9\": \"10d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"dex\",\n \"name\": \"DEX\",\n \"url\": \"/api/ability-scores/dex\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 60\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wall-of-thorns\"\n },\n {\n \"index\": \"warding-bond\",\n \"name\": \"Warding Bond\",\n \"desc\": [\n \"This spell wards a willing creature you touch and creates a mystic connection between you and the target until the spell ends. While the target is within 60 feet of you, it gains a +1 bonus to AC and saving throws, and it has resistance to all damage. Also, each time it takes damage, you take the same amount of damage.\",\n \"The spell ends if you drop to 0 hit points or if you and the target become separated by more than 60 feet.\",\n \"It also ends if the spell is cast again on either of the connected creatures. You can also dismiss the spell as an action.\"\n ],\n \"range\": \"Touch\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A pair of platinum rings worth at least 50gp each, which you and the target must wear for the duration.\",\n \"ritual\": false,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"school\": {\n \"index\": \"abjuration\",\n \"name\": \"Abjuration\",\n \"url\": \"/api/magic-schools/abjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/warding-bond\"\n },\n {\n \"index\": \"water-breathing\",\n \"name\": \"Water Breathing\",\n \"desc\": [\n \"This spell gives a maximum of ten willing creatures within range and you can see, the ability to breathe underwater until the end of its term. Affected creatures also retain their normal breathing pattern.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A short piece of reed or straw.\",\n \"ritual\": true,\n \"duration\": \"24 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/water-breathing\"\n },\n {\n \"index\": \"water-walk\",\n \"name\": \"Water Walk\",\n \"desc\": [\n \"This spell grants the ability to move across any liquid surface--such as water, acid, mud, snow, quicksand, or lava--as if it were harmless solid ground (creatures crossing molten lava can still take damage from the heat). Up to ten willing creatures you can see within range gain this ability for the duration.\",\n \"If you target a creature submerged in a liquid, the spell carries the target to the surface of the liquid at a rate of 60 feet per round.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A piece of cork.\",\n \"ritual\": true,\n \"duration\": \"1 hour\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n },\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/water-walk\"\n },\n {\n \"index\": \"web\",\n \"name\": \"Web\",\n \"desc\": [\n \"You conjure a mass of thick, sticky webbing at a point of your choice within range. The webs fill a 20-foot cube from that point for the duration. The webs are difficult terrain and lightly obscure their area.\",\n \"If the webs aren't anchored between two solid masses (such as walls or trees) or layered across a floor, wall, or ceiling, the conjured web collapses on itself, and the spell ends at the start of your next turn. Webs layered over a flat surface have a depth of 5 feet.\",\n \"Each creature that starts its turn in the webs or that enters them during its turn must make a dexterity saving throw. On a failed save, the creature is restrained as long as it remains in the webs or until it breaks free.\",\n \"A creature restrained by the webs can use its action to make a Strength check against your spell save DC. If it succeeds, it is no longer restrained.\",\n \"The webs are flammable. Any 5-foot cube of webs exposed to fire burns away in 1 round, dealing 2d4 fire damage to any creature that starts its turn in the fire.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A bit of spiderweb.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 hour\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"cube\",\n \"size\": 20\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"land\",\n \"name\": \"Land\",\n \"url\": \"/api/subclasses/land\"\n }\n ],\n \"url\": \"/api/spells/web\"\n },\n {\n \"index\": \"weird\",\n \"name\": \"Weird\",\n \"desc\": [\n \"Drawing on the deepest fears of a group of creatures, you create illusory creatures in their minds, visible only to them. Each creature in a 30-foot-radius sphere centered on a point of your choice within range must make a wisdom saving throw. On a failed save, a creature becomes frightened for the duration. The illusion calls on the creature's deepest fears, manifesting its worst nightmares as an implacable threat. At the start of each of the frightened creature's turns, it must succeed on a wisdom saving throw or take 4d10 psychic damage. On a successful save, the spell ends for that creature.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"dc\": {\n \"dc_type\": {\n \"index\": \"wis\",\n \"name\": \"WIS\",\n \"url\": \"/api/ability-scores/wis\"\n },\n \"dc_success\": \"none\"\n },\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 30\n },\n \"school\": {\n \"index\": \"illusion\",\n \"name\": \"Illusion\",\n \"url\": \"/api/magic-schools/illusion\"\n },\n \"classes\": [\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/weird\"\n },\n {\n \"index\": \"wind-walk\",\n \"name\": \"Wind Walk\",\n \"desc\": [\n \"You and up to ten willing creatures you can see within range assume a gaseous form for the duration, appearing as wisps of cloud. While in this cloud form, a creature has a flying speed of 300 feet and has resistance to damage from nonmagical weapons. The only actions a creature can take in this form are the Dash action or to revert to its normal form. Reverting takes 1 minute, during which time a creature is incapacitated and can't move. Until the spell ends, a creature can revert to cloud form, which also requires the 1-minute transformation.\",\n \"If a creature is in cloud form and flying when the effect ends, the creature descends 60 feet per round for 1 minute until it lands, which it does safely. If it can't land after 1 minute, the creature falls the remaining distance.\"\n ],\n \"range\": \"30 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"Fire and holy water.\",\n \"ritual\": false,\n \"duration\": \"8 hours\",\n \"concentration\": false,\n \"casting_time\": \"1 minute\",\n \"level\": 6,\n \"school\": {\n \"index\": \"transmutation\",\n \"name\": \"Transmutation\",\n \"url\": \"/api/magic-schools/transmutation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wind-walk\"\n },\n {\n \"index\": \"wind-wall\",\n \"name\": \"Wind Wall\",\n \"desc\": [\n \"A wall of strong wind rises from the ground at a point you choose within range. You can make the wall up to 50 feet long, 15 feet high, and 1 foot thick. You can shape the wall in any way you choose so long as it makes one continuous path along the ground. The wall lasts for the duration.\",\n \"When the wall appears, each creature within its area must make a strength saving throw. A creature takes 3d8 bludgeoning damage on a failed save, or half as much damage on a successful one.\",\n \"The strong wind keeps fog, smoke, and other gases at bay. Small or smaller flying creatures or objects can't pass through the wall. Loose, lightweight materials brought into the wall fly upward. Arrows, bolts, and other ordinary projectiles launched at targets behind the wall are deflected upward and automatically miss. (Boulders hurled by giants or siege engines, and similar projectiles, are unaffected.) Creatures in gaseous form can't pass through it.\"\n ],\n \"range\": \"120 feet\",\n \"components\": [\"V\", \"S\", \"M\"],\n \"material\": \"A tiny fan and a feather of exotic origin.\",\n \"ritual\": false,\n \"duration\": \"Up to 1 minute\",\n \"concentration\": true,\n \"casting_time\": \"1 action\",\n \"level\": 3,\n \"damage\": {\n \"damage_type\": {\n \"index\": \"bludgeoning\",\n \"name\": \"Bludgeoning\",\n \"url\": \"/api/damage-types/bludgeoning\"\n },\n \"damage_at_slot_level\": {\n \"3\": \"3d8\"\n }\n },\n \"dc\": {\n \"dc_type\": {\n \"index\": \"str\",\n \"name\": \"STR\",\n \"url\": \"/api/ability-scores/str\"\n },\n \"dc_success\": \"half\"\n },\n \"area_of_effect\": {\n \"type\": \"line\",\n \"size\": 50\n },\n \"school\": {\n \"index\": \"evocation\",\n \"name\": \"Evocation\",\n \"url\": \"/api/magic-schools/evocation\"\n },\n \"classes\": [\n {\n \"index\": \"druid\",\n \"name\": \"Druid\",\n \"url\": \"/api/classes/druid\"\n },\n {\n \"index\": \"ranger\",\n \"name\": \"Ranger\",\n \"url\": \"/api/classes/ranger\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n }\n ],\n \"url\": \"/api/spells/wind-wall\"\n },\n {\n \"index\": \"wish\",\n \"name\": \"Wish\",\n \"desc\": [\n \"Wish is the mightiest spell a mortal creature can cast. By simply speaking aloud, you can alter the very foundations of reality in accord with your desires.\",\n \"The basic use of this spell is to duplicate any other spell of 8th level or lower. You don't need to meet any requirements in that spell, including costly components. The spell simply takes effect.\",\n \"Alternatively, you can create one of the following effects of your choice:\",\n \"- You create one object of up to 25,000 gp in value that isn't a magic item. The object can be no more than 300 feet in any dimension, and it appears in an unoccupied space you can see on the ground.\",\n \"- You allow up to twenty creatures that you can see to regain all hit points, and you end all effects on them described in the greater restoration spell.\",\n \"- You grant up to ten creatures that you can see resistance to a damage type you choose.\",\n \"- You grant up to ten creatures you can see immunity to a single spell or other magical effect for 8 hours. For instance, you could make yourself and all your companions immune to a lich's life drain attack.\",\n \"- You undo a single recent event by forcing a reroll of any roll made within the last round (including your last turn). Reality reshapes itself to accommodate the new result. For example, a wish spell could undo an opponent's successful save, a foe's critical hit, or a friend's failed save. You can force the reroll to be made with advantage or disadvantage, and you can choose whether to use the reroll or the original roll.\",\n \"You might be able to achieve something beyond the scope of the above examples. State your wish to the GM as precisely as possible. The GM has great latitude in ruling what occurs in such an instance; the greater the wish, the greater the likelihood that something goes wrong. This spell might simply fail, the effect you desire might only be partly achieved, or you might suffer some unforeseen consequence as a result of how you worded the wish. For example, wishing that a villain were dead might propel you forward in time to a period when that villain is no longer alive, effectively removing you from the game. Similarly, wishing for a legendary magic item or artifact might instantly transport you to the presence of the item's current owner.\",\n \"The stress of casting this spell to produce any effect other than duplicating another spell weakens you. After enduring that stress, each time you cast a spell until you finish a long rest, you take 1d10 necrotic damage per level of that spell. This damage can't be reduced or prevented in any way. In addition, your Strength drops to 3, if it isn't 3 or lower already, for 2d4 days. For each of those days that you spend resting and doing nothing more than light activity, your remaining recovery time decreases by 2 days. Finally, there is a 33 percent chance that you are unable to cast wish ever again if you suffer this stress.\"\n ],\n \"range\": \"Self\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 9,\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"sorcerer\",\n \"name\": \"Sorcerer\",\n \"url\": \"/api/classes/sorcerer\"\n },\n {\n \"index\": \"wizard\",\n \"name\": \"Wizard\",\n \"url\": \"/api/classes/wizard\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/wish\"\n },\n {\n \"index\": \"word-of-recall\",\n \"name\": \"Word of Recall\",\n \"desc\": [\n \"You and up to five willing creatures within 5 feet of you instantly teleport to a previously designated sanctuary. You and any creatures that teleport with you appear in the nearest unoccupied space to the spot you designated when you prepared your sanctuary (see below). If you cast this spell without first preparing a sanctuary, the spell has no effect.\",\n \"You must designate a sanctuary by casting this spell within a location, such as a temple, dedicated to or strongly linked to your deity. If you attempt to cast the spell in this manner in an area that isn't dedicated to your deity, the spell has no effect.\"\n ],\n \"range\": \"5 feet\",\n \"components\": [\"V\"],\n \"ritual\": false,\n \"duration\": \"Instantaneous\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 6,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 5\n },\n \"school\": {\n \"index\": \"conjuration\",\n \"name\": \"Conjuration\",\n \"url\": \"/api/magic-schools/conjuration\"\n },\n \"classes\": [\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n }\n ],\n \"subclasses\": [],\n \"url\": \"/api/spells/word-of-recall\"\n },\n {\n \"index\": \"zone-of-truth\",\n \"name\": \"Zone of Truth\",\n \"desc\": [\n \"You create a magical zone that guards against deception in a 15-foot-radius sphere centered on a point of your choice within range. Until the spell ends, a creature that enters the spell's area for the first time on a turn or starts its turn there must make a Charisma saving throw. On a failed save, a creature can't speak a deliberate lie while in the radius. You know whether each creature succeeds or fails on its saving throw.\",\n \"An affected creature is aware of the spell and can thus avoid answering questions to which it would normally respond with a lie. Such a creature can remain evasive in its answers as long as it remains within the boundaries of the truth.\"\n ],\n \"range\": \"60 feet\",\n \"components\": [\"V\", \"S\"],\n \"ritual\": false,\n \"duration\": \"10 minutes\",\n \"concentration\": false,\n \"casting_time\": \"1 action\",\n \"level\": 2,\n \"area_of_effect\": {\n \"type\": \"sphere\",\n \"size\": 15\n },\n \"school\": {\n \"index\": \"enchantment\",\n \"name\": \"Enchantment\",\n \"url\": \"/api/magic-schools/enchantment\"\n },\n \"classes\": [\n {\n \"index\": \"bard\",\n \"name\": \"Bard\",\n \"url\": \"/api/classes/bard\"\n },\n {\n \"index\": \"cleric\",\n \"name\": \"Cleric\",\n \"url\": \"/api/classes/cleric\"\n },\n {\n \"index\": \"paladin\",\n \"name\": \"Paladin\",\n \"url\": \"/api/classes/paladin\"\n }\n ],\n \"subclasses\": [\n {\n \"index\": \"lore\",\n \"name\": \"Lore\",\n \"url\": \"/api/subclasses/lore\"\n },\n {\n \"index\": \"devotion\",\n \"name\": \"Devotion\",\n \"url\": \"/api/subclasses/devotion\"\n }\n ],\n \"url\": \"/api/spells/zone-of-truth\"\n }\n]\n", "import spellData from '../5e-SRD-Spells.json';\nimport { getCurrentCharacter } from '../services/CharacterService';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n
    \n
    \n
    \n \n \n
    \n
    \n
    \n
    \n
      \n
    • \n
    • \n
    • \n
    • \n
    • \n
    \n
    \n
    \n
    \n`;\n\nclass SpellItem extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n this.#setupElements();\n }\n\n connectedCallback () {\n this.#loadData();\n this.#populateSpellItem();\n\n this.#setupEventListeners();\n }\n\n disconnectedCallback () {\n this.#removeEventListeners();\n }\n\n // Group together html elements for readability\n #setupElements () {\n this.elements = {\n accordion: this.shadowRoot.querySelector('.accordion'),\n accordion_icon: this.shadowRoot.querySelector('.accordion-icon'),\n panel: this.shadowRoot.querySelector('.panel'),\n add_button: this.shadowRoot.querySelector('.spell-item-add'),\n stats: this.shadowRoot.querySelector('.spell-item-stats'),\n spell_range: this.shadowRoot.querySelector('.spell-item-range'),\n spell_components: this.shadowRoot.querySelector('.spell-item-comps'),\n spell_duration: this.shadowRoot.querySelector('.spell-item-dur'),\n spell_casting: this.shadowRoot.querySelector('.spell-item-casting'),\n spell_concentration: this.shadowRoot.querySelector('.spell-item-conc'),\n spell_name: this.shadowRoot.querySelector('.spell-item-name'),\n spell_description: this.shadowRoot.querySelector('.spell-item-desc'),\n spell_higher_level: this.shadowRoot.querySelector('.spell-item-hl'),\n added_indicator: this.shadowRoot.querySelector('.spell-item-added')\n };\n }\n\n #setupEventListeners () {\n this.elements.accordion.addEventListener('click', this._handleAccordionClick.bind(this));\n this.elements.add_button.addEventListener('click', this._handleAddNewSpell.bind(this));\n }\n\n #removeEventListeners () {\n this.elements.accordion.removeEventListener('click', this._handleAccordionClick);\n this.elements.add_button.removeEventListener('click', this._handleAddNewSpell);\n }\n \n #loadData () {\n this.cur_character = getCurrentCharacter();\n this.spell = spellData.filter((spell) => spell.name === this.dataset.name)[0]; // filter returns an array\n this.elements.accordion_icon.innerHTML = '⌄'; // down-chevron\n }\n\n // Declutters #populateSpellItem\n #setElementContent (selector, content) {\n this.elements[selector].innerHTML = content;\n }\n \n /**\n * Populate the content of the spell item\n */\n #populateSpellItem () {\n const spell = this.spell;\n\n this.#setElementContent('spell_name', `${spell.name}`);\n this.#setElementContent('spell_range', `Range: ${spell.range}`);\n this.#setElementContent('spell_components', `Components: ${spell.components}`);\n this.#setElementContent('spell_duration', `Duration: ${spell.duration}`);\n this.#setElementContent('spell_casting', `Casting Time: ${spell.casting_time}`);\n // Break up each section of the spell description\n this.#setElementContent('spell_description', `Description:
    ${spell.desc.join('

    ')}`);\n \n if (spell.concentration) {\n this.#setElementContent('spell_concentration', `Requires Concentration`);\n }\n\n if (spell.higher_level !== undefined) {\n this.#setElementContent('spell_higher_level', `At Higher Levels:
    ${spell.higher_level}`);\n }\n }\n\n #updateAddedIndicator () {\n const characterSpells = this.cur_character.getSpells(this.dataset.subfield);\n const spellWasAdded = characterSpells.includes(this.spell.name);\n\n if (spellWasAdded) {\n this.#setElementContent('added_indicator', `Added ✓`);\n };\n }\n\n _handleAddNewSpell (ev) {\n const level = this.dataset.subfield;\n\n this.cur_character.setSpells(this.spell, level);\n this.#updateAddedIndicator();\n }\n\n _handleAccordionClick (ev) {\n // Prevent the dropdown from opening on add\n if (ev.target === this.elements.add_button) {\n return;\n }\n\n const panelStyle = this.elements.panel.style;\n\n panelStyle.display = panelStyle.display === 'flex' ? 'none' : 'flex';\n this.elements.accordion_icon.innerHTML = panelStyle.display === 'flex' ? '⌃' : '⌄'; // up chevron and down chevron\n }\n}\n\nif (!window.customElements.get('spell-item')) {\n window.customElements.define('spell-item', SpellItem);\n}\n\nexport default SpellItem;\n", "import spellData from '../5e-SRD-Spells.json';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n\n\n`;\n\nclass AddSpellButton extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n }\n\n connectedCallback () {\n this.addEventListener('click', this._handleClick.bind(this));\n }\n\n disconnectedCallback () {\n this.removeEventListener('click', this._handleClick.bind(this));\n }\n\n // Opens the spell modal\n _handleClick (ev) {\n this.spellDialog = this.spellDialog || document.getElementById('dialog-spells');\n this.spellDialog.clear();\n\n if (this.spellDialog.isOpen) {\n this.spellDialog.close();\n return;\n };\n\n const modal = document.getElementById('spellModal');\n const content = document.importNode(modal.content, true);\n const list = content.querySelector('ul');\n const spellLevel = ev.target.dataset.level;\n\n try {\n const spells = spellData.filter((spell) => spell.level === Number(spellLevel));\n\n spells.forEach(spell => {\n const spellItem = document.createElement('spell-item');\n\n spellItem.dataset.name = spell.name;\n spellItem.dataset.subfield = spell.level;\n\n list.appendChild(spellItem);\n });\n } catch (error) {\n console.log(error);\n const item = document.createElement('div');\n item.innerText = 'Unable to access this resource at the moment.';\n list.appendChild(item);\n };\n\n this.spellDialog.setContent([...content.children]);\n this.spellDialog.open();\n }\n}\n\nif (!window.customElements.get('add-spell-button')) {\n window.customElements.define('add-spell-button', AddSpellButton);\n}\n\nexport default AddSpellButton;\n", "/* eslint-disable no-unused-vars */\nimport EventEmitter from './services/EventEmitter.js';\nimport Manager from './views/Manager.js';\n\n// All the web components we need in the app.\nimport ActionMenu from './views/ActionMenu.js';\nimport NoteListItem from './components/NoteListItem.js';\nimport NoteList from './components/NoteList.js';\nimport SimpleList from './components/SimpleList.js';\nimport TableEditable from './components/TableEditable.js';\nimport SkillListing from './components/SkillListing.js';\nimport AttributeListing from './components/AttributeListing.js';\nimport DiceRoller from './components/DiceRoller.js';\nimport Die from './components/Die.js';\nimport EditableField from './components/EditableField.js';\nimport FooterNav from './components/FooterNav.js';\nimport ConfirmButton from './components/ConfirmButton.js';\nimport Modal from './components/Modal.js';\nimport SpellItem from './components/SpellItem.js';\nimport AddSpellButton from './components/AddSpellButton.js';\n\n/**\n* Register service worker if it's supported\n*/\nif ('serviceWorker' in navigator) {\n navigator.serviceWorker.register(\n './service_worker.js',\n {\n type: 'module'\n }\n );\n}\n\nconst emitter = new EventEmitter();\n\ndocument.querySelector('action-menu').setEmitter(emitter);\n\nManager.initialize({\n emitter,\n prefix: 'charsheet-app-',\n appname: 'character-sheet'\n});\n"], "mappings": "MAIA,IAAqBA,GAArB,KAAkC,CAC9B,aAAe,CACX,KAAK,OAAS,CAAC,EACf,KAAK,MAAQ,EACjB,CAQA,cAAeC,EAAOC,EAAU,CAC5B,OAAO,KAAK,OAAOD,CAAK,EAAE,UAAWE,GAC1BA,EAAK,WAAaD,CAC5B,CACL,CAQA,GAAID,EAAOC,EAAUE,EAAW,K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,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,+BACT,EACA,CACE,MAAS,mBACT,KAAQ,mBACR,KAAQ,CACN,0lBACA,oWACF,EACA,aAAgB,CACd,kJACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,oBACZ,OAAU,GACV,SAAY,WACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,8BACT,EACA,CACE,MAAS,gBACT,KAAQ,gBACR,KAAQ,CACN,qTACA,+zBACA,8HACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,iBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,2BACT,EACA,CACE,MAAS,eACT,KAAQ,eACR,KAAQ,CACN,mVACA,onBACA,wYACF,EACA,aAAgB,CACd,mPACF,E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AAc,MAChB,EACA,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,oBACT,EACA,CACE,MAAS,qBACT,KAAQ,qBACR,KAAQ,CACN,6TACF,EACA,aAAgB,CACd,2IACF,EACA,MAAS,UACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,WACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,uBACT,CACF,EACA,IAAO,gCACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,KAAQ,CACN,ypBACA,sWACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,WACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,mBACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,KAAQ,CACN,8RACF,EACA,MAAS,OACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,iBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,WACT,KAAQ,WACR,IAAO,6BACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,kBACT,EACA,CACE,MAAS,iBACT,KAAQ,iBACR,KAAQ,CACN,6UACF,EACA,aAAgB,CACd,sIACF,EACA,MAAS,OACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,iBACZ,cAAiB,GACjB,aAAgB,iBAChB,MAAS,EACT,OAAU,CACR,YAAe,CACb,MAAS,UACT,KAAQ,UACR,IAAO,2BACT,EACA,qBAAwB,CACtB,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACP,CACF,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,4BACT,EACA,CACE,MAAS,gBACT,KAAQ,gBACR,KAAQ,CACN,4SACA,uFACF,EACA,aAAgB,CACd,gIACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,YAAe,CACb,MAAS,OACT,KAAQ,OACR,IAAO,wBACT,EACA,qBAAwB,CACtB,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,MACP,CACF,EACA,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,eAAkB,CAChB,KAAQ,OACR,KAAQ,EACV,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,uBACT,CACF,EACA,IAAO,2BACT,EACA,CACE,MAAS,iBACT,KAAQ,iBACR,KAAQ,CACN,yTACA,idACA,oNACF,EACA,aAAgB,CACd,iIACF,EACA,MAAS,WACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,mBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,YAAe,CACb,MAAS,YACT,KAAQ,YACR,IAAO,6BACT,EACA,qBAAwB,CACtB,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,MACP,CACF,EACA,eAAkB,CAChB,KAAQ,SACR,KAAQ,CACV,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,4BACT,EACA,CACE,MAAS,gBACT,KAAQ,gBACR,KAAQ,CAC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,EACA,CACE,MAAS,UACT,KAAQ,UACR,KAAQ,CACN,uSACA,4NACA,uIACA,8EACA,8FACA,+DACA,uNACF,EACA,aAAgB,CACd,oNACF,EACA,MAAS,UACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,UACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,uBACT,CACF,EACA,IAAO,qBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,KAAQ,CACN,mNACA,6TACA,kNACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,8CACZ,OAAU,GACV,SAAY,WACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,WACT,KAAQ,WACR,IAAO,0BACT,CACF,EACA,IAAO,qBACT,EACA,CACE,MAAS,sBACT,KAAQ,sBACR,KAAQ,CACN,sWACA,mIACA,gCACA,oDACA,4DACA,6CACA,cACA,2KACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,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,CACR,YAAe,CACb,MAAS,OACT,KAAQ,OACR,IAAO,wBACT,EACA,qBAAwB,CACtB,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,OACL,IAAK,MACP,CACF,EACA,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,OACd,KAAQ,yEACV,EACA,eAAkB,CAChB,KAAQ,OACR,KAAQ,EACV,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,0BACT,EACA,CACE,MAAS,YACT,KAAQ,YACR,KAAQ,CACN,mRACA,yIACA,qBACA,YACA,0MACA,iEACA,wMACA,qDACA,uIACF,EACA,aAAgB,CACd,iJACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,uBACZ,OAAU,GACV,SAAY,iBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,eAAkB,CAChB,KAAQ,SACR,KAAQ,EACV,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,uBACT,EACA,CACE,MAAS,kBACT,KAAQ,kBACR,KAAQ,CACN,2KACA,6CACA,8CACA,iDACA,kDACA,+GACA,2VACA,uCAC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A,iYACA,sSACA,2CACF,EACA,aAAgB,CACd,wIACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,eACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,yBACT,EACA,CACE,MAAS,2BACT,KAAQ,2BACR,KAAQ,CACN,+IACA,iDACA,kDACA,qDACA,uDACA,uGACA,2VACA,uCACF,EACA,aAAgB,CACd,gOACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,eACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,sCACT,EACA,CACE,MAAS,0BACT,KAAQ,0BACR,KAAQ,CACN,iJACA,oDACA,qDACA,wDACA,yDACA,uFACA,8VACA,uCACF,EACA,aAAgB,CACd,gOACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,yCACZ,OAAU,GACV,SAAY,eACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,qCACT,EACA,CACE,MAAS,sBACT,KAAQ,sBACR,KAAQ,CACN,ghBACA,gYACF,EAC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Q,CACN,4PACF,EACA,MAAS,QACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,mDACZ,OAAU,GACV,SAAY,kBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,6BACT,EACA,CACE,MAAS,gBACT,KAAQ,gBACR,KAAQ,CACN,8RACA,sLACA,kVACA,wMACA,oXACA,mbACA,wdACA,ifACA,6JACF,EACA,MAAS,WACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,uCACZ,OAAU,GACV,SAAY,mBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,YAAe,CACb,MAAS,cACT,KAAQ,cACR,IAAO,+BACT,EACA,qBAAwB,CACtB,IAAK,KACP,CACF,EACA,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,eAAkB,CAChB,KAAQ,OACR,KAAQ,GACV,EACA,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,2BACT,EACA,CACE,MAAS,kBACT,KAAQ,kBACR,KAAQ,CACN,wMACA,gXACA,0LACA,sBACA,wBACA,YACA,gBACA,uBACA,iCACA,8BACA,qDACA,oBACA,wBACA,YACA,0BACA,cACA,eACA,eACA,eACA,sBACA,aACA,wBACA,YACA,eACA,wBAC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T,OAAU,CACR,YAAe,CACb,MAAS,UACT,KAAQ,UACR,IAAO,2BACT,EACA,qBAAwB,CACtB,IAAK,KACP,CACF,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,0BACT,EACA,CACE,MAAS,cACT,KAAQ,cACR,KAAQ,CACN,4SACA,kDACA,gEACA,sEACA,6CACA,kQACF,EACA,MAAS,UACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,iBAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,OACd,KAAQ,iFACV,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,yBACT,EACA,CACE,MAAS,iBACT,KAAQ,iBACR,KAAQ,CACN,uPACA,oiBACA,sdACF,EACA,aAAgB,CACd,qGACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,iBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,4BACT,EACA,CACE,MAAS,mBACT,KAAQ,mBACR,KAAQ,CACN,uPACA,oiBACA,gVACA,wIACF,EACA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T,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,sBACT,EACA,CACE,MAAS,eACT,KAAQ,eACR,KAAQ,CACN,odACA,wQACA,4JACA,qVACA,iJACF,EACA,aAAgB,CACd,sOACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,UACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,0BACT,EACA,CACE,MAAS,sBACT,KAAQ,sBACR,KAAQ,CACN,qLACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,mBACZ,cAAiB,GACjB,aAAgB,iBAChB,MAAS,EACT,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,iCACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,KAAQ,CACN,odACA,oJACA,+UACA,4LACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,iBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO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ACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,0BACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,KAAQ,CACN,8SACA,wQACA,6IACA,0dACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,oCACZ,OAAU,GACV,SAAY,iBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,kBACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,KAAQ,CACN,khBACA,sJACA,gIACF,EACA,aAAgB,CACd,4NACF,EACA,MAAS,UACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,UACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,kBACT,EACA,CACE,MAAS,gBACT,KAAQ,gBACR,KAAQ,CACN,qHACA,4MACF,EACA,MAAS,QACT,WAAc,C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ACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,uBACT,EACA,CACE,MAAS,oBACT,KAAQ,oBACR,KAAQ,CACN,+NACF,EACA,aAAgB,CACd,iIACF,EACA,MAAS,UACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,iBAChB,MAAS,EACT,mBAAsB,CACpB,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,WACP,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,+BACT,EACA,CACE,MAAS,kBACT,KAAQ,kBACR,KAAQ,CACN,sgBACA,gVACA,wRACA,8GACF,EACA,aAAgB,CACd,uNACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,SAAY,yEACZ,OAAU,GACV,SAAY,WACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,6BACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,KAAQ,CACN,6JACA,kNACA,gIACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,mBACZ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AAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,0BACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,KAAQ,CACN,mMACA,iJACA,6SACF,EACA,MAAS,OACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,eACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,WACT,KAAQ,WACR,IAAO,6BACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,qBACT,EACA,CACE,MAAS,aACT,KAAQ,aACR,KAAQ,CACN,yGACF,EACA,MAAS,OACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,iBAChB,MAAS,EACT,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,wBACT,EACA,CACE,MAAS,gBACT,KAAQ,gBACR,KAAQ,CACN,+dACA,4XACA,mZACA,qaACA,qGACF,EACA,aAAgB,CACd,kQACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,iB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ACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,yBACT,EACA,CACE,MAAS,eACT,KAAQ,eACR,KAAQ,CACN,+JACA,4PACA,6FACA,0NACF,EACA,MAAS,WACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,0BACT,EACA,CACE,MAAS,eACT,KAAQ,eACR,KAAQ,CACN,yMACA,kHACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,YAAe,CACb,MAAS,SACT,KAAQ,SACR,IAAO,0BACT,EACA,0BAA6B,CAC3B,IAAK,OACL,IAAK,OACL,KAAM,OACN,KAAM,MACR,CACF,EACA,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CAC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AW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,6BACT,EACA,CACE,MAAS,oBACT,KAAQ,oBACR,KAAQ,CACN,8LACF,EACA,aAAgB,CACd,iIACF,EACA,MAAS,UACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,aAChB,MAAS,EACT,mBAAsB,CACpB,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,YACL,IAAK,WACP,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,+BACT,EACA,CACE,MAAS,mBACT,KAAQ,mBACR,KAAQ,CACN,iJACA,yIACA,iFACA,2EACA,kFACA,2FACA,iIACA,qKACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,SACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,8BACT,EACA,CACE,MAAS,kBACT,KAAQ,kBACR,KAAQ,CACN,sQACA,gHACA,mHACA,wHACA,oHACA,iHACA,waACA,4cACA,uFACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,qBAAwB,CACtB,IAAK,MACP,CACF,EACA,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,QACd,KAAQ,qEACV,EACA,eAAkB,CAChB,KAAQ,OACR,KAAQ,EACV,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,6BACT,EACA,CACE,MAAS,iBACT,KAAQ,iBACR,KAAQ,CACN,seACA,qZACA,2VACA,0RACA,4QACA,gPACA,iMACA,mPACA,yLACA,4aACA,oLACA,qkBACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,aACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,eAAkB,CAChB,KAAQ,OACR,KAAQ,EACV,EACA,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,4BACT,EACA,CACE,MAAS,kBACT,KAAQ,kBACR,KAAQ,CACN,qNACA,iIACA,yEACA,gHACA,8HACA,kEACA,yDACA,qDACA,uFACF,EACA,aAAgB,CACd,gQACF,EACA,MAAS,WACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,oGACZ,OAAU,GACV,SAAY,WACZ,cAAiB,GACjB,aAAgB,aAChB,MAAS,EACT,eAAkB,CAChB,KAAQ,OACR,KAA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,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,0BACT,EACA,CACE,MAAS,aACT,KAAQ,aACR,KAAQ,CACN,uOACA,mOACF,EACA,MAAS,QACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,iCACZ,OAAU,GACV,SAAY,SACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,mBAAsB,CACpB,IAAK,UACP,EACA,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,wBACT,EACA,CACE,MAAS,cACT,KAAQ,cACR,KAAQ,CACN,sRACA,iQACA,kBACA,YACA,yBACA,0BACA,8BACA,wBACA,wBACA,wBACA,4BACA,0BACA,uBACA,uBACA,kCACA,8BACA,oBACA,uBACA,8NACF,EACA,MAAS,QACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,4EACZ,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,SAChB,MAAS,EACT,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,yBACT,EACA,CACE,MAAS,eACT,KAAQ,eACR,KAAQ,CACN,uNACF,EACA,MAAS,QACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,M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,IAAO,0BACT,CACF,EACA,IAAO,uBACT,EACA,CACE,MAAS,gBACT,KAAQ,gBACR,KAAQ,CACN,mHACA,sFACF,EACA,aAAgB,CACd,kIACF,EACA,MAAS,WACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,YAAe,CACb,MAAS,OACT,KAAQ,OACR,IAAO,wBACT,EACA,qBAAwB,CACtB,IAAK,KACP,CACF,EACA,OAAU,CACR,MAAS,YACT,KAAQ,YACR,IAAO,8BACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,uBACT,CACF,EACA,IAAO,2BACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,KAAQ,CACN,2WACA,gCACA,YACA,qDACA,+CACA,+CACA,GACA,iCACA,YACA,+BACA,iCACA,8DACA,+GACA,kVACA,iLACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,8GACZ,OAAU,GACV,SAAY,mBACZ,cAAiB,GACjB,aAAgB,aAChB,MAAS,EACT,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,QACT,KAAQ,QACR,IAAO,oBACT,EACA,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,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,CAChB,KAAQ,OACR,KAAQ,EACV,EACA,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,oBACT,EACA,CACE,MAAS,cACT,KAAQ,cACR,KAAQ,CACN,6aACA,kbACA,uIACA,2NACA,gTACA,iOACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,mBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,eAAkB,CAChB,KAAQ,SACR,KAAQ,EACV,EACA,OAAU,CACR,MAAS,gBACT,KAAQ,gBACR,IAAO,kCACT,EACA,QAAW,CACT,CACE,MAAS,WACT,KAAQ,WACR,IAAO,uBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,yBACT,EACA,CACE,MAAS,kBACT,KAAQ,kBACR,KAAQ,CACN,oPACA,qOACF,EACA,MAAS,UACT,WAAc,CAAC,IAAK,IAAK,GAAG,EAC5B,SAAY,2DACZ,OAAU,GACV,SAAY,SACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,6BACT,EACA,CACE,MAAS,WACT,KAAQ,WACR,KAAQ,CACN,+UACA,2OACA,mEACA,wBACA,+CACA,gDACA,qDACA,qDACA,mDACA,mDACA,mDACA,8GACA,4OACA,2IACA,qGACA,qEACA,0HACA,kNACA,uFACA,0oBACA,ufACA,0QACF,EACA,MAAS,UACT,WAAc,CAAC,GAAG,EAClB,OAAU,GAC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ACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,4BACT,EACA,CACE,MAAS,iBACT,KAAQ,iBACR,KAAQ,CACN,oXACF,EACA,aAAgB,CACd,gIACF,EACA,MAAS,OACT,WAAc,CAAC,IAAK,GAAG,EACvB,OAAU,GACV,SAAY,iBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,YAAe,QACf,OAAU,CACR,YAAe,CACb,MAAS,WACT,KAAQ,WACR,IAAO,4BACT,EACA,qBAAwB,CACtB,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACP,CACF,EACA,OAAU,CACR,MAAS,aACT,KAAQ,aACR,IAAO,+BACT,EACA,QAAW,CACT,CACE,MAAS,UACT,KAAQ,UACR,IAAO,sBACT,EACA,CACE,MAAS,SACT,KAAQ,SACR,IAAO,qBACT,CACF,EACA,WAAc,CACZ,CACE,MAAS,OACT,KAAQ,OACR,IAAO,sBACT,CACF,EACA,IAAO,4BACT,EACA,CACE,MAAS,kBACT,KAAQ,kBACR,KAAQ,CACN,qUACA,8GACF,EACA,MAAS,UACT,WAAc,CAAC,GAAG,EAClB,OAAU,GACV,SAAY,gBACZ,cAAiB,GACjB,aAAgB,WAChB,MAAS,EACT,OAAU,CACR,YAAe,CACb,MAAS,UACT,KAAQ,UACR,IAAO,2BACT,EACA,0BAA6B,CAC3B,IAAK,MACL,IAAK,MACL,KAAM,MACN,KAAM,KACR,CACF,EACA,GAAM,CACJ,QAAW,CACT,MAAS,MACT,KAAQ,MACR,IAAO,yBACT,EACA,WAAc,MAChB,EACA,OAAU,CACR,MAAS,cACT,KAAQ,cACR,IAAO,gCACT,EACA,QAAW,CACT,CACE,MAAS,OACT,KAAQ,OACR,IAAO,mBACT,CACF,EACA,WAAc,CAAC,EACf,IAAO,6BACT,EACA,CACE,MAAS,eACT,KAAQ,eACR,KAAQ,C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,EAAY,SAAS,cAAc,YAAY,EAErDA,EAAU,QAAQ,KAAOD,EAAM,KAC/BC,EAAU,QAAQ,SAAWD,EAAM,MAEnCH,EAAK,YAAYI,CAAS,CAC9B,CAAC,CACL,OAASC,EAAO,CACZ,QAAQ,IAAIA,CAAK,EACjB,IAAMC,EAAO,SAAS,cAAc,KAAK,EACzCA,EAAK,UAAY,gDACjBN,EAAK,YAAYM,CAAI,CACzB,CAEA,KAAK,YAAY,WAAW,CAAC,GAAGP,EAAQ,QAAQ,CAAC,EACjD,KAAK,YAAY,KAAK,CAC1B,CACJ,EAEK,OAAO,eAAe,IAAI,kBAAkB,GAC7C,OAAO,eAAe,OAAO,mBAAoBH,EAAc,ECxC/D,kBAAmB,WACnB,UAAU,cAAc,SACpB,sBACA,CACI,KAAM,QACV,CACJ,EAGJ,IAAMW,GAAU,IAAIC,GAEpB,SAAS,cAAc,aAAa,EAAE,WAAWD,EAAO,EAExDE,GAAQ,WAAW,CACf,QAAAF,GACA,OAAQ,iBACR,QAAS,iBACb,CAAC", "names": ["EventEmitter", "event", "listener", "item", "boundObj", "index", "wrap", "binder", "args", "listenObj", "CharacterNote", "header", "text", "obj", "prop", "Character", "key", "charname", "updated", "key_prev", "version", "noteArray", "value", "item", "CharacterNote", "obj", "prop", "el", "attributes", "skillAttributes", "skillLevels", "Weapon", "name", "attack", "damage", "notes", "obj", "prop", "Character5e", "Character", "key", "charname", "charclass", "race", "background", "alignment", "level", "experience", "inspiration", "armor_class", "speed", "hp_cur", "hp_max", "hd_cur", "hd_max", "deathSave", "class_points", "str", "dex", "con", "intel", "wis", "cha", "saves", "skills", "weapons", "proficiencies_other", "languages", "traits", "ideals", "bonds", "flaws", "appearance", "equipment", "cp", "sp", "gp", "pp", "features", "notes", "notes_adv", "notes_cam", "npcs", "factions", "partymembers", "spell_ability", "spell_save", "spell_attack", "spell_slots", "spell_slots_cur", "spells", "updated", "key_prev", "version", "sleight", "item", "Weapon", "newVal", "cur", "prof", "newProf", "attribute", "value", "skill", "skillAttributes", "score", "raw", "skillLevels", "newValue", "curValue", "attr", "profMod", "checked", "spell", "newSpellsList", "newSpellSlotsLength", "CharacterVagabonds", "Character", "key", "charname", "level", "conflict_approach", "goal", "gimmick", "background", "foreground", "weakness", "core_flaw", "techniques", "traits", "hp_cur", "hp_max", "armor", "initiative", "lineage", "experience", "appearance", "personality", "inventory", "coins", "injuries", "notes", "notes_adv", "notes_cam", "npcs", "factions", "partymembers", "updated", "key_prev", "version", "Storage", "prefix", "key", "txt", "object", "e", "keys", "key_regex", "i", "objects", "char_obj", "Storage_default", "stringToByteArray", "str", "out", "p", "i", "c", "byteArrayToString", "bytes", "pos", "c1", "c2", "c3", "c4", "u", "base64", "input", "webSafe", "byteToCharMap", "output", "byte1", "haveByte2", "byte2", "haveByte3", "byte3", "outByte1", "outByte2", "outByte3", "outByte4", "charToByteMap", "byte4", "DecodeBase64StringError", "base64Encode", "utf8Bytes", "base64urlEncodeWithoutPadding", "base64Decode", "getGlobal", "getDefaultsFromGlobal", "getDefaultsFromEnvVariable", "defaultsJsonString", "getDefaultsFromCookie", "match", "decoded", "base64Decode", "getDefaults", "e", "getDefaultEmulatorHost", "productName", "_a", "_b", "getDefaultEmulatorHostnameAndPort", "host", "separatorIndex", "port", "getDefaultAppConfig", "getExperimentalSetting", "name", "Deferred", "resolve", "reject", "callback", "error", "value", "createMockUserToken", "token", "projectId", "header", "project", "iat", "sub", "payload", "base64urlEncodeWithoutPadding", "getUA", "isMobileCordova", "isNode", "forceEnvironment", "isBrowserExtension", "runtime", "isReactNative", "isIE", "ua", "getUA", "isSafari", "isNode", "isIndexedDBAvailable", "validateIndexedDBOpenable", "resolve", "reject", "preExist", "DB_CHECK_NAME", "request", "_a", "error", "ERROR_NAME", "FirebaseError", "_FirebaseError", "code", "message", "customData", "ErrorFactory", "service", "serviceName", "errors", "data", "fullCode", "template", "replaceTemplate", "fullMessage", "PATTERN", "_", "key", "value", "isEmpty", "obj", "key", "deepEqual", "a", "b", "aKeys", "bKeys", "k", "aProp", "bProp", "isObject", "thing", "querystring", "querystringParams", "params", "key", "value", "arrayVal", "querystringDecode", "obj", "token", "extractQuerystring", "url", "queryStart", "fragmentStart", "createSubscribe", "executor", "onNoObservers", "proxy", "ObserverProxy", "e", "value", "observer", "error", "nextOrObserver", "complete", "implementsAnyMethods", "noop", "unsub", "i", "fn", "err", "implementsAnyMethods", "obj", "methods", "method", "noop", "MAX_VALUE_MILLIS", "getModularInstance", "service", "Component", "name", "instanceFactory", "type", "mode", "multipleInstances", "props", "callback", "DEFAULT_ENTRY_NAME", "Provider", "container", "identifier", "normalizedIdentifier", "deferred", "Deferred", "instance", "options", "optional", "_a", "e", "component", "isComponentEager", "instanceIdentifier", "instanceDeferred", "services", "service", "opts", "normalizedDeferredIdentifier", "existingCallbacks", "existingInstance", "callbacks", "normalizeIdentifierForFactory", "ComponentContainer", "provider", "instances", "LogLevel", "levelStringToEnum", "defaultLogLevel", "ConsoleMethod", "defaultLogHandler", "instance", "logType", "args", "now", "method", "Logger", "name", "val", "instanceOfAny", "object", "constructors", "c", "idbProxyableTypes", "cursorAdvanceMethods", "getIdbProxyableTypes", "getCursorAdvanceMethods", "cursorRequestMap", "transactionDoneMap", "transactionStoreNamesMap", "transformCache", "reverseTransformCache", "promisifyRequest", "request", "promise", "resolve", "reject", "unlisten", "success", "error", "wrap", "value", "cacheDonePromiseForTransaction", "tx", "done", "complete", "idbProxyTraps", "target", "prop", "receiver", "replaceTraps", "callback", "wrapFunction", "func", "storeNames", "args", "unwrap", "transformCachableValue", "newValue", "openDB", "name", "version", "blocked", "upgrade", "blocking", "terminated", "request", "openPromise", "wrap", "event", "db", "readMethods", "writeMethods", "cachedMethods", "getMethod", "target", "prop", "targetFuncName", "useIndex", "isWrite", "method", "storeName", "args", "tx", "replaceTraps", "oldTraps", "receiver", "PlatformLoggerServiceImpl", "container", "provider", "isVersionServiceProvider", "service", "logString", "component", "logger", "Logger", "DEFAULT_ENTRY_NAME", "PLATFORM_LOG_STRING", "appName", "appCompatName", "analyticsName", "analyticsCompatName", "appCheckName", "appCheckCompatName", "authName", "authCompatName", "databaseName", "databaseCompatName", "functionsName", "functionsCompatName", "installationsName", "installationsCompatName", "messagingName", "messagingCompatName", "performanceName", "performanceCompatName", "remoteConfigName", "remoteConfigCompatName", "storageName", "storageCompatName", "firestoreName", "firestoreCompatName", "vertexName", "packageName", "_apps", "_serverApps", "_components", "_addComponent", "app", "e", "_registerComponent", "component", "componentName", "_components", "logger", "app", "_apps", "_addComponent", "serverApp", "_serverApps", "_getProvider", "name", "heartbeatController", "_isFirebaseServerApp", "obj", "ERRORS", "ERROR_FACTORY", "ErrorFactory", "FirebaseAppImpl", "options", "config", "container", "Component", "val", "SDK_VERSION", "version", "initializeApp", "_options", "rawConfig", "options", "config", "DEFAULT_ENTRY_NAME", "name", "ERROR_FACTORY", "getDefaultAppConfig", "existingApp", "_apps", "deepEqual", "container", "ComponentContainer", "component", "_components", "newApp", "FirebaseAppImpl", "getApp", "name", "DEFAULT_ENTRY_NAME", "app", "_apps", "getDefaultAppConfig", "initializeApp", "ERROR_FACTORY", "registerVersion", "libraryKeyOrName", "version", "variant", "library", "_a", "PLATFORM_LOG_STRING", "libraryMismatch", "versionMismatch", "warning", "logger", "_registerComponent", "Component", "DB_NAME", "DB_VERSION", "STORE_NAME", "dbPromise", "getDbPromise", "openDB", "db", "oldVersion", "e", "ERROR_FACTORY", "readHeartbeatsFromIndexedDB", "app", "tx", "result", "computeKey", "FirebaseError", "logger", "idbGetError", "writeHeartbeatsToIndexedDB", "heartbeatObject", "MAX_HEADER_BYTES", "STORED_HEARTBEAT_RETENTION_MAX_MILLIS", "HeartbeatServiceImpl", "container", "HeartbeatStorageImpl", "agent", "date", "getUTCDateString", "_a", "_b", "singleDateHeartbeat", "hbTimestamp", "heartbeatsToSend", "unsentEntries", "extractHeartbeatsForHeader", "headerString", "base64urlEncodeWithoutPadding", "heartbeatsCache", "maxSize", "heartbeatEntry", "hb", "countBytes", "isIndexedDBAvailable", "validateIndexedDBOpenable", "idbHeartbeatObject", "heartbeatsObject", "existingHeartbeatsObject", "registerCoreComponents", "variant", "_registerComponent", "Component", "PlatformLoggerServiceImpl", "registerVersion", "name", "version", "h", "k", "f", "a", "c", "d", "e", "g", "b", "r", "l", "m", "n", "p", "q", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "F", "E", "G", "H", "I", "J", "Md5", "bloom_blob_es2018", "Integer", "global", "h", "aa", "a", "b", "c", "ba", "global", "ca", "da", "d", "e", "ea", "f", "fa", "k", "ha", "n", "ia", "ja", "p", "ka", "r", "g", "m", "la", "ma", "na", "t", "u", "oa", "pa", "qa", "ra", "sa", "ta", "ua", "va", "wa", "xa", "za", "Aa", "Ba", "Ca", "x", "y", "Ea", "Da", "z", "A", "Fa", "C", "Ga", "D", "Ha", "Ia", "Ja", "Ka", "La", "Ma", "Na", "Oa", "Qa", "Ra", "Sa", "Ta", "Ua", "Va", "Wa", "Xa", "Ya", "Za", "$a", "E", "F", "ab", "q", "bb", "cb", "eb", "G", "fb", "gb", "hb", "ib", "jb", "kb", "lb", "mb", "H", "nb", "ob", "I", "pb", "qb", "rb", "J", "sb", "K", "tb", "ub", "vb", "wb", "l", "v", "w", "xb", "L", "yb", "zb", "Ab", "Bb", "Cb", "Db", "M", "Eb", "Fb", "Gb", "Hb", "Ib", "N", "Jb", "Kb", "Lb", "Mb", "P", "O", "Nb", "Ob", "Pb", "Q", "Qb", "Rb", "B", "Sb", "Tb", "Ub", "Vb", "Wb", "Xb", "Yb", "Zb", "$b", "ac", "R", "ya", "bc", "db", "S", "cc", "dc", "ec", "fc", "gc", "hc", "ic", "jc", "kc", "lc", "mc", "nc", "oc", "pc", "T", "qc", "rc", "sc", "tc", "uc", "vc", "wc", "xc", "yc", "zc", "Ac", "Bc", "Cc", "U", "V", "Dc", "Ec", "Fc", "W", "Gc", "Hc", "Ic", "Jc", "Kc", "Lc", "Mc", "Nc", "Oc", "Pc", "X", "Qc", "Rc", "Sc", "Tc", "Uc", "Vc", "Wc", "Xc", "Yc", "Zc", "$c", "ad", "bd", "cd", "dd", "ed", "fd", "gd", "hd", "Y", "Z", "id", "jd", "createWebChannelTransport", "webchannel_blob_es2018", "getStatEventTarget", "Event", "Stat", "ErrorCode", "EventType", "WebChannel", "FetchXmlHttpFactory", "XhrIo", "User", "constructor", "uid", "this", "isAuthenticated", "toKey", "isEqual", "otherUser", "UNAUTHENTICATED", "GOOGLE_CREDENTIALS", "FIRST_PARTY", "MOCK_USER", "SDK_VERSION", "__PRIVATE_logClient", "Logger", "__PRIVATE_getLogLevel", "logLevel", "__PRIVATE_logDebug", "msg", "obj", "__PRIVATE_logClient", "logLevel", "LogLevel", "DEBUG", "args", "map", "__PRIVATE_argToString", "debug", "SDK_VERSION", "__PRIVATE_logError", "ERROR", "error", "__PRIVATE_logWarn", "WARN", "warn", "value", "JSON", "stringify", "e", "fail", "__PRIVATE_failure", "message", "Error", "__PRIVATE_hardAssert", "assertion", "__PRIVATE_debugCast", "obj", "constructor", "Code", "OK", "CANCELLED", "UNKNOWN", "INVALID_ARGUMENT", "DEADLINE_EXCEEDED", "NOT_FOUND", "ALREADY_EXISTS", "PERMISSION_DENIED", "UNAUTHENTICATED", "RESOURCE_EXHAUSTED", "FAILED_PRECONDITION", "ABORTED", "OUT_OF_RANGE", "UNIMPLEMENTED", "INTERNAL", "UNAVAILABLE", "DATA_LOSS", "FirestoreError", "FirebaseError", "code", "message", "super", "this", "toString", "name", "__PRIVATE_Deferred", "promise", "Promise", "resolve", "reject", "__PRIVATE_OAuthToken", "value", "user", "type", "headers", "Map", "set", "__PRIVATE_EmptyAuthCredentialsProvider", "getToken", "invalidateToken", "start", "asyncQueue", "changeListener", "enqueueRetryable", "User", "shutdown", "__PRIVATE_EmulatorAuthCredentialsProvider", "token", "__PRIVATE_FirebaseAuthCredentialsProvider", "__PRIVATE_authProvider", "currentUser", "__PRIVATE_tokenCounter", "forceRefresh", "auth", "__PRIVATE_lastTokenId", "__PRIVATE_guardedChangeListener", "__PRIVATE_nextToken", "__PRIVATE_tokenListener", "__PRIVATE_getUser", "__PRIVATE_awaitNextToken", "__PRIVATE_currentTokenAttempt", "async", "__PRIVATE_registerAuth", "__PRIVATE_logDebug", "addAuthTokenListener", "onInit", "setTimeout", "getImmediate", "optional", "__PRIVATE_initialTokenCounter", "then", "__PRIVATE_tokenData", "__PRIVATE_hardAssert", "accessToken", "removeAuthTokenListener", "__PRIVATE_currentUid", "getUid", "__PRIVATE_FirstPartyToken", "__PRIVATE_sessionIndex", "__PRIVATE_iamToken", "__PRIVATE_authTokenFactory", "FIRST_PARTY", "__PRIVATE__headers", "__PRIVATE_getAuthToken", "__PRIVATE_authHeaderTokenValue", "__PRIVATE_FirstPartyAuthCredentialsProvider", "AppCheckToken", "length", "__PRIVATE_FirebaseAppCheckTokenProvider", "__PRIVATE_appCheckProvider", "appCheck", "__PRIVATE_latestAppCheckToken", "onTokenChanged", "tokenResult", "error", "__PRIVATE_tokenUpdated", "__PRIVATE_registerAppCheck", "addTokenListener", "removeTokenListener", "__PRIVATE_randomBytes", "__PRIVATE_nBytes", "crypto", "self", "bytes", "Uint8Array", "getRandomValues", "__PRIVATE_i", "Math", "floor", "random", "__PRIVATE_AutoId", "static", "__PRIVATE_chars", "__PRIVATE_maxMultiple", "length", "__PRIVATE_autoId", "charAt", "__PRIVATE_primitiveComparator", "left", "right", "__PRIVATE_arrayEquals", "comparator", "every", "value", "index", "Timestamp", "constructor", "seconds", "nanoseconds", "this", "FirestoreError", "Code", "INVALID_ARGUMENT", "static", "fromMillis", "Date", "now", "date", "getTime", "milliseconds", "Math", "floor", "nanos", "toDate", "toMillis", "_compareTo", "other", "__PRIVATE_primitiveComparator", "isEqual", "toString", "toJSON", "valueOf", "__PRIVATE_adjustedSeconds", "String", "padStart", "SnapshotVersion", "timestamp", "value", "compareTo", "toMicroseconds", "toTimestamp", "BasePath", "segments", "offset", "length", "undefined", "fail", "len", "comparator", "child", "nameOrPath", "slice", "limit", "forEach", "segment", "push", "construct", "popFirst", "size", "popLast", "firstSegment", "lastSegment", "get", "index", "isEmpty", "isPrefixOf", "__PRIVATE_i", "isImmediateParentOf", "potentialChild", "fn", "end", "toArray", "p1", "p2", "min", "left", "right", "ResourcePath", "canonicalString", "join", "toUriEncodedString", "map", "encodeURIComponent", "pathComponents", "path", "indexOf", "split", "filter", "__PRIVATE_identifierRegExp", "FieldPath", "test", "str", "replace", "isValidIdentifier", "isKeyField", "current", "__PRIVATE_addCurrentSegment", "__PRIVATE_inBackticks", "c", "next", "DocumentKey", "fromString", "name", "emptyPath", "collectionGroup", "hasCollectionId", "collectionId", "getCollectionGroup", "getCollectionPath", "k1", "k2", "FieldIndex", "indexId", "fields", "indexState", "FieldIndex", "UNKNOWN_ID", "__PRIVATE_newIndexOffsetSuccessorFromReadTime", "readTime", "largestBatchId", "__PRIVATE_successorSeconds", "toTimestamp", "seconds", "__PRIVATE_successorNanos", "nanoseconds", "__PRIVATE_successor", "SnapshotVersion", "fromTimestamp", "Timestamp", "IndexOffset", "DocumentKey", "empty", "__PRIVATE_newIndexOffsetFromDocument", "document", "key", "constructor", "documentKey", "this", "static", "min", "max", "__PRIVATE_indexOffsetComparator", "left", "right", "cmp", "compareTo", "comparator", "__PRIVATE_primitiveComparator", "__PRIVATE_PRIMARY_LEASE_LOST_ERROR_MSG", "PersistenceTransaction", "onCommittedListeners", "addOnCommittedListener", "listener", "push", "raiseOnCommittedEvent", "forEach", "async", "__PRIVATE_ignoreIfPrimaryLeaseLoss", "err", "code", "Code", "FAILED_PRECONDITION", "message", "__PRIVATE_logDebug", "PersistencePromise", "callback", "nextCallback", "catchCallback", "result", "error", "undefined", "isDone", "callbackAttached", "value", "catch", "fn", "next", "nextFn", "catchFn", "fail", "wrapFailure", "wrapSuccess", "resolve", "reject", "toPromise", "Promise", "wrapUserFunction", "e", "all", "expectedCount", "__PRIVATE_resolvedCount", "done", "element", "predicates", "p", "predicate", "__PRIVATE_isTrue", "collection", "f", "__PRIVATE_promises", "r", "s", "call", "waitFor", "array", "length", "results", "Array", "__PRIVATE_i", "current", "condition", "action", "process", "__PRIVATE_getAndroidVersion", "__PRIVATE_ua", "__PRIVATE_androidVersionRegex", "match", "version", "split", "slice", "join", "Number", "__PRIVATE_isIndexedDbTransactionError", "e", "name", "__PRIVATE_ListenSequence", "constructor", "previousValue", "__PRIVATE_sequenceNumberSyncer", "this", "sequenceNumberHandler", "sequenceNumber", "__PRIVATE_setPreviousValue", "__PRIVATE_writeNewSequenceNumber", "writeSequenceNumber", "__PRIVATE_externalPreviousValue", "Math", "max", "next", "__PRIVATE_nextValue", "__PRIVATE_INVALID", "__PRIVATE_isNullOrUndefined", "value", "__PRIVATE_isNegativeZero", "isSafeInteger", "Number", "isInteger", "MAX_SAFE_INTEGER", "MIN_SAFE_INTEGER", "__PRIVATE_DbDocumentMutationPlaceholder", "__PRIVATE_V11_STORES", "__PRIVATE_V12_STORES", "__PRIVATE_V13_STORES", "__PRIVATE_V14_STORES", "__PRIVATE_V15_STORES", "__PRIVATE_objectSize", "obj", "count", "key", "Object", "prototype", "hasOwnProperty", "call", "forEach", "fn", "isEmpty", "obj", "key", "Object", "prototype", "hasOwnProperty", "call", "SortedMap", "constructor", "comparator", "root", "this", "LLRBNode", "EMPTY", "insert", "value", "copy", "BLACK", "remove", "get", "node", "cmp", "left", "right", "indexOf", "__PRIVATE_prunedNodes", "size", "minKey", "maxKey", "inorderTraversal", "action", "forEach", "fn", "k", "v", "toString", "__PRIVATE_descriptions", "push", "join", "reverseTraversal", "getIterator", "SortedMapIterator", "getIteratorFrom", "getReverseIterator", "getReverseIteratorFrom", "startKey", "isReverse", "nodeStack", "getNext", "pop", "result", "hasNext", "length", "peek", "color", "RED", "min", "n", "fixUp", "removeMin", "isRed", "moveRedLeft", "__PRIVATE_smallest", "rotateRight", "moveRedRight", "rotateLeft", "colorFlip", "__PRIVATE_nl", "__PRIVATE_nr", "checkMaxDepth", "__PRIVATE_blackDepth", "check", "Math", "pow", "fail", "LLRBEmptyNode", "SortedSet", "data", "has", "elem", "first", "last", "cb", "forEachInRange", "range", "iter", "forEachWhile", "start", "firstAfterOrEqual", "SortedSetIterator", "add", "delete", "unionWith", "other", "isEqual", "__PRIVATE_thisIt", "__PRIVATE_otherIt", "__PRIVATE_thisElem", "__PRIVATE_otherElem", "toArray", "__PRIVATE_res", "targetId", "FieldMask", "constructor", "fields", "this", "sort", "FieldPath", "comparator", "static", "unionWith", "extraFields", "__PRIVATE_mergedMaskSet", "SortedSet", "fieldPath", "add", "toArray", "covers", "__PRIVATE_fieldMaskPath", "isPrefixOf", "isEqual", "other", "__PRIVATE_arrayEquals", "l", "r", "__PRIVATE_Base64DecodeError", "Error", "name", "ByteString", "constructor", "binaryString", "this", "static", "base64", "__PRIVATE_encoded", "atob", "e", "DOMException", "__PRIVATE_Base64DecodeError", "array", "__PRIVATE_i", "length", "String", "fromCharCode", "Symbol", "iterator", "next", "value", "charCodeAt", "done", "undefined", "toBase64", "raw", "btoa", "__PRIVATE_encodeBase64", "toUint8Array", "buffer", "Uint8Array", "approximateByteSize", "compareTo", "other", "__PRIVATE_primitiveComparator", "isEqual", "EMPTY_BYTE_STRING", "__PRIVATE_ISO_TIMESTAMP_REG_EXP", "RegExp", "__PRIVATE_normalizeTimestamp", "date", "__PRIVATE_hardAssert", "nanos", "__PRIVATE_fraction", "exec", "__PRIVATE_nanoStr", "substr", "Number", "__PRIVATE_parsedDate", "Date", "seconds", "Math", "floor", "getTime", "__PRIVATE_normalizeNumber", "__PRIVATE_normalizeByteString", "blob", "fromBase64String", "fromUint8Array", "__PRIVATE_isServerTimestamp", "_b", "_a", "mapValue", "fields", "stringValue", "__PRIVATE_getPreviousValue", "previousValue", "__PRIVATE_getLocalWriteTime", "localWriteTime", "timestampValue", "Timestamp", "DatabaseInfo", "databaseId", "appId", "persistenceKey", "host", "ssl", "forceLongPolling", "autoDetectLongPolling", "longPollingOptions", "useFetchStreams", "DatabaseId", "projectId", "database", "isDefaultDatabase", "MAX_VALUE", "__type__", "__PRIVATE_typeOrder", "value", "__PRIVATE_isServerTimestamp", "__PRIVATE_isMaxValue", "fail", "__PRIVATE_valueEquals", "left", "right", "__PRIVATE_leftType", "booleanValue", "__PRIVATE_getLocalWriteTime", "isEqual", "timestampValue", "length", "__PRIVATE_leftTimestamp", "__PRIVATE_normalizeTimestamp", "__PRIVATE_rightTimestamp", "seconds", "nanos", "__PRIVATE_timestampEquals", "stringValue", "__PRIVATE_normalizeByteString", "bytesValue", "__PRIVATE_blobEquals", "referenceValue", "__PRIVATE_normalizeNumber", "geoPointValue", "latitude", "longitude", "__PRIVATE_geoPointEquals", "integerValue", "__PRIVATE_n1", "doubleValue", "__PRIVATE_n2", "__PRIVATE_isNegativeZero", "isNaN", "__PRIVATE_numberEquals", "__PRIVATE_arrayEquals", "arrayValue", "values", "__PRIVATE_leftMap", "mapValue", "fields", "__PRIVATE_rightMap", "__PRIVATE_objectSize", "key", "hasOwnProperty", "__PRIVATE_arrayValueContains", "__PRIVATE_haystack", "__PRIVATE_needle", "find", "v", "__PRIVATE_valueCompare", "__PRIVATE_rightType", "__PRIVATE_primitiveComparator", "__PRIVATE_leftNumber", "__PRIVATE_rightNumber", "__PRIVATE_compareNumbers", "__PRIVATE_compareTimestamps", "__PRIVATE_leftBytes", "__PRIVATE_rightBytes", "compareTo", "__PRIVATE_leftPath", "__PRIVATE_rightPath", "__PRIVATE_leftSegments", "split", "__PRIVATE_rightSegments", "__PRIVATE_i", "comparison", "__PRIVATE_leftArray", "__PRIVATE_rightArray", "compare", "MAX_VALUE", "__PRIVATE_leftKeys", "Object", "keys", "__PRIVATE_rightKeys", "sort", "__PRIVATE_keyCompare", "canonicalId", "__PRIVATE_canonifyValue", "timestamp", "__PRIVATE_normalizedTimestamp", "byteString", "toBase64", "__PRIVATE_canonifyByteString", "DocumentKey", "fromName", "toString", "__PRIVATE_canonifyReference", "__PRIVATE_geoPoint", "__PRIVATE_canonifyGeoPoint", "result", "first", "__PRIVATE_sortedKeys", "__PRIVATE_canonifyMap", "isInteger", "value", "isArray", "__PRIVATE_isNullValue", "__PRIVATE_isNanValue", "isNaN", "Number", "doubleValue", "__PRIVATE_isMapValue", "__PRIVATE_deepClone", "source", "geoPointValue", "Object", "assign", "timestampValue", "mapValue", "target", "fields", "forEach", "key", "val", "arrayValue", "values", "__PRIVATE_i", "length", "__PRIVATE_isMaxValue", "stringValue", "ObjectValue", "constructor", "value", "this", "static", "mapValue", "field", "path", "isEmpty", "__PRIVATE_currentLevel", "__PRIVATE_i", "length", "fields", "get", "__PRIVATE_isMapValue", "lastSegment", "set", "getFieldsMap", "popLast", "__PRIVATE_deepClone", "setAll", "data", "parent", "FieldPath", "emptyPath", "__PRIVATE_upserts", "__PRIVATE_deletes", "forEach", "isImmediateParentOf", "__PRIVATE_fieldsMap", "applyChanges", "push", "delete", "__PRIVATE_nestedValue", "isEqual", "other", "__PRIVATE_valueEquals", "current", "next", "__PRIVATE_inserts", "key", "val", "clone", "__PRIVATE_extractFieldMask", "__PRIVATE_currentPath", "__PRIVATE_nestedFields", "__PRIVATE_nestedPath", "child", "FieldMask", "MutableDocument", "documentType", "version", "readTime", "createTime", "documentState", "documentKey", "SnapshotVersion", "min", "empty", "convertToFoundDocument", "convertToNoDocument", "convertToUnknownDocument", "setHasCommittedMutations", "setHasLocalMutations", "setReadTime", "hasLocalMutations", "hasCommittedMutations", "hasPendingWrites", "isValidDocument", "isFoundDocument", "isNoDocument", "isUnknownDocument", "mutableCopy", "toString", "JSON", "stringify", "Bound", "position", "inclusive", "__PRIVATE_boundCompareToDocument", "bound", "orderBy", "doc", "comparison", "__PRIVATE_orderByComponent", "component", "isKeyField", "DocumentKey", "comparator", "fromName", "referenceValue", "__PRIVATE_valueCompare", "dir", "__PRIVATE_boundEquals", "left", "right", "OrderBy", "__PRIVATE_orderByEquals", "Filter", "FieldFilter", "op", "super", "createKeyFieldInFilter", "__PRIVATE_KeyFieldFilter", "__PRIVATE_ArrayContainsFilter", "__PRIVATE_InFilter", "__PRIVATE_NotInFilter", "__PRIVATE_ArrayContainsAnyFilter", "__PRIVATE_KeyFieldInFilter", "__PRIVATE_KeyFieldNotInFilter", "matches", "matchesComparison", "__PRIVATE_typeOrder", "fail", "isInequality", "indexOf", "getFlattenedFilters", "getFilters", "CompositeFilter", "filters", "__PRIVATE_memoizedFlattenedFilters", "__PRIVATE_compositeFilterIsConjunction", "undefined", "find", "filter", "reduce", "result", "__PRIVATE_subfilter", "concat", "Object", "assign", "compositeFilter", "__PRIVATE_compositeFilterIsFlatConjunction", "compositeFilter", "__PRIVATE_compositeFilterIsFlat", "__PRIVATE_compositeFilterIsConjunction", "filter", "filters", "CompositeFilter", "__PRIVATE_canonifyFilter", "FieldFilter", "field", "canonicalString", "op", "toString", "canonicalId", "value", "map", "join", "__PRIVATE_canonicalIdsString", "__PRIVATE_filterEquals", "__PRIVATE_f1", "__PRIVATE_f2", "isEqual", "__PRIVATE_valueEquals", "__PRIVATE_fieldFilterEquals", "length", "reduce", "result", "__PRIVATE_f1Filter", "index", "fail", "__PRIVATE_stringifyFilter", "filter", "FieldFilter", "field", "canonicalString", "op", "canonicalId", "value", "CompositeFilter", "toString", "getFilters", "map", "join", "__PRIVATE_stringifyCompositeFilter", "__PRIVATE_KeyFieldFilter", "constructor", "super", "this", "key", "DocumentKey", "fromName", "referenceValue", "matches", "doc", "comparison", "comparator", "matchesComparison", "__PRIVATE_KeyFieldInFilter", "keys", "__PRIVATE_extractDocumentKeysFromArrayValue", "some", "isEqual", "__PRIVATE_KeyFieldNotInFilter", "_a", "arrayValue", "values", "v", "__PRIVATE_ArrayContainsFilter", "other", "data", "isArray", "__PRIVATE_arrayValueContains", "__PRIVATE_InFilter", "__PRIVATE_NotInFilter", "nullValue", "__PRIVATE_ArrayContainsAnyFilter", "val", "__PRIVATE_TargetImpl", "path", "collectionGroup", "orderBy", "filters", "limit", "startAt", "endAt", "__PRIVATE_memoizedCanonicalId", "__PRIVATE_newTarget", "__PRIVATE_canonifyTarget", "target", "__PRIVATE_targetImpl", "__PRIVATE_debugCast", "str", "f", "__PRIVATE_canonifyFilter", "o", "dir", "__PRIVATE_isNullOrUndefined", "inclusive", "position", "p", "__PRIVATE_targetEquals", "left", "right", "length", "__PRIVATE_i", "__PRIVATE_orderByEquals", "__PRIVATE_filterEquals", "__PRIVATE_boundEquals", "__PRIVATE_targetIsDocumentTarget", "isDocumentKey", "__PRIVATE_QueryImpl", "constructor", "path", "collectionGroup", "explicitOrderBy", "filters", "limit", "limitType", "startAt", "endAt", "this", "__PRIVATE_memoizedNormalizedOrderBy", "__PRIVATE_memoizedTarget", "__PRIVATE_memoizedAggregateTarget", "__PRIVATE_newQuery", "__PRIVATE_newQueryForPath", "__PRIVATE_queryMatchesAllDocuments", "query", "length", "field", "isKeyField", "__PRIVATE_isCollectionGroupQuery", "__PRIVATE_queryNormalizedOrderBy", "__PRIVATE_queryImpl", "__PRIVATE_debugCast", "__PRIVATE_fieldsNormalized", "Set", "orderBy", "push", "add", "canonicalString", "__PRIVATE_lastDirection", "dir", "__PRIVATE_inequalityFields", "result", "SortedSet", "FieldPath", "comparator", "forEach", "filter", "getFlattenedFilters", "isInequality", "has", "OrderBy", "keyField", "__PRIVATE_queryToTarget", "__PRIVATE__queryToTarget", "__PRIVATE__queryToTarget", "__PRIVATE_queryImpl", "__PRIVATE_orderBys", "limitType", "__PRIVATE_newTarget", "path", "collectionGroup", "filters", "limit", "startAt", "endAt", "map", "orderBy", "dir", "OrderBy", "field", "Bound", "position", "inclusive", "__PRIVATE_queryWithLimit", "query", "limit", "limitType", "__PRIVATE_QueryImpl", "path", "collectionGroup", "explicitOrderBy", "slice", "filters", "startAt", "endAt", "__PRIVATE_queryEquals", "left", "right", "__PRIVATE_targetEquals", "__PRIVATE_queryToTarget", "__PRIVATE_canonifyQuery", "__PRIVATE_canonifyTarget", "__PRIVATE_stringifyQuery", "target", "str", "canonicalString", "length", "map", "f", "__PRIVATE_stringifyFilter", "join", "__PRIVATE_isNullOrUndefined", "orderBy", "o", "field", "dir", "inclusive", "position", "p", "canonicalId", "__PRIVATE_queryMatches", "doc", "isFoundDocument", "__PRIVATE_docPath", "key", "hasCollectionId", "isPrefixOf", "DocumentKey", "isDocumentKey", "isEqual", "isImmediateParentOf", "__PRIVATE_queryNormalizedOrderBy", "isKeyField", "data", "__PRIVATE_queryMatchesOrderBy", "filter", "matches", "__PRIVATE_boundSortsBeforeDocument", "bound", "comparison", "__PRIVATE_boundCompareToDocument", "__PRIVATE_boundSortsAfterDocument", "__PRIVATE_queryCollectionGroup", "lastSegment", "get", "__PRIVATE_newQueryComparator", "__PRIVATE_d1", "__PRIVATE_d2", "__PRIVATE_comparedOnKeyField", "comp", "__PRIVATE_compareDocs", "comparator", "v1", "v2", "__PRIVATE_valueCompare", "fail", "ObjectMap", "constructor", "mapKeyFn", "equalsFn", "this", "inner", "innerSize", "id", "__PRIVATE_otherKey", "value", "has", "undefined", "set", "__PRIVATE_i", "push", "delete", "splice", "forEach", "fn", "_", "entries", "k", "v", "isEmpty", "size", "__PRIVATE_EMPTY_MUTABLE_DOCUMENT_MAP", "SortedMap", "__PRIVATE_mutableDocumentMap", "__PRIVATE_EMPTY_DOCUMENT_MAP", "documentMap", "docs", "insert", "__PRIVATE_convertOverlayedDocumentMapToDocumentMap", "collection", "documents", "overlayedDocument", "__PRIVATE_newOverlayMap", "__PRIVATE_newDocumentKeyMap", "__PRIVATE_newMutationMap", "toString", "l", "r", "__PRIVATE_EMPTY_DOCUMENT_VERSION_MAP", "__PRIVATE_EMPTY_DOCUMENT_KEY_SET", "SortedSet", "__PRIVATE_documentKeySet", "keys", "add", "__PRIVATE_EMPTY_TARGET_ID_SET", "__PRIVATE_primitiveComparator", "__PRIVATE_targetIdSet", "__PRIVATE_toDouble", "serializer", "useProto3Json", "isNaN", "doubleValue", "Infinity", "__PRIVATE_isNegativeZero", "__PRIVATE_toInteger", "integerValue", "toNumber", "isSafeInteger", "TransformOperation", "__PRIVATE_applyTransformOperationToLocalView", "transform", "previousValue", "localWriteTime", "__PRIVATE_ServerTimestampTransform", "mapValue", "fields", "__type__", "stringValue", "__local_write_time__", "timestampValue", "seconds", "nanos", "nanoseconds", "__PRIVATE_isServerTimestamp", "__PRIVATE_getPreviousValue", "serverTimestamp", "__PRIVATE_ArrayUnionTransformOperation", "__PRIVATE_applyArrayUnionTransformOperation", "__PRIVATE_ArrayRemoveTransformOperation", "__PRIVATE_applyArrayRemoveTransformOperation", "__PRIVATE_baseValue", "__PRIVATE_computeTransformOperationBaseValue", "sum", "asNumber", "__PRIVATE_operand", "isInteger", "__PRIVATE_applyNumericIncrementTransformOperationToLocalView", "__PRIVATE_applyTransformOperationToRemoteDocument", "__PRIVATE_transformResult", "__PRIVATE_NumericIncrementTransformOperation", "__PRIVATE_isNumber", "elements", "super", "values", "__PRIVATE_coercedFieldValuesArray", "__PRIVATE_toUnion", "some", "element", "__PRIVATE_valueEquals", "arrayValue", "__PRIVATE_toRemove", "__PRIVATE_normalizeNumber", "isArray", "__PRIVATE_fieldTransformEquals", "left", "right", "field", "isEqual", "__PRIVATE_ArrayUnionTransformOperation", "__PRIVATE_ArrayRemoveTransformOperation", "__PRIVATE_arrayEquals", "elements", "__PRIVATE_valueEquals", "__PRIVATE_NumericIncrementTransformOperation", "__PRIVATE_operand", "__PRIVATE_ServerTimestampTransform", "transform", "MutationResult", "constructor", "version", "transformResults", "this", "Precondition", "updateTime", "exists", "static", "isNone", "undefined", "other", "__PRIVATE_preconditionIsValidForDocument", "precondition", "document", "isFoundDocument", "Mutation", "__PRIVATE_calculateOverlayMutation", "doc", "mask", "hasLocalMutations", "fields", "length", "isNoDocument", "__PRIVATE_DeleteMutation", "key", "none", "__PRIVATE_SetMutation", "data", "__PRIVATE_docValue", "__PRIVATE_patchValue", "ObjectValue", "empty", "__PRIVATE_maskSet", "SortedSet", "FieldPath", "comparator", "path", "has", "value", "popLast", "delete", "set", "add", "__PRIVATE_PatchMutation", "FieldMask", "toArray", "__PRIVATE_mutationApplyToRemoteDocument", "mutation", "__PRIVATE_mutationResult", "__PRIVATE_newData", "clone", "__PRIVATE_serverTransformResults", "fieldTransforms", "setAll", "convertToFoundDocument", "setHasCommittedMutations", "convertToUnknownDocument", "__PRIVATE_getPatch", "__PRIVATE_patchMutationApplyToRemoteDocument", "convertToNoDocument", "__PRIVATE_deleteMutationApplyToRemoteDocument", "__PRIVATE_mutationApplyToLocalView", "__PRIVATE_previousMask", "localWriteTime", "__PRIVATE_localTransformResults", "setHasLocalMutations", "unionWith", "fieldMask", "map", "__PRIVATE_mutationExtractBaseValue", "__PRIVATE_baseObject", "__PRIVATE_fieldTransform", "__PRIVATE_existingValue", "__PRIVATE_coercedValue", "__PRIVATE_computeTransformOperationBaseValue", "__PRIVATE_mutationEquals", "type", "l", "r", "super", "getFieldMask", "result", "Map", "forEach", "fieldPath", "isEmpty", "newValue", "__PRIVATE_mutableDocument", "__PRIVATE_hardAssert", "__PRIVATE_i", "previousValue", "__PRIVATE_applyTransformOperationToRemoteDocument", "__PRIVATE_applyTransformOperationToLocalView", "__PRIVATE_VerifyMutation", "MutationBatch", "batchId", "baseMutations", "mutations", "applyToRemoteDocument", "batchResult", "mutationResults", "applyToLocalView", "mutatedFields", "applyToLocalDocumentSet", "documentMap", "documentsWithoutRemoteVersion", "overlays", "__PRIVATE_newMutationMap", "m", "overlayedDocument", "get", "__PRIVATE_overlay", "isValidDocument", "SnapshotVersion", "min", "keys", "reduce", "__PRIVATE_documentKeySet", "MutationBatchResult", "batch", "commitVersion", "docVersions", "results", "__PRIVATE_versionMap", "__PRIVATE_documentVersionMap", "__PRIVATE_EMPTY_DOCUMENT_VERSION_MAP", "insert", "Overlay", "largestBatchId", "getKey", "toString", "ExistenceFilter", "constructor", "count", "unchangedNames", "this", "__PRIVATE_RpcCode", "RpcCode", "__PRIVATE_isPermanentError", "code", "fail", "Code", "CANCELLED", "UNKNOWN", "DEADLINE_EXCEEDED", "RESOURCE_EXHAUSTED", "INTERNAL", "UNAVAILABLE", "UNAUTHENTICATED", "INVALID_ARGUMENT", "NOT_FOUND", "ALREADY_EXISTS", "PERMISSION_DENIED", "FAILED_PRECONDITION", "ABORTED", "OUT_OF_RANGE", "UNIMPLEMENTED", "DATA_LOSS", "__PRIVATE_mapCodeFromRpcCode", "__PRIVATE_logError", "OK", "__PRIVATE_testingHooksSpi", "__PRIVATE_newTextEncoder", "TextEncoder", "__PRIVATE_MAX_64_BIT_UNSIGNED_INTEGER", "Integer", "__PRIVATE_getMd5HashValue", "value", "__PRIVATE_encodedValue", "encode", "__PRIVATE_md5", "Md5", "update", "Uint8Array", "digest", "__PRIVATE_get64BitUints", "Bytes", "__PRIVATE_dataView", "DataView", "buffer", "__PRIVATE_chunk1", "getUint32", "__PRIVATE_chunk2", "__PRIVATE_chunk3", "__PRIVATE_chunk4", "BloomFilter", "bitmap", "padding", "hashCount", "__PRIVATE_BloomFilterError", "length", "__PRIVATE_bitCount", "__PRIVATE_bitCountInInteger", "fromNumber", "__PRIVATE_getBitIndex", "__PRIVATE_num1", "__PRIVATE_num2", "__PRIVATE_hashIndex", "__PRIVATE_hashValue", "add", "multiply", "compare", "getBits", "modulo", "toNumber", "__PRIVATE_isBitSet", "index", "Math", "floor", "mightContain", "__PRIVATE_md5HashedValue", "__PRIVATE_hash1", "__PRIVATE_hash2", "__PRIVATE_i", "static", "contains", "ceil", "bloomFilter", "forEach", "item", "insert", "__PRIVATE_setBit", "__PRIVATE_indexOfByte", "offset", "Error", "name", "RemoteEvent", "snapshotVersion", "targetChanges", "targetMismatches", "documentUpdates", "resolvedLimboDocuments", "targetId", "current", "resumeToken", "Map", "set", "TargetChange", "createSynthesizedTargetChangeForCurrentChange", "SnapshotVersion", "min", "SortedMap", "__PRIVATE_primitiveComparator", "__PRIVATE_mutableDocumentMap", "__PRIVATE_documentKeySet", "addedDocuments", "modifiedDocuments", "removedDocuments", "__PRIVATE_DocumentWatchChange", "__PRIVATE_updatedTargetIds", "removedTargetIds", "key", "__PRIVATE_newDoc", "__PRIVATE_ExistenceFilterChange", "__PRIVATE_existenceFilter", "__PRIVATE_WatchTargetChange", "state", "targetIds", "ByteString", "EMPTY_BYTE_STRING", "cause", "__PRIVATE_TargetState", "__PRIVATE_pendingResponses", "__PRIVATE_documentChanges", "__PRIVATE_snapshotChangesMap", "__PRIVATE__resumeToken", "__PRIVATE__current", "__PRIVATE__hasPendingChanges", "__PRIVATE_isPending", "__PRIVATE_hasPendingChanges", "__PRIVATE_updateResumeToken", "approximateByteSize", "__PRIVATE_toTargetChange", "changeType", "__PRIVATE_clearPendingChanges", "__PRIVATE_addDocumentChange", "__PRIVATE_removeDocumentChange", "remove", "__PRIVATE_recordPendingTargetRequest", "__PRIVATE_recordTargetResponse", "__PRIVATE_hardAssert", "__PRIVATE_markCurrent", "__PRIVATE_WatchChangeAggregator", "__PRIVATE_metadataProvider", "__PRIVATE_targetStates", "__PRIVATE_pendingDocumentUpdates", "__PRIVATE_pendingDocumentTargetMapping", "__PRIVATE_documentTargetMap", "__PRIVATE_pendingTargetResets", "__PRIVATE_handleDocumentChange", "__PRIVATE_docChange", "isFoundDocument", "__PRIVATE_addDocumentToTarget", "__PRIVATE_removeDocumentFromTarget", "__PRIVATE_handleTargetChange", "targetChange", "forEachTarget", "__PRIVATE_targetState", "__PRIVATE_ensureTargetState", "__PRIVATE_isActiveTarget", "removeTarget", "__PRIVATE_resetTarget", "fn", "_", "__PRIVATE_handleExistenceFilter", "__PRIVATE_watchChange", "expectedCount", "targetData", "__PRIVATE_targetDataForActiveTarget", "target", "__PRIVATE_targetIsDocumentTarget", "DocumentKey", "path", "MutableDocument", "newNoDocument", "__PRIVATE_currentSize", "__PRIVATE_getCurrentDocumentCountForTarget", "__PRIVATE_parseBloomFilter", "status", "__PRIVATE_applyBloomFilter", "purpose", "__PRIVATE_notifyOnExistenceFilterMismatch", "localCacheCount", "databaseId", "__PRIVATE_bloomFilterStatus", "result", "existenceFilterCount", "database", "projectId", "applied", "_a", "bitmapLength", "_d", "_c", "_b", "bits", "a", "_f", "_e", "c", "t", "__PRIVATE_getDatabaseId", "__PRIVATE_normalizedBitmap", "__PRIVATE_normalizeByteString", "toUint8Array", "err", "__PRIVATE_Base64DecodeError", "__PRIVATE_logWarn", "message", "__PRIVATE_currentCount", "__PRIVATE_filterRemovedDocuments", "__PRIVATE_existingKeys", "getRemoteKeysForTarget", "__PRIVATE_removalCount", "documentPath", "canonicalString", "__PRIVATE_createRemoteEvent", "get", "__PRIVATE_targetContainsDocument", "__PRIVATE_targets", "__PRIVATE_isOnlyLimboTarget", "forEachWhile", "doc", "setReadTime", "remoteEvent", "document", "__PRIVATE_ensureDocumentTargetMapping", "__PRIVATE_updatedDocument", "delete", "size", "__PRIVATE_targetMapping", "SortedSet", "__PRIVATE_targetActive", "__PRIVATE_logDebug", "__PRIVATE_getTargetDataForTarget", "has", "comparator", "__PRIVATE_DIRECTIONS", "__PRIVATE_dirs", "__PRIVATE_OPERATORS", "__PRIVATE_ops", "__PRIVATE_COMPOSITE_OPERATORS", "JsonProtoSerializer", "useProto3Json", "__PRIVATE_toInt32Proto", "serializer", "val", "__PRIVATE_isNullOrUndefined", "toTimestamp", "timestamp", "Date", "seconds", "toISOString", "replace", "nanoseconds", "slice", "nanos", "__PRIVATE_toBytes", "bytes", "toBase64", "__PRIVATE_toVersion", "version", "__PRIVATE_fromVersion", "fromTimestamp", "date", "__PRIVATE_normalizeTimestamp", "Timestamp", "__PRIVATE_toResourceName", "__PRIVATE_toResourcePath", "__PRIVATE_resourcePath", "ResourcePath", "__PRIVATE_fullyQualifiedPrefixPath", "child", "__PRIVATE_fromResourceName", "__PRIVATE_resource", "fromString", "__PRIVATE_isValidResourceName", "__PRIVATE_toName", "fromName", "FirestoreError", "__PRIVATE_extractLocalPathFromResourceName", "__PRIVATE_toQueryPath", "__PRIVATE_fromQueryPath", "__PRIVATE_resourceName", "emptyPath", "__PRIVATE_getEncodedDatabaseId", "popFirst", "__PRIVATE_toMutationDocument", "fields", "mapValue", "__PRIVATE_fromWatchChange", "serializer", "__PRIVATE_change", "__PRIVATE_watchChange", "targetChange", "state", "fail", "__PRIVATE_fromWatchTargetChangeState", "targetChangeType", "targetIds", "resumeToken", "value", "useProto3Json", "__PRIVATE_hardAssert", "undefined", "ByteString", "fromBase64String", "Buffer", "Uint8Array", "fromUint8Array", "__PRIVATE_causeProto", "cause", "status", "code", "Code", "UNKNOWN", "__PRIVATE_mapCodeFromRpcCode", "FirestoreError", "message", "__PRIVATE_WatchTargetChange", "documentChange", "__PRIVATE_entityChange", "document", "name", "updateTime", "key", "fromName", "version", "__PRIVATE_fromVersion", "createTime", "SnapshotVersion", "min", "data", "ObjectValue", "mapValue", "fields", "doc", "MutableDocument", "newFoundDocument", "__PRIVATE_updatedTargetIds", "removedTargetIds", "__PRIVATE_DocumentWatchChange", "documentDelete", "__PRIVATE_docDelete", "readTime", "newNoDocument", "documentRemove", "__PRIVATE_docRemove", "filter", "targetId", "count", "unchangedNames", "__PRIVATE_existenceFilter", "ExistenceFilter", "__PRIVATE_ExistenceFilterChange", "toMutation", "mutation", "result", "__PRIVATE_SetMutation", "update", "__PRIVATE_toMutationDocument", "__PRIVATE_DeleteMutation", "delete", "__PRIVATE_toName", "__PRIVATE_PatchMutation", "updateMask", "__PRIVATE_toDocumentMask", "fieldMask", "__PRIVATE_VerifyMutation", "verify", "fieldTransforms", "length", "updateTransforms", "map", "transform", "__PRIVATE_fieldTransform", "__PRIVATE_ServerTimestampTransform", "fieldPath", "field", "canonicalString", "setToServerValue", "__PRIVATE_ArrayUnionTransformOperation", "appendMissingElements", "values", "elements", "__PRIVATE_ArrayRemoveTransformOperation", "removeAllFromArray", "__PRIVATE_NumericIncrementTransformOperation", "increment", "__PRIVATE_operand", "precondition", "isNone", "currentDocument", "__PRIVATE_toVersion", "exists", "__PRIVATE_fromWriteResults", "__PRIVATE_protos", "commitTime", "length", "__PRIVATE_hardAssert", "undefined", "map", "proto", "version", "updateTime", "__PRIVATE_fromVersion", "isEqual", "SnapshotVersion", "min", "MutationResult", "transformResults", "__PRIVATE_fromWriteResult", "__PRIVATE_toDocumentsTarget", "serializer", "target", "documents", "__PRIVATE_toQueryPath", "path", "__PRIVATE_toQueryTarget", "__PRIVATE_queryTarget", "structuredQuery", "parent", "collectionGroup", "from", "collectionId", "allDescendants", "popLast", "lastSegment", "where", "filters", "__PRIVATE_toFilter", "CompositeFilter", "create", "__PRIVATE_toFilters", "orderBy", "__PRIVATE_orderBys", "order", "field", "__PRIVATE_toFieldPathReference", "direction", "__PRIVATE_toDirection", "dir", "__PRIVATE_toOrder", "limit", "__PRIVATE_toInt32Proto", "startAt", "cursor", "before", "inclusive", "values", "position", "endAt", "__PRIVATE_toEndAtCursor", "__PRIVATE_convertQueryTargetToQuery", "target", "path", "__PRIVATE_fromQueryPath", "parent", "query", "structuredQuery", "__PRIVATE_fromCount", "from", "length", "collectionGroup", "__PRIVATE_hardAssert", "allDescendants", "collectionId", "child", "__PRIVATE_filterBy", "where", "filter", "result", "__PRIVATE_fromFilter", "CompositeFilter", "__PRIVATE_compositeFilterIsFlatConjunction", "getFilters", "__PRIVATE_fromFilters", "orderBy", "__PRIVATE_orderBys", "map", "order", "OrderBy", "__PRIVATE_fromFieldPathReference", "field", "dir", "direction", "__PRIVATE_fromOrder", "limit", "val", "value", "__PRIVATE_isNullOrUndefined", "__PRIVATE_fromInt32Proto", "startAt", "cursor", "inclusive", "before", "position", "values", "Bound", "__PRIVATE_fromStartAtCursor", "endAt", "__PRIVATE_newQuery", "__PRIVATE_toListenRequestLabels", "serializer", "targetData", "purpose", "fail", "__PRIVATE_toLabel", "unaryFilter", "op", "__PRIVATE_nanField", "FieldFilter", "create", "doubleValue", "NaN", "__PRIVATE_nullField", "nullValue", "__PRIVATE_notNanField", "__PRIVATE_notNullField", "__PRIVATE_fromUnaryFilter", "undefined", "fieldFilter", "__PRIVATE_fromOperatorName", "__PRIVATE_fromFieldFilter", "compositeFilter", "filters", "__PRIVATE_fromCompositeOperatorName", "__PRIVATE_fromCompositeFilter", "__PRIVATE_toDirection", "__PRIVATE_DIRECTIONS", "__PRIVATE_toOperatorName", "__PRIVATE_OPERATORS", "__PRIVATE_toCompositeOperatorName", "__PRIVATE_COMPOSITE_OPERATORS", "__PRIVATE_toFieldPathReference", "fieldPath", "canonicalString", "__PRIVATE_fieldReference", "FieldPath", "fromServerFormat", "__PRIVATE_toFilter", "__PRIVATE_isNanValue", "__PRIVATE_isNullValue", "__PRIVATE_toUnaryOrFieldFilter", "__PRIVATE_protos", "__PRIVATE_toCompositeFilter", "__PRIVATE_toDocumentMask", "fieldMask", "__PRIVATE_canonicalFields", "fields", "forEach", "push", "fieldPaths", "__PRIVATE_isValidResourceName", "get", "TargetData", "constructor", "targetId", "sequenceNumber", "snapshotVersion", "SnapshotVersion", "min", "lastLimboFreeSnapshotVersion", "resumeToken", "ByteString", "EMPTY_BYTE_STRING", "expectedCount", "this", "withSequenceNumber", "withResumeToken", "withExpectedCount", "withLastLimboFreeSnapshotVersion", "__PRIVATE_LocalSerializer", "__PRIVATE_remoteSerializer", "__PRIVATE_fromBundledQuery", "bundledQuery", "query", "__PRIVATE_convertQueryTargetToQuery", "parent", "structuredQuery", "limitType", "__PRIVATE_queryWithLimit", "limit", "__PRIVATE_FirestoreIndexValueWriter", "constructor", "__PRIVATE_writeIndexValue", "value", "__PRIVATE_encoder", "this", "__PRIVATE_writeIndexValueAux", "__PRIVATE_writeInfinity", "__PRIVATE_indexValue", "__PRIVATE_writeValueTypeLabel", "__PRIVATE_writeNumber", "booleanValue", "__PRIVATE_normalizeNumber", "integerValue", "n", "doubleValue", "isNaN", "__PRIVATE_isNegativeZero", "timestamp", "timestampValue", "__PRIVATE_normalizeTimestamp", "__PRIVATE_writeString", "seconds", "nanos", "__PRIVATE_writeIndexString", "stringValue", "__PRIVATE_writeTruncationMarker", "__PRIVATE_writeBytes", "__PRIVATE_normalizeByteString", "bytesValue", "__PRIVATE_writeIndexEntityRef", "referenceValue", "__PRIVATE_geoPoint", "geoPointValue", "latitude", "longitude", "__PRIVATE_isMaxValue", "Number", "MAX_SAFE_INTEGER", "__PRIVATE_writeIndexMap", "mapValue", "__PRIVATE_writeIndexArray", "arrayValue", "fail", "__PRIVATE_stringIndexValue", "__PRIVATE_writeUnlabeledIndexString", "__PRIVATE_mapIndexValue", "map", "fields", "key", "Object", "keys", "__PRIVATE_arrayIndexValue", "values", "element", "DocumentKey", "fromName", "path", "forEach", "segment", "__PRIVATE_typeOrder", "__PRIVATE_INSTANCE", "__PRIVATE_MemoryIndexManager", "constructor", "this", "__PRIVATE_collectionParentIndex", "__PRIVATE_MemoryCollectionParentIndex", "addToCollectionParentIndex", "transaction", "collectionPath", "add", "PersistencePromise", "resolve", "getCollectionParents", "collectionId", "getEntries", "addFieldIndex", "index", "deleteFieldIndex", "deleteAllFieldIndexes", "createTargetIndexes", "target", "getDocumentsMatchingTarget", "getIndexType", "getFieldIndexes", "collectionGroup", "getNextCollectionGroupToUpdate", "getMinOffset", "IndexOffset", "min", "getMinOffsetFromCollectionGroup", "updateCollectionGroup", "offset", "updateIndexEntries", "documents", "lastSegment", "parentPath", "popLast", "__PRIVATE_existingParents", "SortedSet", "ResourcePath", "comparator", "__PRIVATE_added", "has", "toArray", "__PRIVATE_EMPTY_VALUE", "Uint8Array", "LruParams", "constructor", "cacheSizeCollectionThreshold", "percentileToCollect", "maximumSequenceNumbersToCollect", "this", "static", "cacheSize", "DEFAULT_COLLECTION_PERCENTILE", "DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT", "LruParams", "DEFAULT_COLLECTION_PERCENTILE", "DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT", "DEFAULT", "DISABLED", "__PRIVATE_TargetIdGenerator", "constructor", "__PRIVATE_lastId", "this", "next", "static", "RemoteDocumentChangeBuffer", "constructor", "this", "changes", "ObjectMap", "key", "toString", "l", "r", "isEqual", "changesApplied", "addEntry", "document", "assertNotApplied", "set", "removeEntry", "readTime", "MutableDocument", "newInvalidDocument", "setReadTime", "getEntry", "transaction", "documentKey", "__PRIVATE_bufferedEntry", "get", "PersistencePromise", "resolve", "getFromCache", "getEntries", "documentKeys", "getAllFromCache", "apply", "applyChanges", "OverlayedDocument", "constructor", "overlayedDocument", "mutatedFields", "this", "LocalDocumentsView", "remoteDocumentCache", "mutationQueue", "documentOverlayCache", "indexManager", "getDocument", "transaction", "key", "__PRIVATE_overlay", "getOverlay", "next", "value", "getEntry", "document", "__PRIVATE_mutationApplyToLocalView", "mutation", "FieldMask", "empty", "Timestamp", "now", "getDocuments", "keys", "getEntries", "docs", "getLocalViewOfDocuments", "__PRIVATE_documentKeySet", "existenceStateChanged", "overlays", "__PRIVATE_newOverlayMap", "populateOverlays", "computeViews", "__PRIVATE_computeViewsResult", "result", "documentMap", "forEach", "documentKey", "insert", "getOverlayedDocuments", "__PRIVATE_missingOverlays", "has", "push", "getOverlays", "val", "set", "__PRIVATE_recalculateDocuments", "__PRIVATE_mutableDocumentMap", "__PRIVATE_newDocumentKeyMap", "results", "__PRIVATE_newOverlayedDocumentMap", "_", "doc", "get", "undefined", "__PRIVATE_PatchMutation", "getFieldMask", "recalculateAndSaveOverlays", "__PRIVATE_recalculatedFields", "mask", "_a", "__PRIVATE_masks", "__PRIVATE_documentsByBatchId", "SortedMap", "key1", "key2", "__PRIVATE_processed", "getAllMutationBatchesAffectingDocumentKeys", "__PRIVATE_batches", "batch", "__PRIVATE_baseDoc", "applyToLocalView", "__PRIVATE_newSet", "batchId", "add", "__PRIVATE_promises", "iter", "getReverseIterator", "hasNext", "entry", "getNext", "__PRIVATE_newMutationMap", "overlayMutation", "__PRIVATE_calculateOverlayMutation", "saveOverlays", "PersistencePromise", "waitFor", "recalculateAndSaveOverlaysForDocumentKeys", "documentKeys", "getDocumentsMatchingQuery", "query", "offset", "context", "DocumentKey", "isDocumentKey", "path", "collectionGroup", "filters", "length", "__PRIVATE_isDocumentQuery", "getDocumentsMatchingDocumentQuery", "__PRIVATE_isCollectionGroupQuery", "getDocumentsMatchingCollectionGroupQuery", "getDocumentsMatchingCollectionQuery", "getNextDocuments", "count", "getAllFromCollectionGroup", "__PRIVATE_originalDocs", "__PRIVATE_overlaysPromise", "size", "getOverlaysForCollectionGroup", "largestBatchId", "resolve", "__PRIVATE_modifiedDocs", "__PRIVATE_localDocs", "changes", "__PRIVATE_convertOverlayedDocumentMapToDocumentMap", "__PRIVATE_docPath", "isFoundDocument", "collectionId", "getCollectionParents", "__PRIVATE_parents", "parent", "__PRIVATE_collectionQuery", "__PRIVATE_QueryImpl", "explicitOrderBy", "slice", "limit", "limitType", "startAt", "endAt", "child", "r", "getOverlaysForCollection", "__PRIVATE_remoteDocuments", "getKey", "MutableDocument", "newInvalidDocument", "__PRIVATE_queryMatches", "__PRIVATE_MemoryBundleCache", "serializer", "__PRIVATE_bundles", "Map", "__PRIVATE_namedQueries", "getBundleMetadata", "bundleId", "saveBundleMetadata", "__PRIVATE_bundleMetadata", "id", "metadata", "version", "createTime", "__PRIVATE_fromVersion", "__PRIVATE_fromBundleMetadata", "getNamedQuery", "queryName", "saveNamedQuery", "name", "namedQuery", "__PRIVATE_fromBundledQuery", "bundledQuery", "readTime", "__PRIVATE_fromProtoNamedQuery", "__PRIVATE_MemoryDocumentOverlayCache", "comparator", "__PRIVATE_overlayByBatchId", "__PRIVATE_saveOverlay", "removeOverlaysForBatchId", "remove", "delete", "collection", "sinceBatchId", "__PRIVATE_immediateChildrenPathLength", "prefix", "getIteratorFrom", "isPrefixOf", "__PRIVATE_batchIdToOverlays", "getIterator", "getCollectionGroup", "__PRIVATE_overlaysForBatchId", "__PRIVATE_batchIter", "__PRIVATE_existing", "Overlay", "__PRIVATE_ReferenceSet", "__PRIVATE_refsByKey", "SortedSet", "__PRIVATE_DocReference", "__PRIVATE_compareByKey", "__PRIVATE_refsByTarget", "__PRIVATE_compareByTargetId", "isEmpty", "addReference", "ref", "__PRIVATE_addReferences", "removeReference", "__PRIVATE_removeRef", "__PRIVATE_removeReferences", "__PRIVATE_removeReferencesForId", "__PRIVATE_emptyKey", "ResourcePath", "__PRIVATE_startRef", "__PRIVATE_endRef", "forEachInRange", "__PRIVATE_removeAllReferences", "__PRIVATE_referencesForId", "containsKey", "__PRIVATE_firstRef", "firstAfterOrEqual", "isEqual", "__PRIVATE_targetOrBatchId", "static", "left", "right", "__PRIVATE_primitiveComparator", "__PRIVATE_MemoryMutationQueue", "referenceDelegate", "__PRIVATE_nextBatchId", "__PRIVATE_batchesByDocumentKey", "checkEmpty", "addMutationBatch", "localWriteTime", "baseMutations", "mutations", "MutationBatch", "addToCollectionParentIndex", "popLast", "lookupMutationBatch", "__PRIVATE_findMutationBatch", "getNextMutationBatchAfterBatchId", "__PRIVATE_rawIndex", "__PRIVATE_indexOfBatchId", "index", "getHighestUnacknowledgedBatchId", "getAllMutationBatches", "getAllMutationBatchesAffectingDocumentKey", "start", "end", "Number", "POSITIVE_INFINITY", "__PRIVATE_uniqueBatchIDs", "__PRIVATE_findMutationBatches", "getAllMutationBatchesAffectingQuery", "__PRIVATE_startPath", "forEachWhile", "__PRIVATE_rowKeyPath", "__PRIVATE_batchIDs", "removeMutationBatch", "__PRIVATE_hardAssert", "__PRIVATE_indexOfExistingBatchId", "shift", "__PRIVATE_references", "markPotentiallyOrphaned", "__PRIVATE_removeCachedMutationKeys", "txn", "performConsistencyCheck", "action", "__PRIVATE_MemoryRemoteDocumentCacheImpl", "__PRIVATE_sizer", "__PRIVATE_documentEntryMap", "setIndexManager", "addEntry", "__PRIVATE_previousSize", "__PRIVATE_currentSize", "mutableCopy", "removeEntry", "mutatedDocs", "collectionPath", "iterator", "__PRIVATE_indexOffsetComparator", "__PRIVATE_newIndexOffsetFromDocument", "__PRIVATE_limti", "fail", "__PRIVATE_forEachDocumentKey", "f", "newChangeBuffer", "options", "__PRIVATE_MemoryRemoteDocumentChangeBuffer", "getSize", "RemoteDocumentChangeBuffer", "__PRIVATE_documentCache", "super", "applyChanges", "isValidDocument", "getFromCache", "getAllFromCache", "__PRIVATE_MemoryTargetCache", "persistence", "__PRIVATE_targets", "ObjectMap", "t", "__PRIVATE_canonifyTarget", "__PRIVATE_targetEquals", "lastRemoteSnapshotVersion", "SnapshotVersion", "min", "highestTargetId", "__PRIVATE_highestSequenceNumber", "targetCount", "__PRIVATE_targetIdGenerator", "__PRIVATE_TargetIdGenerator", "__PRIVATE_forTargetCache", "forEachTarget", "targetData", "getLastRemoteSnapshotVersion", "getHighestSequenceNumber", "allocateTargetId", "setTargetsMetadata", "highestListenSequenceNumber", "__PRIVATE_saveTargetData", "target", "targetId", "sequenceNumber", "addTargetData", "updateTargetData", "removeTargetData", "removeTargets", "upperBound", "activeTargetIds", "__PRIVATE_removals", "removeMatchingKeysForTargetId", "getTargetCount", "getTargetData", "addMatchingKeys", "removeMatchingKeys", "getMatchingKeysForTargetId", "__PRIVATE_matchingKeys", "__PRIVATE_MemoryPersistence", "__PRIVATE_referenceDelegateFactory", "__PRIVATE_mutationQueues", "__PRIVATE_listenSequence", "__PRIVATE_ListenSequence", "__PRIVATE__started", "__PRIVATE_targetCache", "__PRIVATE_MemoryIndexManager", "__PRIVATE_documentSize", "__PRIVATE_LocalSerializer", "__PRIVATE_bundleCache", "Promise", "shutdown", "started", "setDatabaseDeletedListener", "setNetworkEnabled", "getIndexManager", "user", "getDocumentOverlayCache", "toKey", "getMutationQueue", "__PRIVATE_queue", "getTargetCache", "getRemoteDocumentCache", "getBundleCache", "runTransaction", "mode", "transactionOperation", "__PRIVATE_logDebug", "__PRIVATE_MemoryTransaction", "__PRIVATE_onTransactionStarted", "__PRIVATE_onTransactionCommitted", "toPromise", "then", "raiseOnCommittedEvent", "__PRIVATE_mutationQueuesContainKey", "or", "Object", "values", "map", "PersistenceTransaction", "currentSequenceNumber", "__PRIVATE_MemoryEagerDelegate", "__PRIVATE_localViewReferences", "__PRIVATE__orphanedDocuments", "__PRIVATE_orphanedDocuments", "toString", "removeTarget", "cache", "Set", "__PRIVATE_changeBuffer", "fromPath", "__PRIVATE_isReferenced", "apply", "updateLimboDocument", "__PRIVATE_LocalViewChanges", "constructor", "targetId", "fromCache", "__PRIVATE_addedKeys", "__PRIVATE_removedKeys", "this", "static", "__PRIVATE_viewSnapshot", "__PRIVATE_documentKeySet", "__PRIVATE_docChange", "docChanges", "type", "add", "doc", "key", "QueryContext", "_documentReadCount", "documentReadCount", "incrementDocumentReadCount", "amount", "__PRIVATE_QueryEngine", "__PRIVATE_initialized", "__PRIVATE_indexAutoCreationEnabled", "__PRIVATE_indexAutoCreationMinCollectionSize", "__PRIVATE_relativeIndexReadCostPerDocument", "__PRIVATE_getDefaultRelativeIndexReadCostPerDocument", "isSafari", "__PRIVATE_getAndroidVersion", "getUA", "initialize", "localDocuments", "indexManager", "__PRIVATE_localDocumentsView", "getDocumentsMatchingQuery", "transaction", "query", "lastLimboFreeSnapshotVersion", "__PRIVATE_remoteKeys", "__PRIVATE_queryResult", "result", "__PRIVATE_performQueryUsingIndex", "next", "__PRIVATE_performQueryUsingRemoteKeys", "context", "__PRIVATE_executeFullCollectionScan", "__PRIVATE_createCacheIndexes", "size", "__PRIVATE_resultSize", "__PRIVATE_getLogLevel", "LogLevel", "DEBUG", "__PRIVATE_logDebug", "__PRIVATE_stringifyQuery", "PersistencePromise", "resolve", "createTargetIndexes", "__PRIVATE_queryToTarget", "__PRIVATE_queryMatchesAllDocuments", "target", "getIndexType", "__PRIVATE_indexType", "limit", "__PRIVATE_queryWithLimit", "getDocumentsMatchingTarget", "keys", "__PRIVATE_sortedKeys", "getDocuments", "__PRIVATE_indexedDocuments", "getMinOffset", "offset", "__PRIVATE_previousResults", "__PRIVATE_applyQuery", "__PRIVATE_needsRefill", "readTime", "__PRIVATE_appendRemainingResults", "isEqual", "SnapshotVersion", "min", "documents", "toString", "__PRIVATE_newIndexOffsetSuccessorFromReadTime", "results", "__PRIVATE_queryResults", "SortedSet", "__PRIVATE_newQueryComparator", "forEach", "_", "__PRIVATE_maybeDoc", "__PRIVATE_queryMatches", "__PRIVATE_sortedPreviousResults", "__PRIVATE_limboFreeSnapshotVersion", "__PRIVATE_docAtLimitEdge", "limitType", "last", "first", "hasPendingWrites", "version", "compareTo", "IndexOffset", "__PRIVATE_indexedResults", "__PRIVATE_remainingResults", "d", "insert", "__PRIVATE_LocalStoreImpl", "persistence", "__PRIVATE_queryEngine", "initialUser", "serializer", "__PRIVATE_targetDataByTarget", "SortedMap", "__PRIVATE_primitiveComparator", "__PRIVATE_targetIdByTarget", "ObjectMap", "t", "__PRIVATE_canonifyTarget", "__PRIVATE_targetEquals", "__PRIVATE_collectionGroupReadTime", "Map", "__PRIVATE_remoteDocuments", "getRemoteDocumentCache", "__PRIVATE_targetCache", "getTargetCache", "__PRIVATE_bundleCache", "getBundleCache", "__PRIVATE_initializeUserComponents", "user", "documentOverlayCache", "getDocumentOverlayCache", "getIndexManager", "mutationQueue", "getMutationQueue", "LocalDocumentsView", "setIndexManager", "collectGarbage", "garbageCollector", "runTransaction", "txn", "collect", "__PRIVATE_newLocalStore", "__PRIVATE_localStoreHandleUserChange", "localStore", "__PRIVATE_localStoreImpl", "__PRIVATE_debugCast", "__PRIVATE_oldBatches", "getAllMutationBatches", "__PRIVATE_promisedOldBatches", "__PRIVATE_newBatches", "removedBatchIds", "addedBatchIds", "__PRIVATE_changedKeys", "batch", "push", "batchId", "mutation", "mutations", "__PRIVATE_affectedDocuments", "__PRIVATE_localStoreAcknowledgeBatch", "batchResult", "__PRIVATE_affected", "__PRIVATE_documentBuffer", "newChangeBuffer", "trackRemovals", "__PRIVATE_docKeys", "__PRIVATE_promiseChain", "__PRIVATE_docKey", "getEntry", "__PRIVATE_ackVersion", "docVersions", "get", "__PRIVATE_hardAssert", "applyToRemoteDocument", "isValidDocument", "setReadTime", "commitVersion", "addEntry", "removeMutationBatch", "apply", "performConsistencyCheck", "removeOverlaysForBatchId", "recalculateAndSaveOverlaysForDocumentKeys", "__PRIVATE_i", "mutationResults", "length", "transformResults", "__PRIVATE_localStoreGetLastRemoteSnapshotVersion", "getLastRemoteSnapshotVersion", "__PRIVATE_localStoreApplyRemoteEventToLocalCache", "remoteEvent", "__PRIVATE_remoteVersion", "snapshotVersion", "__PRIVATE_newTargetDataByTargetMap", "__PRIVATE_promises", "targetChanges", "__PRIVATE_change", "__PRIVATE_oldTargetData", "removeMatchingKeys", "removedDocuments", "addMatchingKeys", "addedDocuments", "__PRIVATE_newTargetData", "withSequenceNumber", "currentSequenceNumber", "targetMismatches", "withResumeToken", "ByteString", "EMPTY_BYTE_STRING", "withLastLimboFreeSnapshotVersion", "resumeToken", "approximateByteSize", "toMicroseconds", "modifiedDocuments", "updateTargetData", "__PRIVATE_changedDocs", "__PRIVATE_mutableDocumentMap", "__PRIVATE_existenceChangedKeys", "documentUpdates", "resolvedLimboDocuments", "has", "referenceDelegate", "updateLimboDocument", "__PRIVATE_populateDocumentChangeBuffer", "__PRIVATE_changedDocuments", "__PRIVATE_updateRemoteVersion", "lastRemoteSnapshotVersion", "setTargetsMetadata", "waitFor", "getLocalViewOfDocuments", "then", "__PRIVATE_updatedKeys", "k", "getEntries", "__PRIVATE_existingDocs", "__PRIVATE_existingDoc", "isFoundDocument", "isNoDocument", "removeEntry", "__PRIVATE_localStoreGetNextMutationBatch", "__PRIVATE_afterBatchId", "undefined", "getNextMutationBatchAfterBatchId", "__PRIVATE_localStoreAllocateTarget", "targetData", "getTargetData", "__PRIVATE_cached", "allocateTargetId", "TargetData", "addTargetData", "__PRIVATE_cachedTargetData", "set", "async", "__PRIVATE_localStoreReleaseTarget", "__PRIVATE_keepPersistedTargetData", "mode", "removeTarget", "e", "__PRIVATE_isIndexedDbTransactionError", "remove", "delete", "__PRIVATE_localStoreExecuteQuery", "__PRIVATE_usePreviousResults", "__PRIVATE_localStoreGetTargetData", "getMatchingKeysForTargetId", "__PRIVATE_setMaxReadTime", "__PRIVATE_queryCollectionGroup", "__PRIVATE_setMaxReadTime", "__PRIVATE_localStoreImpl", "collectionGroup", "__PRIVATE_changedDocs", "readTime", "__PRIVATE_collectionGroupReadTime", "get", "SnapshotVersion", "min", "forEach", "_", "doc", "compareTo", "set", "__PRIVATE_LocalClientState", "constructor", "this", "activeTargetIds", "__PRIVATE_targetIdSet", "__PRIVATE_addQueryTarget", "targetId", "add", "__PRIVATE_removeQueryTarget", "delete", "__PRIVATE_toWebStorageJSON", "data", "toArray", "updateTimeMs", "Date", "now", "JSON", "stringify", "__PRIVATE_MemorySharedClientState", "constructor", "this", "__PRIVATE_localState", "__PRIVATE_LocalClientState", "__PRIVATE_queryState", "onlineStateHandler", "sequenceNumberHandler", "addPendingMutation", "batchId", "updateMutationState", "state", "error", "addLocalQueryTarget", "targetId", "__PRIVATE_addQueryTarget", "updateQueryState", "removeLocalQueryTarget", "__PRIVATE_removeQueryTarget", "isLocalQueryTarget", "activeTargetIds", "has", "clearQueryState", "getAllActiveQueryTargets", "isActiveQueryTarget", "start", "Promise", "resolve", "handleUserChange", "user", "removedBatchIds", "addedBatchIds", "setOnlineState", "onlineState", "shutdown", "writeSequenceNumber", "sequenceNumber", "notifyBundleLoaded", "collectionGroups", "__PRIVATE_NoopConnectivityMonitor", "__PRIVATE_addCallback", "callback", "__PRIVATE_BrowserConnectivityMonitor", "__PRIVATE_networkAvailableListener", "__PRIVATE_onNetworkAvailable", "__PRIVATE_networkUnavailableListener", "__PRIVATE_onNetworkUnavailable", "__PRIVATE_callbacks", "__PRIVATE_configureNetworkMonitoring", "push", "window", "removeEventListener", "addEventListener", "__PRIVATE_logDebug", "static", "undefined", "__PRIVATE_lastUniqueDebugId", "__PRIVATE_generateUniqueDebugId", "__PRIVATE_generateInitialUniqueDebugId", "Math", "round", "__PRIVATE_maxResult", "random", "toString", "__PRIVATE_RPC_NAME_URL_MAPPING", "__PRIVATE_StreamBridge", "args", "__PRIVATE_sendFn", "__PRIVATE_closeFn", "__PRIVATE_onConnected", "__PRIVATE_wrappedOnConnected", "__PRIVATE_onOpen", "__PRIVATE_wrappedOnOpen", "__PRIVATE_onClose", "__PRIVATE_wrappedOnClose", "onMessage", "__PRIVATE_wrappedOnMessage", "close", "send", "msg", "__PRIVATE_callOnConnected", "__PRIVATE_callOnOpen", "__PRIVATE_callOnClose", "err", "__PRIVATE_callOnMessage", "__PRIVATE_LOG_TAG", "__PRIVATE_WebChannelConnection", "__PRIVATE_RestConnection", "databaseInfo", "databaseId", "proto", "ssl", "projectId", "encodeURIComponent", "database", "__PRIVATE_baseUrl", "host", "__PRIVATE_databasePath", "__PRIVATE_requestParams", "__PRIVATE_shouldResourcePathBeIncludedInRequest", "__PRIVATE_invokeRPC", "__PRIVATE_rpcName", "path", "__PRIVATE_req", "__PRIVATE_authToken", "appCheckToken", "streamId", "url", "__PRIVATE_makeUrl", "toUriEncodedString", "headers", "__PRIVATE_modifyHeadersForRequest", "__PRIVATE_performRPCRequest", "then", "response", "__PRIVATE_logWarn", "__PRIVATE_invokeStreamingRPC", "request", "__PRIVATE_expectedResponseCount", "__PRIVATE_getGoogApiClientValue", "SDK_VERSION", "appId", "forEach", "value", "key", "__PRIVATE_urlRpcName", "terminate", "info", "super", "forceLongPolling", "autoDetectLongPolling", "useFetchStreams", "longPollingOptions", "body", "reject", "__PRIVATE_xhr", "XhrIo", "setWithCredentials", "listenOnce", "EventType", "COMPLETE", "getLastErrorCode", "ErrorCode", "NO_ERROR", "json", "getResponseJson", "JSON", "stringify", "TIMEOUT", "FirestoreError", "Code", "DEADLINE_EXCEEDED", "HTTP_ERROR", "status", "getStatus", "getResponseText", "Array", "isArray", "__PRIVATE_responseError", "message", "__PRIVATE_firestoreErrorCode", "__PRIVATE_serverError", "toLowerCase", "replace", "Object", "values", "indexOf", "UNKNOWN", "__PRIVATE_mapCodeFromHttpResponseErrorStatus", "UNAVAILABLE", "fail", "__PRIVATE_requestString", "__PRIVATE_openStream", "__PRIVATE_urlParts", "__PRIVATE_webchannelTransport", "createWebChannelTransport", "__PRIVATE_requestStats", "getStatEventTarget", "httpSessionIdParam", "initMessageHeaders", "messageUrlParams", "sendRawJson", "supportsCrossDomainXhr", "internalChannelParams", "forwardChannelRequestTimeoutMs", "detectBufferingProxy", "__PRIVATE_longPollingTimeoutSeconds", "timeoutSeconds", "longPollingTimeout", "xmlHttpFactory", "FetchXmlHttpFactory", "encodeInitMessageHeaders", "join", "channel", "createWebChannel", "__PRIVATE_opened", "closed", "__PRIVATE_streamBridge", "open", "__PRIVATE_unguardedEventListen", "target", "type", "fn", "listen", "param", "e", "setTimeout", "WebChannel", "OPEN", "CLOSE", "ERROR", "MESSAGE", "__PRIVATE_msgData", "data", "__PRIVATE_hardAssert", "__PRIVATE_msgDataOrError", "_a", "code", "__PRIVATE_RpcCode", "__PRIVATE_mapCodeFromRpcCode", "INTERNAL", "Event", "STAT_EVENT", "event", "stat", "Stat", "PROXY", "NOPROXY", "getDocument", "document", "__PRIVATE_newSerializer", "databaseId", "JsonProtoSerializer", "__PRIVATE_ExponentialBackoff", "constructor", "__PRIVATE_queue", "timerId", "__PRIVATE_initialDelayMs", "__PRIVATE_backoffFactor", "__PRIVATE_maxDelayMs", "this", "__PRIVATE_currentBaseMs", "__PRIVATE_timerPromise", "__PRIVATE_lastAttemptTime", "Date", "now", "reset", "__PRIVATE_resetToMax", "__PRIVATE_backoffAndRun", "op", "cancel", "__PRIVATE_desiredDelayWithJitterMs", "Math", "floor", "__PRIVATE_jitterDelayMs", "__PRIVATE_delaySoFarMs", "max", "__PRIVATE_remainingDelayMs", "__PRIVATE_logDebug", "enqueueAfterDelay", "__PRIVATE_skipBackoff", "skipDelay", "random", "__PRIVATE_PersistentStream", "__PRIVATE_connectionTimerId", "__PRIVATE_idleTimerId", "__PRIVATE_healthTimerId", "connection", "authCredentialsProvider", "appCheckCredentialsProvider", "listener", "state", "__PRIVATE_closeCount", "__PRIVATE_idleTimer", "__PRIVATE_healthCheck", "stream", "__PRIVATE_backoff", "__PRIVATE_isStarted", "__PRIVATE_isOpen", "start", "auth", "__PRIVATE_performBackoff", "async", "close", "__PRIVATE_inhibitBackoff", "__PRIVATE_markIdle", "__PRIVATE_handleIdleCloseTimer", "__PRIVATE_sendRequest", "msg", "__PRIVATE_cancelIdleCheck", "send", "__PRIVATE_cancelHealthCheck", "__PRIVATE_finalState", "error", "code", "Code", "RESOURCE_EXHAUSTED", "__PRIVATE_logError", "toString", "UNAUTHENTICATED", "invalidateToken", "__PRIVATE_tearDown", "__PRIVATE_onClose", "__PRIVATE_dispatchIfNotClosed", "__PRIVATE_getCloseGuardedDispatcher", "Promise", "all", "getToken", "then", "__PRIVATE_authToken", "appCheckToken", "__PRIVATE_startStream", "__PRIVATE_rpcError", "FirestoreError", "UNKNOWN", "message", "__PRIVATE_handleStreamClose", "__PRIVATE_startRpc", "__PRIVATE_onConnected", "__PRIVATE_onOpen", "resolve", "onMessage", "__PRIVATE_startCloseCount", "fn", "enqueueAndForget", "__PRIVATE_PersistentListenStream", "authCredentials", "appCheckCredentials", "serializer", "super", "__PRIVATE_openStream", "__PRIVATE_watchChangeProto", "__PRIVATE_watchChange", "__PRIVATE_fromWatchChange", "snapshot", "__PRIVATE_change", "SnapshotVersion", "min", "targetChange", "targetIds", "length", "readTime", "__PRIVATE_fromVersion", "__PRIVATE_onWatchChange", "__PRIVATE_watch", "targetData", "request", "database", "__PRIVATE_getEncodedDatabaseId", "addTarget", "result", "target", "__PRIVATE_targetIsDocumentTarget", "documents", "__PRIVATE_toDocumentsTarget", "query", "__PRIVATE_toQueryTarget", "__PRIVATE_queryTarget", "targetId", "resumeToken", "approximateByteSize", "__PRIVATE_toBytes", "expectedCount", "__PRIVATE_toInt32Proto", "snapshotVersion", "compareTo", "toTimestamp", "__PRIVATE_toTarget", "labels", "__PRIVATE_toListenRequestLabels", "__PRIVATE_unwatch", "removeTarget", "__PRIVATE_PersistentWriteStream", "__PRIVATE_handshakeComplete_", "__PRIVATE_handshakeComplete", "lastStreamToken", "__PRIVATE_writeMutations", "__PRIVATE_responseProto", "__PRIVATE_hardAssert", "streamToken", "results", "__PRIVATE_fromWriteResults", "writeResults", "commitTime", "commitVersion", "__PRIVATE_onMutationResult", "__PRIVATE_onHandshakeComplete", "__PRIVATE_writeHandshake", "mutations", "writes", "map", "mutation", "toMutation", "__PRIVATE_DatastoreImpl", "Datastore", "__PRIVATE_terminated", "__PRIVATE_verifyInitialized", "FAILED_PRECONDITION", "__PRIVATE_invokeRPC", "__PRIVATE_rpcName", "__PRIVATE_resourcePath", "__PRIVATE_toResourcePath", "catch", "name", "__PRIVATE_invokeStreamingRPC", "__PRIVATE_expectedResponseCount", "terminate", "__PRIVATE_OnlineStateTracker", "asyncQueue", "onlineStateHandler", "__PRIVATE_watchStreamFailures", "__PRIVATE_onlineStateTimer", "__PRIVATE_shouldWarnClientIsOffline", "__PRIVATE_handleWatchStreamStart", "__PRIVATE_setAndBroadcast", "__PRIVATE_logClientOfflineWarningIfNecessary", "__PRIVATE_handleWatchStreamFailure", "__PRIVATE_clearOnlineStateTimer", "set", "__PRIVATE_newState", "details", "__PRIVATE_RemoteStoreImpl", "localStore", "datastore", "__PRIVATE_connectivityMonitor", "remoteSyncer", "__PRIVATE_writePipeline", "__PRIVATE_listenTargets", "Map", "__PRIVATE_offlineCauses", "Set", "__PRIVATE_onNetworkStatusChange", "__PRIVATE_addCallback", "_", "__PRIVATE_canUseNetwork", "remoteStore", "__PRIVATE_remoteStoreImpl", "__PRIVATE_debugCast", "add", "__PRIVATE_disableNetworkInternal", "__PRIVATE_onlineStateTracker", "delete", "__PRIVATE_enableNetworkInternal", "__PRIVATE_networkStatusHandler", "__PRIVATE_remoteStoreListen", "has", "__PRIVATE_shouldStartWatchStream", "__PRIVATE_startWatchStream", "__PRIVATE_ensureWatchStream", "__PRIVATE_sendWatchRequest", "__PRIVATE_remoteStoreUnlisten", "__PRIVATE_watchStream", "__PRIVATE_sendUnwatchRequest", "size", "__PRIVATE_watchChangeAggregator", "__PRIVATE_recordPendingTargetRequest", "getRemoteKeysForTarget", "withExpectedCount", "__PRIVATE_WatchChangeAggregator", "__PRIVATE_getTargetDataForTarget", "get", "__PRIVATE_getDatabaseId", "__PRIVATE_cleanUpWatchStreamState", "undefined", "__PRIVATE_onWatchStreamConnected", "__PRIVATE_onWatchStreamOpen", "forEach", "__PRIVATE_onWatchStreamClose", "__PRIVATE_onWatchStreamChange", "__PRIVATE_WatchTargetChange", "cause", "rejectListen", "e", "join", "__PRIVATE_disableNetworkUntilRecovery", "__PRIVATE_DocumentWatchChange", "__PRIVATE_handleDocumentChange", "__PRIVATE_ExistenceFilterChange", "__PRIVATE_handleExistenceFilter", "__PRIVATE_handleTargetChange", "isEqual", "lastRemoteSnapshotVersion", "__PRIVATE_localStoreGetLastRemoteSnapshotVersion", "remoteEvent", "__PRIVATE_createRemoteEvent", "targetChanges", "withResumeToken", "targetMismatches", "__PRIVATE_targetPurpose", "ByteString", "EMPTY_BYTE_STRING", "__PRIVATE_requestTargetData", "TargetData", "sequenceNumber", "applyRemoteEvent", "__PRIVATE_raiseWatchSnapshot", "__PRIVATE_isIndexedDbTransactionError", "enqueueRetryable", "__PRIVATE_executeWithRecovery", "__PRIVATE_fillWritePipeline", "__PRIVATE_writeStream", "__PRIVATE_ensureWriteStream", "__PRIVATE_lastBatchIdRetrieved", "batchId", "__PRIVATE_canAddToWritePipeline", "batch", "__PRIVATE_localStoreGetNextMutationBatch", "__PRIVATE_addToWritePipeline", "__PRIVATE_shouldStartWriteStream", "__PRIVATE_startWriteStream", "push", "__PRIVATE_onWriteStreamOpen", "__PRIVATE_onWriteHandshakeComplete", "shift", "__PRIVATE_success", "MutationBatchResult", "from", "applySuccessfulWrite", "__PRIVATE_onWriteStreamClose", "__PRIVATE_isPermanentError", "ABORTED", "__PRIVATE_isPermanentWriteError", "rejectFailedWrite", "__PRIVATE_handleWriteError", "__PRIVATE_remoteStoreHandleCredentialChange", "user", "verifyOperationInProgress", "__PRIVATE_usesNetwork", "handleCredentialChange", "__PRIVATE_remoteStoreApplyPrimaryState", "isPrimary", "__PRIVATE_datastoreImpl", "bind", "enabled", "stop", "DelayedOperation", "targetTimeMs", "removalCallback", "deferred", "__PRIVATE_Deferred", "promise", "err", "static", "delayMs", "__PRIVATE_targetTime", "__PRIVATE_delayedOp", "timerHandle", "setTimeout", "handleDelayElapsed", "reason", "clearTimeout", "reject", "CANCELLED", "__PRIVATE_wrapInUserErrorIfRecoverable", "UNAVAILABLE", "DocumentSet", "comp", "comparator", "__PRIVATE_d1", "__PRIVATE_d2", "DocumentKey", "key", "keyedMap", "documentMap", "sortedSet", "SortedMap", "oldSet", "first", "minKey", "last", "maxKey", "isEmpty", "indexOf", "doc", "cb", "inorderTraversal", "k", "v", "copy", "insert", "remove", "other", "__PRIVATE_thisIt", "getIterator", "__PRIVATE_otherIt", "hasNext", "__PRIVATE_thisDoc", "getNext", "__PRIVATE_otherDoc", "__PRIVATE_docStrings", "__PRIVATE_newSet", "__PRIVATE_DocumentChangeSet", "__PRIVATE_changeMap", "track", "__PRIVATE_oldChange", "type", "fail", "__PRIVATE_getChanges", "changes", "ViewSnapshot", "docs", "oldDocs", "docChanges", "mutatedKeys", "fromCache", "syncStateChanged", "excludesMetadataChanges", "hasCachedResults", "emptySet", "hasPendingWrites", "__PRIVATE_queryEquals", "__PRIVATE_otherChanges", "__PRIVATE_i", "__PRIVATE_QueryListenersInfo", "__PRIVATE_viewSnap", "__PRIVATE_listeners", "__PRIVATE_hasRemoteListeners", "some", "__PRIVATE_listensToRemoteStore", "__PRIVATE_EventManagerImpl", "queries", "ObjectMap", "q", "__PRIVATE_canonifyQuery", "onlineState", "__PRIVATE_snapshotsInSyncListeners", "__PRIVATE_eventManagerListen", "eventManager", "__PRIVATE_eventManagerImpl", "__PRIVATE_listenerAction", "__PRIVATE_queryInfo", "onListen", "onFirstRemoteStoreListen", "__PRIVATE_firestoreError", "__PRIVATE_stringifyQuery", "onError", "__PRIVATE_applyOnlineStateChange", "__PRIVATE_onViewSnapshot", "__PRIVATE_raiseSnapshotsInSyncEvent", "__PRIVATE_eventManagerUnlisten", "splice", "onUnlisten", "onLastRemoteStoreUnlisten", "__PRIVATE_eventManagerOnWatchChange", "__PRIVATE_viewSnaps", "__PRIVATE_raisedEvent", "__PRIVATE_eventManagerOnWatchError", "observer", "next", "__PRIVATE_ListenerDataSource", "ListenerDataSource", "__PRIVATE_QueryListener", "__PRIVATE_queryObserver", "options", "__PRIVATE_raisedInitialEvent", "__PRIVATE_snap", "includeMetadataChanges", "__PRIVATE_docChange", "__PRIVATE_shouldRaiseEvent", "__PRIVATE_shouldRaiseInitialEvent", "__PRIVATE_raiseInitialEvent", "__PRIVATE_maybeOnline", "__PRIVATE_waitForSyncWhenOnline", "__PRIVATE_hasPendingWritesChanged", "fromInitialDocuments", "source", "Cache", "__PRIVATE_AddedLimboDocument", "constructor", "key", "this", "__PRIVATE_RemovedLimboDocument", "__PRIVATE_View", "query", "__PRIVATE__syncedDocuments", "__PRIVATE_syncState", "hasCachedResults", "current", "__PRIVATE_limboDocuments", "__PRIVATE_documentKeySet", "mutatedKeys", "__PRIVATE_docComparator", "__PRIVATE_newQueryComparator", "__PRIVATE_documentSet", "DocumentSet", "__PRIVATE_syncedDocuments", "__PRIVATE_computeDocChanges", "docChanges", "__PRIVATE_previousChanges", "__PRIVATE_changeSet", "__PRIVATE_DocumentChangeSet", "__PRIVATE_oldDocumentSet", "__PRIVATE_newMutatedKeys", "__PRIVATE_newDocumentSet", "__PRIVATE_needsRefill", "__PRIVATE_lastDocInLimit", "limitType", "size", "limit", "last", "__PRIVATE_firstDocInLimit", "first", "inorderTraversal", "entry", "__PRIVATE_oldDoc", "get", "__PRIVATE_newDoc", "__PRIVATE_queryMatches", "__PRIVATE_oldDocHadPendingMutations", "has", "__PRIVATE_newDocHasPendingMutations", "hasLocalMutations", "hasCommittedMutations", "__PRIVATE_changeApplied", "data", "isEqual", "track", "type", "doc", "__PRIVATE_shouldWaitForSyncedDocument", "add", "delete", "applyChanges", "__PRIVATE_limboResolutionEnabled", "targetChange", "__PRIVATE_targetIsPendingReset", "oldDocs", "changes", "__PRIVATE_getChanges", "sort", "__PRIVATE_c1", "__PRIVATE_c2", "order", "__PRIVATE_change", "fail", "__PRIVATE_applyTargetChange", "__PRIVATE_limboChanges", "__PRIVATE_updateLimboDocuments", "__PRIVATE_newSyncState", "syncStateChanged", "length", "snapshot", "ViewSnapshot", "resumeToken", "approximateByteSize", "__PRIVATE_applyOnlineStateChange", "onlineState", "__PRIVATE_shouldBeInLimbo", "addedDocuments", "forEach", "modifiedDocuments", "removedDocuments", "__PRIVATE_oldLimboDocuments", "push", "__PRIVATE_synchronizeWithPersistedState", "__PRIVATE_queryResult", "__PRIVATE_remoteKeys", "documents", "__PRIVATE_computeInitialSnapshot", "fromInitialDocuments", "__PRIVATE_QueryView", "targetId", "view", "LimboResolution", "__PRIVATE_receivedDocument", "__PRIVATE_SyncEngineImpl", "localStore", "remoteStore", "eventManager", "sharedClientState", "currentUser", "maxConcurrentLimboResolutions", "__PRIVATE_syncEngineListener", "__PRIVATE_queryViewsByQuery", "ObjectMap", "q", "__PRIVATE_canonifyQuery", "__PRIVATE_queryEquals", "__PRIVATE_queriesByTarget", "Map", "__PRIVATE_enqueuedLimboResolutions", "Set", "__PRIVATE_activeLimboTargetsByKey", "SortedMap", "DocumentKey", "comparator", "__PRIVATE_activeLimboResolutionsByTarget", "__PRIVATE_limboDocumentRefs", "__PRIVATE_ReferenceSet", "__PRIVATE_mutationUserCallbacks", "__PRIVATE_pendingWritesCallbacks", "__PRIVATE_limboTargetIdGenerator", "__PRIVATE_TargetIdGenerator", "__PRIVATE_forSyncEngine", "__PRIVATE__isPrimaryClient", "undefined", "isPrimaryClient", "async", "__PRIVATE_syncEngineListen", "syncEngine", "__PRIVATE_shouldListenToRemote", "__PRIVATE_syncEngineImpl", "__PRIVATE_ensureWatchCallbacks", "__PRIVATE_viewSnapshot", "__PRIVATE_queryView", "addLocalQueryTarget", "__PRIVATE_allocateTargetAndMaybeListen", "__PRIVATE_triggerRemoteStoreListen", "__PRIVATE_shouldInitializeView", "targetData", "__PRIVATE_localStoreAllocateTarget", "__PRIVATE_queryToTarget", "status", "__PRIVATE_initializeViewAndComputeSnapshot", "__PRIVATE_remoteStoreListen", "__PRIVATE_applyDocChanges", "remoteEvent", "__PRIVATE_viewDocChanges", "__PRIVATE_localStoreExecuteQuery", "then", "targetChanges", "targetMismatches", "__PRIVATE_viewChange", "__PRIVATE_updateTrackedLimbos", "__PRIVATE_synthesizedTargetChange", "TargetChange", "createSynthesizedTargetChangeForCurrentChange", "set", "__PRIVATE_syncEngineUnlisten", "__PRIVATE_shouldUnlistenToRemote", "__PRIVATE_debugCast", "queries", "filter", "removeLocalQueryTarget", "isActiveQueryTarget", "__PRIVATE_localStoreReleaseTarget", "clearQueryState", "__PRIVATE_remoteStoreUnlisten", "__PRIVATE_removeAndCleanupTarget", "catch", "__PRIVATE_ignoreIfPrimaryLeaseLoss", "__PRIVATE_triggerRemoteStoreUnlisten", "__PRIVATE_syncEngineWrite", "batch", "__PRIVATE_userCallback", "__PRIVATE_syncEngineEnsureWriteCallbacks", "result", "mutations", "__PRIVATE_localStoreImpl", "localWriteTime", "Timestamp", "now", "keys", "reduce", "m", "__PRIVATE_overlayedDocuments", "__PRIVATE_mutationBatch", "persistence", "runTransaction", "txn", "__PRIVATE_remoteDocs", "__PRIVATE_mutableDocumentMap", "__PRIVATE_docsWithoutRemoteVersion", "__PRIVATE_remoteDocuments", "getEntries", "next", "docs", "isValidDocument", "localDocuments", "getOverlayedDocuments", "baseMutations", "mutation", "__PRIVATE_baseValue", "__PRIVATE_mutationExtractBaseValue", "overlayedDocument", "__PRIVATE_PatchMutation", "__PRIVATE_extractFieldMask", "value", "mapValue", "Precondition", "exists", "mutationQueue", "addMutationBatch", "overlays", "applyToLocalDocumentSet", "documentOverlayCache", "saveOverlays", "batchId", "__PRIVATE_convertOverlayedDocumentMapToDocumentMap", "__PRIVATE_localStoreWriteLocally", "addPendingMutation", "callback", "__PRIVATE_newCallbacks", "toKey", "__PRIVATE_primitiveComparator", "insert", "__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore", "__PRIVATE_fillWritePipeline", "e", "error", "__PRIVATE_wrapInUserErrorIfRecoverable", "reject", "__PRIVATE_syncEngineApplyRemoteEvent", "__PRIVATE_localStoreApplyRemoteEventToLocalCache", "__PRIVATE_limboResolution", "__PRIVATE_hardAssert", "__PRIVATE_syncEngineApplyOnlineStateChange", "source", "__PRIVATE_newViewSnapshots", "__PRIVATE_eventManagerImpl", "__PRIVATE_raisedEvent", "_", "__PRIVATE_queryInfo", "listener", "__PRIVATE_listeners", "__PRIVATE_raiseSnapshotsInSyncEvent", "__PRIVATE_eventManagerOnOnlineStateChange", "__PRIVATE_onWatchChange", "setOnlineState", "__PRIVATE_syncEngineRejectListen", "err", "updateQueryState", "__PRIVATE_limboKey", "documentUpdates", "MutableDocument", "newNoDocument", "SnapshotVersion", "min", "resolvedLimboDocuments", "event", "RemoteEvent", "remove", "__PRIVATE_pumpEnqueuedLimboResolutions", "__PRIVATE_syncEngineApplySuccessfulWrite", "__PRIVATE_mutationBatchResult", "__PRIVATE_localStoreAcknowledgeBatch", "__PRIVATE_processUserCallback", "__PRIVATE_triggerPendingWritesCallbacks", "updateMutationState", "__PRIVATE_syncEngineRejectFailedWrite", "__PRIVATE_affectedKeys", "lookupMutationBatch", "removeMutationBatch", "performConsistencyCheck", "removeOverlaysForBatchId", "recalculateAndSaveOverlaysForDocumentKeys", "getDocuments", "__PRIVATE_triggerPendingWritesCallbacks", "__PRIVATE_syncEngineImpl", "batchId", "__PRIVATE_pendingWritesCallbacks", "get", "forEach", "callback", "resolve", "delete", "__PRIVATE_processUserCallback", "syncEngine", "error", "__PRIVATE_debugCast", "__PRIVATE_newCallbacks", "__PRIVATE_mutationUserCallbacks", "currentUser", "toKey", "reject", "remove", "__PRIVATE_removeAndCleanupTarget", "targetId", "sharedClientState", "removeLocalQueryTarget", "query", "__PRIVATE_queriesByTarget", "__PRIVATE_queryViewsByQuery", "__PRIVATE_syncEngineListener", "__PRIVATE_onWatchError", "isPrimaryClient", "__PRIVATE_limboDocumentRefs", "__PRIVATE_removeReferencesForId", "__PRIVATE_limboKey", "containsKey", "__PRIVATE_removeLimboTarget", "key", "__PRIVATE_enqueuedLimboResolutions", "path", "canonicalString", "__PRIVATE_limboTargetId", "__PRIVATE_activeLimboTargetsByKey", "__PRIVATE_remoteStoreUnlisten", "remoteStore", "__PRIVATE_activeLimboResolutionsByTarget", "__PRIVATE_pumpEnqueuedLimboResolutions", "__PRIVATE_updateTrackedLimbos", "__PRIVATE_limboChanges", "__PRIVATE_limboChange", "__PRIVATE_AddedLimboDocument", "addReference", "__PRIVATE_trackLimboChange", "__PRIVATE_RemovedLimboDocument", "__PRIVATE_logDebug", "removeReference", "fail", "__PRIVATE_keyString", "has", "add", "size", "maxConcurrentLimboResolutions", "values", "next", "value", "DocumentKey", "ResourcePath", "fromString", "__PRIVATE_limboTargetIdGenerator", "set", "LimboResolution", "insert", "__PRIVATE_remoteStoreListen", "TargetData", "__PRIVATE_queryToTarget", "__PRIVATE_newQueryForPath", "__PRIVATE_ListenSequence", "__PRIVATE_INVALID", "async", "__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore", "changes", "remoteEvent", "__PRIVATE_newSnaps", "__PRIVATE_docChangesInAllViews", "__PRIVATE_queriesProcessed", "isEmpty", "_", "__PRIVATE_queryView", "push", "__PRIVATE_applyDocChanges", "then", "__PRIVATE_viewSnapshot", "__PRIVATE_isCurrent", "fromCache", "updateQueryState", "docChanges", "__PRIVATE_LocalViewChanges", "__PRIVATE_fromSnapshot", "Promise", "all", "__PRIVATE_onWatchChange", "localStore", "__PRIVATE_viewChanges", "__PRIVATE_localStoreImpl", "persistence", "runTransaction", "txn", "PersistencePromise", "__PRIVATE_viewChange", "__PRIVATE_addedKeys", "referenceDelegate", "__PRIVATE_removedKeys", "e", "__PRIVATE_isIndexedDbTransactionError", "targetData", "__PRIVATE_targetDataByTarget", "lastLimboFreeSnapshotVersion", "snapshotVersion", "__PRIVATE_updatedTargetData", "withLastLimboFreeSnapshotVersion", "__PRIVATE_localStoreNotifyLocalViewChanges", "__PRIVATE_syncEngineHandleCredentialChange", "user", "isEqual", "result", "__PRIVATE_localStoreHandleUserChange", "__PRIVATE_errorMessage", "__PRIVATE_callbacks", "FirestoreError", "Code", "CANCELLED", "clear", "__PRIVATE_rejectOutstandingPendingWritesCallbacks", "handleUserChange", "removedBatchIds", "addedBatchIds", "__PRIVATE_affectedDocuments", "__PRIVATE_syncEngineGetRemoteKeysForTarget", "__PRIVATE_limboResolution", "__PRIVATE_receivedDocument", "__PRIVATE_documentKeySet", "__PRIVATE_keySet", "queries", "unionWith", "view", "__PRIVATE_syncedDocuments", "__PRIVATE_ensureWatchCallbacks", "syncEngine", "__PRIVATE_syncEngineImpl", "__PRIVATE_debugCast", "remoteStore", "remoteSyncer", "applyRemoteEvent", "__PRIVATE_syncEngineApplyRemoteEvent", "bind", "getRemoteKeysForTarget", "__PRIVATE_syncEngineGetRemoteKeysForTarget", "rejectListen", "__PRIVATE_syncEngineRejectListen", "__PRIVATE_syncEngineListener", "__PRIVATE_onWatchChange", "__PRIVATE_eventManagerOnWatchChange", "eventManager", "__PRIVATE_onWatchError", "__PRIVATE_eventManagerOnWatchError", "__PRIVATE_syncEngineEnsureWriteCallbacks", "applySuccessfulWrite", "__PRIVATE_syncEngineApplySuccessfulWrite", "rejectFailedWrite", "__PRIVATE_syncEngineRejectFailedWrite", "MemoryOfflineComponentProvider", "constructor", "this", "synchronizeTabs", "async", "cfg", "serializer", "__PRIVATE_newSerializer", "databaseInfo", "databaseId", "sharedClientState", "createSharedClientState", "persistence", "createPersistence", "start", "localStore", "createLocalStore", "gcScheduler", "createGarbageCollectionScheduler", "indexBackfillerScheduler", "createIndexBackfillerScheduler", "__PRIVATE_newLocalStore", "__PRIVATE_QueryEngine", "initialUser", "__PRIVATE_MemoryPersistence", "__PRIVATE_MemoryEagerDelegate", "__PRIVATE_factory", "__PRIVATE_MemorySharedClientState", "_a", "stop", "_b", "shutdown", "OnlineComponentProvider", "async", "offlineComponentProvider", "cfg", "this", "localStore", "sharedClientState", "datastore", "createDatastore", "remoteStore", "createRemoteStore", "eventManager", "createEventManager", "syncEngine", "createSyncEngine", "synchronizeTabs", "onlineStateHandler", "onlineState", "__PRIVATE_syncEngineApplyOnlineStateChange", "remoteSyncer", "handleCredentialChange", "__PRIVATE_syncEngineHandleCredentialChange", "bind", "__PRIVATE_remoteStoreApplyPrimaryState", "isPrimaryClient", "__PRIVATE_newEventManager", "__PRIVATE_EventManagerImpl", "serializer", "__PRIVATE_newSerializer", "databaseInfo", "databaseId", "connection", "__PRIVATE_WebChannelConnection", "authCredentials", "appCheckCredentials", "__PRIVATE_DatastoreImpl", "__PRIVATE_newDatastore", "asyncQueue", "__PRIVATE_connectivityMonitor", "__PRIVATE_RemoteStoreImpl", "__PRIVATE_newConnectivityMonitor", "__PRIVATE_BrowserConnectivityMonitor", "__PRIVATE_isAvailable", "__PRIVATE_NoopConnectivityMonitor", "startAsPrimary", "__PRIVATE_newSyncEngine", "currentUser", "maxConcurrentLimboResolutions", "isPrimary", "__PRIVATE_SyncEngineImpl", "__PRIVATE__isPrimaryClient", "initialUser", "__PRIVATE_remoteStoreImpl", "__PRIVATE_debugCast", "__PRIVATE_logDebug", "__PRIVATE_offlineCauses", "add", "__PRIVATE_disableNetworkInternal", "shutdown", "__PRIVATE_onlineStateTracker", "set", "_a", "terminate", "__PRIVATE_AsyncObserver", "constructor", "observer", "this", "muted", "next", "value", "__PRIVATE_scheduleEvent", "error", "__PRIVATE_logError", "toString", "__PRIVATE_mute", "__PRIVATE_eventHandler", "event", "setTimeout", "FirestoreClient", "constructor", "authCredentials", "appCheckCredentials", "asyncQueue", "databaseInfo", "this", "user", "User", "UNAUTHENTICATED", "clientId", "__PRIVATE_AutoId", "newId", "authCredentialListener", "Promise", "resolve", "appCheckCredentialListener", "start", "async", "__PRIVATE_logDebug", "uid", "__PRIVATE_newAppCheckToken", "configuration", "initialUser", "maxConcurrentLimboResolutions", "setCredentialChangeListener", "listener", "setAppCheckTokenChangeListener", "verifyNotTerminated", "isShuttingDown", "FirestoreError", "Code", "FAILED_PRECONDITION", "terminate", "enterRestrictedMode", "deferred", "__PRIVATE_Deferred", "enqueueAndForgetEvenWhileRestricted", "_onlineComponents", "_offlineComponents", "shutdown", "e", "__PRIVATE_firestoreError", "__PRIVATE_wrapInUserErrorIfRecoverable", "reject", "promise", "__PRIVATE_setOfflineComponentProvider", "__PRIVATE_client", "offlineComponentProvider", "verifyOperationInProgress", "initialize", "currentUser", "isEqual", "__PRIVATE_localStoreHandleUserChange", "localStore", "persistence", "setDatabaseDeletedListener", "__PRIVATE_setOnlineComponentProvider", "__PRIVATE_onlineComponentProvider", "__PRIVATE_ensureOfflineComponents", "__PRIVATE_remoteStoreHandleCredentialChange", "remoteStore", "_", "__PRIVATE_canFallbackFromIndexedDbError", "error", "name", "code", "UNIMPLEMENTED", "DOMException", "_uninitializedComponentsProvider", "_offline", "__PRIVATE_logWarn", "MemoryOfflineComponentProvider", "__PRIVATE_ensureOnlineComponents", "_online", "OnlineComponentProvider", "__PRIVATE_getSyncEngine", "__PRIVATE_client", "__PRIVATE_ensureOnlineComponents", "then", "c", "syncEngine", "async", "__PRIVATE_getEventManager", "__PRIVATE_client", "__PRIVATE_onlineComponentProvider", "__PRIVATE_ensureOnlineComponents", "eventManager", "onListen", "__PRIVATE_syncEngineListen", "bind", "syncEngine", "onUnlisten", "__PRIVATE_syncEngineUnlisten", "onFirstRemoteStoreListen", "__PRIVATE_triggerRemoteStoreListen", "onLastRemoteStoreUnlisten", "__PRIVATE_triggerRemoteStoreUnlisten", "__PRIVATE_firestoreClientGetDocumentViaSnapshotListener", "__PRIVATE_client", "key", "options", "deferred", "__PRIVATE_Deferred", "asyncQueue", "enqueueAndForget", "async", "eventManager", "result", "__PRIVATE_wrappedObserver", "__PRIVATE_AsyncObserver", "next", "__PRIVATE_snap", "__PRIVATE_eventManagerUnlisten", "listener", "exists", "docs", "has", "fromCache", "reject", "FirestoreError", "Code", "UNAVAILABLE", "source", "resolve", "error", "e", "__PRIVATE_QueryListener", "__PRIVATE_newQueryForPath", "path", "includeMetadataChanges", "__PRIVATE_waitForSyncWhenOnline", "__PRIVATE_eventManagerListen", "__PRIVATE_readDocumentViaSnapshotListener", "__PRIVATE_getEventManager", "promise", "__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener", "__PRIVATE_client", "query", "options", "deferred", "__PRIVATE_Deferred", "asyncQueue", "enqueueAndForget", "async", "eventManager", "result", "__PRIVATE_wrappedObserver", "__PRIVATE_AsyncObserver", "next", "snapshot", "__PRIVATE_eventManagerUnlisten", "listener", "fromCache", "source", "reject", "FirestoreError", "Code", "UNAVAILABLE", "resolve", "error", "e", "__PRIVATE_QueryListener", "includeMetadataChanges", "__PRIVATE_waitForSyncWhenOnline", "__PRIVATE_eventManagerListen", "__PRIVATE_executeQueryViaSnapshotListener", "__PRIVATE_getEventManager", "promise", "__PRIVATE_cloneLongPollingOptions", "options", "clone", "timeoutSeconds", "__PRIVATE_datastoreInstances", "Map", "__PRIVATE_validateNonEmptyArgument", "__PRIVATE_functionName", "__PRIVATE_argumentName", "__PRIVATE_argument", "FirestoreError", "Code", "INVALID_ARGUMENT", "__PRIVATE_validateIsNotUsedTogether", "optionName1", "argument1", "optionName2", "argument2", "__PRIVATE_validateDocumentPath", "path", "DocumentKey", "isDocumentKey", "length", "__PRIVATE_validateCollectionPath", "__PRIVATE_valueDescription", "input", "undefined", "substring", "JSON", "stringify", "Array", "__PRIVATE_customObjectName", "constructor", "name", "fail", "__PRIVATE_cast", "obj", "_delegate", "description", "FirestoreSettingsImpl", "constructor", "settings", "host", "undefined", "ssl", "FirestoreError", "Code", "INVALID_ARGUMENT", "this", "_a", "credentials", "ignoreUndefinedProperties", "localCache", "cacheSizeBytes", "__PRIVATE_validateIsNotUsedTogether", "experimentalForceLongPolling", "experimentalAutoDetectLongPolling", "experimentalLongPollingOptions", "__PRIVATE_cloneLongPollingOptions", "_b", "options", "timeoutSeconds", "isNaN", "useFetchStreams", "isEqual", "other", "__PRIVATE_options1", "__PRIVATE_options2", "Firestore", "_authCredentials", "_appCheckCredentials", "_databaseId", "_app", "type", "_persistenceKey", "_settings", "_settingsFrozen", "app", "FAILED_PRECONDITION", "_initialized", "_terminated", "_terminateTask", "_setSettings", "__PRIVATE_EmptyAuthCredentialsProvider", "__PRIVATE_FirstPartyAuthCredentialsProvider", "__PRIVATE_makeAuthCredentialsProvider", "_getSettings", "_freezeSettings", "_delete", "_terminate", "toJSON", "databaseId", "firestore", "datastore", "__PRIVATE_datastoreInstances", "get", "__PRIVATE_logDebug", "delete", "terminate", "__PRIVATE_removeComponents", "Promise", "resolve", "connectFirestoreEmulator", "port", "__PRIVATE_cast", "__PRIVATE_newHostSetting", "__PRIVATE_logWarn", "Object", "assign", "mockUserToken", "token", "user", "User", "MOCK_USER", "createMockUserToken", "projectId", "uid", "sub", "user_id", "__PRIVATE_EmulatorAuthCredentialsProvider", "__PRIVATE_OAuthToken", "Query", "converter", "_query", "withConverter", "DocumentReference", "_key", "_path", "path", "id", "lastSegment", "canonicalString", "parent", "CollectionReference", "popLast", "super", "__PRIVATE_newQueryForPath", "parentPath", "isEmpty", "DocumentKey", "collection", "pathSegments", "getModularInstance", "__PRIVATE_validateNonEmptyArgument", "__PRIVATE_absolutePath", "ResourcePath", "fromString", "__PRIVATE_validateCollectionPath", "child", "doc", "parent", "path", "pathSegments", "getModularInstance", "arguments", "length", "__PRIVATE_AutoId", "newId", "__PRIVATE_validateNonEmptyArgument", "Firestore", "__PRIVATE_absolutePath", "ResourcePath", "fromString", "__PRIVATE_validateDocumentPath", "DocumentReference", "DocumentKey", "CollectionReference", "FirestoreError", "Code", "INVALID_ARGUMENT", "_path", "child", "firestore", "converter", "__PRIVATE_AsyncQueueImpl", "constructor", "this", "__PRIVATE_tail", "Promise", "resolve", "__PRIVATE_retryableOps", "__PRIVATE__isShuttingDown", "__PRIVATE_delayedOperations", "__PRIVATE_failure", "__PRIVATE_operationInProgress", "__PRIVATE_skipNonRestrictedTasks", "__PRIVATE_timerIdsToSkip", "__PRIVATE_backoff", "__PRIVATE_ExponentialBackoff", "__PRIVATE_visibilityHandler", "document", "getDocument", "__PRIVATE_logDebug", "visibilityState", "__PRIVATE_skipBackoff", "addEventListener", "isShuttingDown", "enqueueAndForget", "op", "enqueue", "enqueueAndForgetEvenWhileRestricted", "__PRIVATE_verifyNotFailed", "__PRIVATE_enqueueInternal", "enterRestrictedMode", "purgeExistingTasks", "removeEventListener", "task", "__PRIVATE_Deferred", "then", "reject", "promise", "enqueueRetryable", "push", "__PRIVATE_retryNextOp", "async", "length", "shift", "reset", "e", "__PRIVATE_isIndexedDbTransactionError", "__PRIVATE_backoffAndRun", "__PRIVATE_newTail", "catch", "error", "message", "stack", "includes", "__PRIVATE_logError", "result", "enqueueAfterDelay", "timerId", "delayMs", "indexOf", "__PRIVATE_delayedOp", "DelayedOperation", "createAndSchedule", "__PRIVATE_removedOp", "__PRIVATE_removeDelayedOperation", "fail", "verifyOperationInProgress", "__PRIVATE_currentTail", "__PRIVATE_containsDelayedOperation", "__PRIVATE_runAllDelayedOperationsUntil", "__PRIVATE_lastTimerId", "__PRIVATE_drain", "sort", "a", "b", "targetTimeMs", "skipDelay", "__PRIVATE_skipDelaysForTimerId", "index", "splice", "Firestore", "__PRIVATE_LiteFirestore", "constructor", "authCredentialsProvider", "appCheckCredentialsProvider", "databaseId", "app", "super", "this", "type", "_queue", "__PRIVATE_newAsyncQueue", "__PRIVATE_AsyncQueueImpl", "_persistenceKey", "name", "_terminate", "_firestoreClient", "__PRIVATE_configureFirestore", "terminate", "getFirestore", "__PRIVATE_appOrDatabaseId", "__PRIVATE_optionalDatabaseId", "app", "getApp", "databaseId", "db", "_getProvider", "getImmediate", "identifier", "_initialized", "__PRIVATE_emulator", "getDefaultEmulatorHostnameAndPort", "connectFirestoreEmulator", "ensureFirestoreConfigured", "firestore", "_firestoreClient", "__PRIVATE_configureFirestore", "verifyNotTerminated", "settings", "_freezeSettings", "databaseInfo", "appId", "persistenceKey", "DatabaseInfo", "host", "ssl", "experimentalForceLongPolling", "experimentalAutoDetectLongPolling", "__PRIVATE_cloneLongPollingOptions", "experimentalLongPollingOptions", "useFetchStreams", "_databaseId", "_a", "_app", "options", "_persistenceKey", "FirestoreClient", "_authCredentials", "_appCheckCredentials", "_queue", "_b", "localCache", "_offlineComponentProvider", "_c", "_onlineComponentProvider", "_uninitializedComponentsProvider", "_offlineKind", "kind", "_offline", "_online", "Bytes", "constructor", "byteString", "this", "_byteString", "static", "base64", "ByteString", "fromBase64String", "e", "FirestoreError", "Code", "INVALID_ARGUMENT", "array", "fromUint8Array", "toBase64", "toUint8Array", "toString", "isEqual", "other", "FieldPath", "fieldNames", "__PRIVATE_i", "length", "_internalPath", "__PRIVATE_InternalFieldPath", "FieldValue", "constructor", "_methodName", "this", "GeoPoint", "latitude", "longitude", "isFinite", "FirestoreError", "Code", "INVALID_ARGUMENT", "_lat", "_long", "isEqual", "other", "toJSON", "_compareTo", "__PRIVATE_primitiveComparator", "__PRIVATE_RESERVED_FIELD_REGEX", "ParsedSetData", "data", "fieldMask", "fieldTransforms", "toMutation", "key", "precondition", "__PRIVATE_PatchMutation", "__PRIVATE_SetMutation", "__PRIVATE_isWrite", "__PRIVATE_dataSource", "fail", "__PRIVATE_ParseContextImpl", "constructor", "settings", "databaseId", "serializer", "ignoreUndefinedProperties", "fieldTransforms", "fieldMask", "this", "__PRIVATE_validatePath", "path", "__PRIVATE_contextWith", "configuration", "Object", "assign", "__PRIVATE_childContextForField", "field", "__PRIVATE_childPath", "_a", "child", "context", "__PRIVATE_arrayElement", "__PRIVATE_validatePathSegment", "__PRIVATE_childContextForFieldPath", "__PRIVATE_childContextForArray", "index", "undefined", "__PRIVATE_createError", "reason", "methodName", "__PRIVATE_hasConverter", "__PRIVATE_targetDoc", "contains", "fieldPath", "find", "isPrefixOf", "transform", "__PRIVATE_i", "length", "get", "segment", "__PRIVATE_RESERVED_FIELD_REGEX", "test", "__PRIVATE_UserDataReader", "__PRIVATE_newSerializer", "__PRIVATE_createContext", "__PRIVATE_InternalFieldPath", "emptyPath", "__PRIVATE_newUserDataReader", "firestore", "_freezeSettings", "_databaseId", "__PRIVATE_parseSetData", "__PRIVATE_userDataReader", "input", "options", "merge", "mergeFields", "__PRIVATE_validatePlainObject", "__PRIVATE_updateData", "__PRIVATE_parseObject", "FieldMask", "__PRIVATE_validatedFieldPaths", "__PRIVATE_stringOrFieldPath", "__PRIVATE_fieldPathFromArgument", "FirestoreError", "Code", "INVALID_ARGUMENT", "__PRIVATE_fieldMaskContains", "push", "filter", "covers", "ParsedSetData", "ObjectValue", "__PRIVATE_parseData", "input", "context", "__PRIVATE_looksLikeJsonObject", "getModularInstance", "__PRIVATE_validatePlainObject", "__PRIVATE_parseObject", "FieldValue", "value", "__PRIVATE_isWrite", "__PRIVATE_dataSource", "__PRIVATE_createError", "_methodName", "path", "__PRIVATE_fieldTransform", "_toFieldTransform", "fieldTransforms", "push", "undefined", "ignoreUndefinedProperties", "fieldMask", "Array", "settings", "__PRIVATE_arrayElement", "array", "values", "__PRIVATE_entryIndex", "entry", "__PRIVATE_parsedEntry", "__PRIVATE_childContextForArray", "nullValue", "arrayValue", "__PRIVATE_parseArray", "toNumber", "serializer", "booleanValue", "stringValue", "Date", "timestamp", "Timestamp", "fromDate", "timestampValue", "toTimestamp", "seconds", "Math", "floor", "nanoseconds", "GeoPoint", "geoPointValue", "latitude", "longitude", "Bytes", "bytesValue", "__PRIVATE_toBytes", "_byteString", "DocumentReference", "__PRIVATE_thisDb", "databaseId", "__PRIVATE_otherDb", "firestore", "_databaseId", "isEqual", "projectId", "database", "referenceValue", "__PRIVATE_toResourceName", "_key", "__PRIVATE_valueDescription", "obj", "fields", "isEmpty", "length", "forEach", "key", "val", "__PRIVATE_parsedValue", "__PRIVATE_childContextForField", "mapValue", "message", "Object", "getPrototypeOf", "prototype", "__PRIVATE_isPlainObject", "description", "__PRIVATE_fieldPathFromArgument", "methodName", "__PRIVATE_targetDoc", "FieldPath", "_internalPath", "__PRIVATE_fieldPathFromDotSeparatedString", "__PRIVATE_FIELD_PATH_RESERVED", "RegExp", "search", "split", "e", "reason", "__PRIVATE_hasConverter", "__PRIVATE_hasPath", "__PRIVATE_hasDocument", "FirestoreError", "Code", "INVALID_ARGUMENT", "__PRIVATE_fieldMaskContains", "__PRIVATE_haystack", "__PRIVATE_needle", "some", "v", "DocumentSnapshot", "constructor", "_firestore", "_userDataWriter", "_document", "_converter", "this", "id", "lastSegment", "ref", "exists", "data", "snapshot", "QueryDocumentSnapshot", "fromFirestore", "convertValue", "get", "fieldPath", "field", "super", "arg", "_delegate", "__PRIVATE_validateHasExplicitOrderByForLimitToLast", "query", "limitType", "explicitOrderBy", "UNIMPLEMENTED", "AbstractUserDataWriter", "convertValue", "value", "serverTimestampBehavior", "__PRIVATE_typeOrder", "booleanValue", "__PRIVATE_normalizeNumber", "integerValue", "doubleValue", "this", "convertTimestamp", "timestampValue", "convertServerTimestamp", "stringValue", "convertBytes", "__PRIVATE_normalizeByteString", "bytesValue", "convertReference", "referenceValue", "convertGeoPoint", "geoPointValue", "convertArray", "arrayValue", "convertObject", "mapValue", "fail", "convertObjectMap", "fields", "result", "forEach", "key", "GeoPoint", "latitude", "longitude", "values", "map", "previousValue", "__PRIVATE_getPreviousValue", "__PRIVATE_getLocalWriteTime", "__PRIVATE_normalizedValue", "__PRIVATE_normalizeTimestamp", "Timestamp", "seconds", "nanos", "convertDocumentKey", "name", "expectedDatabaseId", "__PRIVATE_resourcePath", "ResourcePath", "fromString", "__PRIVATE_hardAssert", "__PRIVATE_isValidResourceName", "databaseId", "DatabaseId", "get", "DocumentKey", "popFirst", "isEqual", "__PRIVATE_logError", "projectId", "database", "__PRIVATE_applyFirestoreDataConverter", "converter", "options", "__PRIVATE_convertedValue", "merge", "mergeFields", "toFirestore", "SnapshotMetadata", "constructor", "hasPendingWrites", "fromCache", "this", "isEqual", "other", "DocumentSnapshot", "__PRIVATE_LiteDocumentSnapshot", "_firestore", "userDataWriter", "key", "document", "metadata", "converter", "super", "_firestoreImpl", "exists", "data", "options", "_document", "_converter", "snapshot", "QueryDocumentSnapshot", "_userDataWriter", "_key", "fromFirestore", "convertValue", "value", "serverTimestamps", "get", "fieldPath", "field", "__PRIVATE_fieldPathFromArgument", "QuerySnapshot", "query", "_snapshot", "docs", "result", "forEach", "doc", "push", "size", "empty", "callback", "thisArg", "call", "mutatedKeys", "has", "docChanges", "includeMetadataChanges", "excludesMetadataChanges", "FirestoreError", "Code", "INVALID_ARGUMENT", "_cachedChanges", "_cachedChangesIncludeMetadataChanges", "__PRIVATE_querySnapshot", "oldDocs", "isEmpty", "index", "map", "__PRIVATE_change", "type", "oldIndex", "newIndex", "__PRIVATE_indexTracker", "filter", "indexOf", "delete", "add", "__PRIVATE_resultChangeType", "__PRIVATE_changesFromSnapshot", "fail", "getDoc", "reference", "__PRIVATE_cast", "DocumentReference", "firestore", "Firestore", "__PRIVATE_firestoreClientGetDocumentViaSnapshotListener", "ensureFirestoreConfigured", "_key", "then", "snapshot", "__PRIVATE_convertToDocSnapshot", "__PRIVATE_ExpUserDataWriter", "AbstractUserDataWriter", "constructor", "super", "this", "convertBytes", "bytes", "Bytes", "convertReference", "name", "key", "convertDocumentKey", "_databaseId", "getDocs", "query", "__PRIVATE_cast", "Query", "firestore", "Firestore", "__PRIVATE_client", "ensureFirestoreConfigured", "userDataWriter", "__PRIVATE_ExpUserDataWriter", "__PRIVATE_validateHasExplicitOrderByForLimitToLast", "_query", "__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener", "then", "snapshot", "QuerySnapshot", "setDoc", "reference", "data", "options", "__PRIVATE_cast", "DocumentReference", "firestore", "Firestore", "__PRIVATE_convertedValue", "__PRIVATE_applyFirestoreDataConverter", "converter", "executeWrite", "__PRIVATE_parseSetData", "__PRIVATE_newUserDataReader", "_key", "toMutation", "Precondition", "none", "deleteDoc", "reference", "executeWrite", "__PRIVATE_cast", "firestore", "Firestore", "__PRIVATE_DeleteMutation", "_key", "Precondition", "none", "executeWrite", "firestore", "mutations", "__PRIVATE_client", "deferred", "__PRIVATE_Deferred", "asyncQueue", "enqueueAndForget", "async", "__PRIVATE_syncEngineWrite", "__PRIVATE_getSyncEngine", "promise", "__PRIVATE_firestoreClientWrite", "ensureFirestoreConfigured", "__PRIVATE_convertToDocSnapshot", "ref", "snapshot", "doc", "docs", "get", "_key", "userDataWriter", "__PRIVATE_ExpUserDataWriter", "DocumentSnapshot", "SnapshotMetadata", "hasPendingWrites", "fromCache", "converter", "__PRIVATE_registerFirestore", "variant", "useFetchStreams", "version", "SDK_VERSION", "_registerComponent", "Component", "container", "instanceIdentifier", "databaseId", "options", "settings", "app", "getProvider", "getImmediate", "__PRIVATE_firestoreInstance", "Firestore", "__PRIVATE_FirebaseAuthCredentialsProvider", "__PRIVATE_FirebaseAppCheckTokenProvider", "database", "Object", "prototype", "hasOwnProperty", "apply", "FirestoreError", "Code", "INVALID_ARGUMENT", "DatabaseId", "projectId", "__PRIVATE_databaseIdFromApp", "assign", "_setSettings", "setMultipleInstances", "registerVersion", "name", "registerVersion", "name", "version", "firebase_default", "init", "firebase_default", "initializeApp", "__rest", "s", "p", "i", "_prodErrorMap", "prodErrorMap", "_prodErrorMap", "_DEFAULT_AUTH_ERROR_FACTORY", "ErrorFactory", "logClient", "Logger", "_logWarn", "msg", "args", "LogLevel", "SDK_VERSION", "_logError", "_fail", "authOrCode", "rest", "createErrorInternal", "_createError", "_errorWithCustomMessage", "auth", "code", "message", "errorMap", "prodErrorMap", "ErrorFactory", "_serverAppCurrentUserOperationNotSupportedError", "_assertInstanceOf", "object", "instance", "constructorInstance", "fullParams", "_DEFAULT_AUTH_ERROR_FACTORY", "_assert", "assertion", "debugFail", "failure", "debugAssert", "_getCurrentUrl", "_a", "_isHttpOrHttps", "_getCurrentScheme", "_isOnline", "isBrowserExtension", "_getUserLanguage", "navigatorLanguage", "Delay", "shortDelay", "longDelay", "isMobileCordova", "isReactNative", "_emulatorUrl", "config", "path", "url", "FetchProvider", "fetchImpl", "headersImpl", "responseImpl", "SERVER_ERROR_MAP", "DEFAULT_API_TIMEOUT_MS", "_addTidIfNecessary", "request", "_performApiRequest", "method", "customErrorMap", "_performFetchWithErrorHandling", "body", "params", "query", "querystring", "headers", "_getFinalTarget", "fetchFn", "networkTimeout", "NetworkTimeout", "response", "json", "_makeTaggedError", "errorMessage", "serverErrorCode", "serverErrorMessage", "authError", "e", "FirebaseError", "_performSignInRequest", "serverResponse", "host", "base", "_parseEnforcementState", "enforcementStateStr", "_", "reject", "errorParams", "error", "isEnterprise", "grecaptcha", "RecaptchaConfig", "response", "providerStr", "recaptchaEnforcementState", "_parseEnforcementState", "getRecaptchaConfig", "auth", "request", "_performApiRequest", "_addTidIfNecessary", "deleteAccount", "getAccountInfo", "auth", "request", "_performApiRequest", "utcTimestampToDateString", "utcTimestamp", "date", "getIdTokenResult", "user", "forceRefresh", "userInternal", "getModularInstance", "token", "claims", "_parseToken", "_assert", "firebase", "signInProvider", "utcTimestampToDateString", "secondsStringToMilliseconds", "seconds", "algorithm", "payload", "signature", "_logError", "decoded", "base64Decode", "e", "_tokenExpiresIn", "parsedToken", "_logoutIfInvalidated", "promise", "bypassAuthState", "FirebaseError", "isUserInvalidated", "code", "ProactiveRefresh", "wasError", "interval", "_a", "UserMetadata", "createdAt", "lastLoginAt", "metadata", "_reloadWithoutSaving", "auth", "idToken", "response", "getAccountInfo", "coreAccount", "newProviderData", "extractProviderData", "providerData", "mergeProviderData", "oldIsAnonymous", "newIsAnonymous", "isAnonymous", "updates", "reload", "original", "newData", "o", "n", "providers", "providerId", "provider", "__rest", "requestStsToken", "refreshToken", "_performFetchWithErrorHandling", "body", "querystring", "tokenApiHost", "apiKey", "url", "_getFinalTarget", "headers", "FetchProvider", "revokeToken", "request", "_performApiRequest", "_addTidIfNecessary", "StsTokenManager", "_StsTokenManager", "expiresIn", "oldToken", "accessToken", "expiresInSec", "appName", "object", "expirationTime", "manager", "stsTokenManager", "debugFail", "assertStringOrUndefined", "assertion", "UserImpl", "_UserImpl", "uid", "opt", "userInfo", "newUser", "callback", "tokensRefreshed", "_isFirebaseServerApp", "_serverAppCurrentUserOperationNotSupportedError", "deleteAccount", "displayName", "email", "_b", "phoneNumber", "_c", "photoURL", "_d", "tenantId", "_e", "_redirectEventId", "_f", "_g", "_h", "emailVerified", "plainObjectTokenManager", "idTokenResponse", "instanceCache", "_getInstance", "cls", "debugAssert", "instance", "InMemoryPersistence", "key", "value", "_key", "_listener", "inMemoryPersistence", "_persistenceKeyName", "PersistenceUserManager", "_PersistenceUserManager", "persistence", "userKey", "config", "name", "blob", "newPersistence", "currentUser", "persistenceHierarchy", "availablePersistences", "selectedPersistence", "userToMigrate", "migrationHierarchy", "p", "_getBrowserName", "userAgent", "ua", "_isIEMobile", "_isFirefox", "_isBlackBerry", "_isWebOS", "_isSafari", "_isChromeIOS", "_isAndroid", "re", "matches", "getUA", "_isIOS", "_isIOSStandalone", "ua", "getUA", "_isIOS", "_a", "_isIE10", "isIE", "_isMobileBrowser", "_isAndroid", "_isWebOS", "_isBlackBerry", "_isIEMobile", "_isIframe", "_getClientVersion", "clientPlatform", "frameworks", "reportedPlatform", "_getBrowserName", "reportedFrameworks", "SDK_VERSION", "AuthMiddlewareQueue", "auth", "callback", "onAbort", "wrappedCallback", "user", "resolve", "reject", "result", "e", "index", "nextUser", "onAbortStack", "beforeStateCallback", "_getPasswordPolicy", "request", "_performApiRequest", "_addTidIfNecessary", "MINIMUM_MIN_PASSWORD_LENGTH", "PasswordPolicyImpl", "response", "responseOptions", "_c", "_b", "_d", "password", "status", "_e", "_f", "minPasswordLength", "maxPasswordLength", "passwordChar", "i", "containsLowercaseCharacter", "containsUppercaseCharacter", "containsNumericCharacter", "containsNonAlphanumericCharacter", "AuthImpl", "app", "heartbeatServiceProvider", "appCheckServiceProvider", "config", "Subscription", "_DEFAULT_AUTH_ERROR_FACTORY", "persistenceHierarchy", "popupRedirectResolver", "_getInstance", "PersistenceUserManager", "idToken", "getAccountInfo", "UserImpl", "err", "_isFirebaseServerApp", "previouslyStoredUser", "futureCurrentUser", "needsTocheckMiddleware", "redirectUserEventId", "storedUserEventId", "_assert", "redirectResolver", "_reloadWithoutSaving", "_getUserLanguage", "userExtern", "_serverAppCurrentUserOperationNotSupportedError", "getModularInstance", "skipBeforeStateCallbacks", "persistence", "passwordPolicy", "errorMap", "ErrorFactory", "nextOrObserver", "error", "completed", "unsubscribe", "token", "revokeToken", "redirectManager", "resolver", "id", "currentUid", "subscription", "cb", "isUnsubscribed", "promise", "action", "framework", "headers", "heartbeatsHeader", "appCheckToken", "appCheckTokenResult", "_logWarn", "_castAuth", "createSubscribe", "observer", "externalJSProvider", "_setExternalJSProvider", "p", "_loadJS", "url", "_recaptchaEnterpriseScriptUrl", "externalJSProvider", "_gapiScriptUrl", "_generateCallbackName", "prefix", "RECAPTCHA_ENTERPRISE_VERIFIER_TYPE", "FAKE_TOKEN", "RecaptchaEnterpriseVerifier", "authExtern", "_castAuth", "action", "forceRefresh", "retrieveSiteKey", "auth", "resolve", "reject", "getRecaptchaConfig", "response", "config", "RecaptchaConfig", "error", "retrieveRecaptchaToken", "siteKey", "grecaptcha", "isEnterprise", "token", "url", "jsHelpers._recaptchaEnterpriseScriptUrl", "jsHelpers\r\n ._loadJS", "injectRecaptchaFields", "request", "captchaResp", "verifier", "captchaResponse", "newRequest", "handleRecaptchaFlow", "authInstance", "actionName", "actionMethod", "_a", "requestWithRecaptcha", "initializeAuth", "app", "deps", "provider", "_getProvider", "auth", "initialOptions", "deepEqual", "_fail", "_initializeAuthInstance", "persistence", "hierarchy", "_getInstance", "connectAuthEmulator", "url", "options", "authInternal", "_castAuth", "_assert", "disableWarnings", "protocol", "extractProtocol", "host", "port", "extractHostAndPort", "portStr", "emitEmulatorWarning", "protocolEnd", "authority", "hostAndPort", "bracketedIPv6", "parsePort", "attachBanner", "el", "sty", "AuthCredential", "providerId", "signInMethod", "debugFail", "_auth", "_idToken", "linkEmailPassword", "auth", "request", "_performApiRequest", "signInWithPassword", "auth", "request", "_performSignInRequest", "_addTidIfNecessary", "signInWithEmailLink", "auth", "request", "_performSignInRequest", "_addTidIfNecessary", "signInWithEmailLinkForLinking", "EmailAuthCredential", "_EmailAuthCredential", "AuthCredential", "_email", "_password", "signInMethod", "_tenantId", "email", "password", "oobCode", "tenantId", "json", "obj", "handleRecaptchaFlow", "signInWithPassword", "_fail", "idToken", "linkEmailPassword", "signInWithIdp", "IDP_REQUEST_URI", "OAuthCredential", "_OAuthCredential", "params", "cred", "providerId", "rest", "__rest", "postBody", "querystring", "sendPhoneVerificationCode", "_performApiRequest", "signInWithPhoneNumber", "linkWithPhoneNumber", "response", "_makeTaggedError", "VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_", "verifyPhoneNumberForExisting", "apiRequest", "PhoneAuthCredential", "_PhoneAuthCredential", "verificationId", "verificationCode", "phoneNumber", "temporaryProof", "parseMode", "mode", "parseDeepLink", "url", "link", "querystringDecode", "extractQuerystring", "doubleDeepLink", "iOSDeepLink", "ActionCodeURL", "_ActionCodeURL", "actionLink", "searchParams", "apiKey", "_a", "code", "_b", "operation", "_c", "_assert", "_d", "_e", "_f", "EmailAuthProvider", "_EmailAuthProvider", "email", "password", "EmailAuthCredential", "emailLink", "actionCodeUrl", "ActionCodeURL", "_assert", "FederatedAuthProvider", "providerId", "languageCode", "customOAuthParameters", "BaseOAuthProvider", "scope", "FacebookAuthProvider", "_FacebookAuthProvider", "BaseOAuthProvider", "accessToken", "OAuthCredential", "userCredential", "error", "tokenResponse", "GoogleAuthProvider", "_GoogleAuthProvider", "idToken", "oauthIdToken", "oauthAccessToken", "GithubAuthProvider", "_GithubAuthProvider", "TwitterAuthProvider", "_TwitterAuthProvider", "BaseOAuthProvider", "token", "secret", "OAuthCredential", "userCredential", "error", "tokenResponse", "oauthAccessToken", "oauthTokenSecret", "UserCredentialImpl", "_UserCredentialImpl", "params", "auth", "operationType", "idTokenResponse", "isAnonymous", "user", "UserImpl", "providerId", "providerIdForResponse", "response", "MultiFactorError", "_MultiFactorError", "FirebaseError", "auth", "error", "operationType", "user", "_a", "_processCredentialSavingMfaContextIfNecessary", "credential", "_link", "user", "credential", "bypassAuthState", "response", "_logoutIfInvalidated", "UserCredentialImpl", "_reauthenticate", "user", "credential", "bypassAuthState", "auth", "_isFirebaseServerApp", "_serverAppCurrentUserOperationNotSupportedError", "operationType", "response", "_logoutIfInvalidated", "_processCredentialSavingMfaContextIfNecessary", "_assert", "parsed", "_parseToken", "localId", "UserCredentialImpl", "e", "_fail", "_signInWithCredential", "userCredential", "onIdTokenChanged", "auth", "nextOrObserver", "error", "completed", "getModularInstance", "beforeAuthStateChanged", "callback", "onAbort", "onAuthStateChanged", "signOut", "auth", "getModularInstance", "startEnrollPhoneMfa", "auth", "request", "_performApiRequest", "_addTidIfNecessary", "finalizeEnrollPhoneMfa", "startEnrollTotpMfa", "finalizeEnrollTotpMfa", "STORAGE_AVAILABLE_KEY", "BrowserPersistenceClass", "storageRetriever", "type", "key", "value", "json", "_iframeCannotSyncWebStorage", "ua", "getUA", "_isSafari", "_isIOS", "_POLLING_INTERVAL_MS", "IE10_LOCAL_STORAGE_SYNC_DELAY", "BrowserLocalPersistence", "event", "poll", "_isIframe", "_isMobileBrowser", "cb", "newValue", "oldValue", "_oldValue", "storedValue", "triggerListeners", "_isIE10", "listeners", "listener", "browserLocalPersistence", "BrowserSessionPersistence", "_key", "_listener", "browserSessionPersistence", "_allSettled", "promises", "promise", "reason", "Receiver", "_Receiver", "eventTarget", "existingInstance", "receiver", "newInstance", "messageEvent", "eventId", "eventType", "data", "handlers", "handler", "response", "eventHandler", "_generateEventId", "prefix", "digits", "random", "i", "Sender", "target", "timeout", "messageChannel", "completionTimer", "resolve", "reject", "ackTimer", "_window", "_setWindowLocation", "url", "_isWorker", "_getActiveServiceWorker", "_getServiceWorkerController", "_a", "_getWorkerGlobalScope", "DB_NAME", "DB_VERSION", "DB_OBJECTSTORE_NAME", "DB_DATA_KEYPATH", "DBPromise", "request", "getObjectStore", "db", "isReadWrite", "_deleteDatabase", "_openDatabase", "e", "_putObject", "getObject", "_deleteObject", "_TRANSACTION_RETRY_COUNT", "IndexedDBLocalPersistence", "op", "numAttempts", "_origin", "_data", "results", "_b", "write", "obj", "result", "getAllRequest", "keys", "keysInResult", "localKey", "indexedDBLocalPersistence", "startSignInPhoneMfa", "auth", "_performApiRequest", "_addTidIfNecessary", "finalizeSignInPhoneMfa", "finalizeSignInTotpMfa", "_JSLOAD_CALLBACK", "jsHelpers._generateCallbackName", "NETWORK_TIMEOUT_DELAY", "Delay", "RECAPTCHA_VERIFIER_TYPE", "_verifyPhoneNumber", "auth", "options", "verifier", "recaptchaToken", "_assert", "RECAPTCHA_VERIFIER_TYPE", "phoneInfoOptions", "session", "startEnrollPhoneMfa", "mfaEnrollmentId", "_a", "startSignInPhoneMfa", "sessionInfo", "sendPhoneVerificationCode", "PhoneAuthProvider", "_PhoneAuthProvider", "auth", "_castAuth", "phoneOptions", "applicationVerifier", "_verifyPhoneNumber", "getModularInstance", "verificationId", "verificationCode", "PhoneAuthCredential", "userCredential", "credential", "error", "tokenResponse", "phoneNumber", "temporaryProof", "_withDefaultResolver", "resolverOverride", "_getInstance", "_assert", "IdpCredential", "AuthCredential", "params", "signInWithIdp", "idToken", "request", "_signIn", "_signInWithCredential", "_reauth", "user", "_reauthenticate", "_link", "_linkUser", "AbstractPopupRedirectOperation", "filter", "resolver", "bypassAuthState", "resolve", "reject", "e", "event", "urlResponse", "sessionId", "postBody", "tenantId", "type", "_fail", "cred", "debugAssert", "_POLL_WINDOW_CLOSE_TIMEOUT", "Delay", "PopupOperation", "_PopupOperation", "AbstractPopupRedirectOperation", "auth", "filter", "provider", "resolver", "user", "result", "_assert", "debugAssert", "eventId", "_generateEventId", "e", "isSupported", "_createError", "_a", "poll", "_b", "_POLL_WINDOW_CLOSE_TIMEOUT", "PENDING_REDIRECT_KEY", "redirectOutcomeMap", "RedirectAction", "bypassAuthState", "readyOutcome", "_getAndClearPendingRedirectStatus", "event", "key", "pendingRedirectKey", "persistence", "resolverPersistence", "hasPendingRedirect", "_setPendingRedirectStatus", "_overrideRedirectResult", "auth", "result", "redirectOutcomeMap", "resolverPersistence", "resolver", "_getInstance", "pendingRedirectKey", "_persistenceKeyName", "PENDING_REDIRECT_KEY", "signInWithRedirect", "provider", "_signInWithRedirect", "_isFirebaseServerApp", "_serverAppCurrentUserOperationNotSupportedError", "authInternal", "_castAuth", "_assertInstanceOf", "FederatedAuthProvider", "resolverInternal", "_withDefaultResolver", "_setPendingRedirectStatus", "_getRedirectResult", "auth", "resolverExtern", "bypassAuthState", "_isFirebaseServerApp", "_serverAppCurrentUserOperationNotSupportedError", "authInternal", "_castAuth", "resolver", "_withDefaultResolver", "result", "RedirectAction", "EVENT_DUPLICATION_CACHE_DURATION_MS", "AuthEventManager", "auth", "authEventConsumer", "event", "handled", "consumer", "isRedirectEvent", "isNullRedirectEvent", "code", "_a", "_createError", "eventIdMatches", "eventUid", "e", "v", "type", "error", "_getProjectConfig", "request", "_performApiRequest", "IP_ADDRESS_REGEX", "HTTP_REGEX", "_validateOrigin", "authorizedDomains", "domain", "matchDomain", "_fail", "expected", "currentUrl", "_getCurrentUrl", "protocol", "hostname", "ceUrl", "escapedDomainPattern", "NETWORK_TIMEOUT", "Delay", "resetUnloadedGapiModules", "beacon", "_window", "hint", "i", "loadGapi", "resolve", "reject", "loadGapiIframe", "_b", "_c", "cbName", "js._generateCallbackName", "js\r\n ._loadJS", "js._gapiScriptUrl", "cachedGApiLoader", "_loadGapi", "PING_TIMEOUT", "IFRAME_PATH", "EMULATED_IFRAME_PATH", "IFRAME_ATTRIBUTES", "EID_FROM_APIHOST", "getIframeUrl", "config", "_assert", "url", "_emulatorUrl", "params", "SDK_VERSION", "eid", "frameworks", "querystring", "_openIframe", "context", "gapiLoader._loadGapi", "gapi", "iframe", "networkError", "networkErrorTimer", "clearTimerAndResolve", "BASE_POPUP_OPTIONS", "DEFAULT_WIDTH", "DEFAULT_HEIGHT", "TARGET_BLANK", "FIREFOX_EMPTY_URL", "AuthPopup", "window", "_open", "name", "width", "height", "top", "left", "target", "options", "ua", "getUA", "_isChromeIOS", "_isFirefox", "optionsString", "accum", "key", "value", "_isIOSStandalone", "openAsNewWindowIOS", "newWin", "el", "click", "WIDGET_PATH", "EMULATOR_WIDGET_PATH", "FIREBASE_APP_CHECK_FRAGMENT_ID", "_getRedirectUrl", "provider", "authType", "redirectUrl", "eventId", "additionalParams", "FederatedAuthProvider", "isEmpty", "BaseOAuthProvider", "scopes", "scope", "paramsDict", "appCheckToken", "appCheckTokenFragment", "getHandlerBase", "WEB_STORAGE_SUPPORT_KEY", "BrowserPopupRedirectResolver", "browserSessionPersistence", "_getRedirectResult", "_overrideRedirectResult", "debugAssert", "_generateEventId", "_setWindowLocation", "manager", "promise", "iframeEvent", "cb", "result", "isSupported", "_isMobileBrowser", "_isSafari", "_isIOS", "browserPopupRedirectResolver", "MultiFactorAssertionImpl", "factorId", "session", "displayName", "debugFail", "PhoneMultiFactorAssertionImpl", "_PhoneMultiFactorAssertionImpl", "credential", "idToken", "finalizeEnrollPhoneMfa", "mfaPendingCredential", "finalizeSignInPhoneMfa", "PhoneMultiFactorGenerator", "TotpMultiFactorGenerator", "secret", "oneTimePassword", "TotpMultiFactorAssertionImpl", "enrollmentId", "mfaSession", "response", "startEnrollTotpMfa", "TotpSecret", "_TotpMultiFactorAssertionImpl", "otp", "finalizeEnrollTotpMfa", "totpVerificationInfo", "finalizeSignInTotpMfa", "_TotpSecret", "secretKey", "hashingAlgorithm", "codeLength", "codeIntervalSeconds", "enrollmentCompletionDeadline", "sessionInfo", "accountName", "issuer", "useDefaults", "_isEmptyString", "input", "AuthInterop", "forceRefresh", "listener", "unsubscribe", "user", "getVersionForPlatform", "clientPlatform", "registerAuth", "_registerComponent", "Component", "container", "deps", "app", "heartbeatServiceProvider", "appCheckServiceProvider", "apiKey", "authDomain", "_getClientVersion", "authInstance", "AuthImpl", "_initializeAuthInstance", "_instanceIdentifier", "_instance", "_castAuth", "registerVersion", "version", "DEFAULT_ID_TOKEN_MAX_AGE", "authIdTokenMaxAge", "getExperimentalSetting", "lastPostedIdToken", "mintCookieFactory", "idTokenResult", "idTokenAge", "getAuth", "getApp", "_getProvider", "initializeAuth", "indexedDBLocalPersistence", "browserLocalPersistence", "authTokenSyncPath", "authTokenSyncUrl", "mintCookie", "beforeAuthStateChanged", "onIdTokenChanged", "authEmulatorHost", "getDefaultEmulatorHost", "connectAuthEmulator", "getScriptParentElement", "_setExternalJSProvider", "isAuthConfigured", "currentUser", "emitter", "getUser", "isAuthed", "handleError", "error", "method", "errorCode", "errorMessage", "message", "signIn", "auth", "getAuth", "provider", "GoogleAuthProvider", "signInWithRedirect", "monitorAuth", "em", "init", "onAuthStateChanged", "user", "signOut", "getUserId", "user", "getUser", "getRefForKey", "userId", "key", "db", "getFirestore", "doc", "getRefForCollection", "collection", "get", "docRef", "docSnap", "getDoc", "err", "set", "char_obj", "setDoc", "getAll", "getDocs", "remove", "deleteDoc", "Database_default", "Tabs", "tablist", "tab", "paneId", "newIndex", "el", "oldTab", "ev", "oldIndex", "newTab", "oldPane", "newPane", "Tabs_default", "template", "SheetView", "emitter", "templateNode", "Tabs_default", "el", "character", "targetPane", "fieldName", "subFieldName", "charValue", "f", "subf", "event", "listItems", "item", "noteItems", "rowItems", "valold", "valnew", "ev", "field", "subfield", "cur_character", "newValue", "currentVal", "id", "SheetView_default", "template", "Character5eSheet", "SheetView_default", "emitter", "nav", "el", "f", "subf", "listItems", "item", "character", "Character5e", "fieldName", "subFieldName", "charValue", "ev", "field", "subfield", "currentVal", "newValue", "object", "Weapon", "skill", "modifier", "proficiency", "attr", "attribute", "spellList", "Character5eSheet_default", "template", "CharacterVagabondsSheet", "SheetView_default", "emitter", "nav", "character", "CharacterVagabonds", "CharacterVagabondsSheet_default", "version", "cur_character", "appVersion", "version", "currentTimestamp", "generateCharacterKey", "key", "getCharacter", "getGameOptions", "characterFactory", "type", "obj", "Character5e", "CharacterVagabonds", "Character", "newCharacter", "char_obj", "Storage_default", "getCharacterRemote", "Database_default", "saveCharacter", "character", "saveCharacterRemote", "removeCharacterLocal", "removeCharacterRemote", "getAllCharactersLocal", "characters", "getAllCharactersRemote", "isAuthed", "char", "importCharacter", "existingCharacter", "temp_key", "setLocalStoragePrefix", "prefix", "setCurrentCharacter", "createOnEmpty", "getCurrentCharacter", "getCurrentCharacterKey", "saveCurrentCharacter", "getSheetView", "emitter", "view", "Character5eSheet_default", "CharacterVagabondsSheet_default", "SheetView_default", "ShortCutKeys", "emitter", "keys", "event", "key", "withControl", "withShift", "code", "ev", "ShortCutKeys_default", "Manager", "char_type", "key", "generateCharacterKey", "err", "urlhash", "cur_character_key", "getCurrentCharacterKey", "cur_character", "setCurrentCharacter", "sheetView", "getSheetView", "event", "saveCurrentCharacter", "e", "form", "data", "names", "ch", "character", "getCharacter", "format", "date", "body", "url", "a", "file", "input_file", "input", "f", "reader", "start", "end", "check", "backups", "imported_chars", "reloadCurrentChar", "currentCharKey", "char_obj", "newCharacter", "importCharacter", "li", "ul", "error", "timeoutIndicator", "removeCharacterLocal", "ev", "template", "emitter", "prefix", "appname", "setLocalStoragePrefix", "monitorAuth", "shortCuts", "ShortCutKeys_default", "div", "getAllCharactersLocal", "Manager_default", "template", "ConfirmButton", "slotted", "value", "newValue", "func", "ev", "ConfirmButton_default", "compareLocalToRemote", "local", "remote", "lUpdated", "rUpdated", "getCharacterMatchings", "localCharacters", "getAllCharactersLocal", "remoteCharacters", "getAllCharactersRemote", "matches", "match", "uploadCharacter", "key", "char", "getCharacter", "getCharacterRemote", "saveCharacterRemote", "downloadCharacter", "saveCharacter", "deleteRemote", "removeCharacterRemote", "deleteLocal", "removeCharacterLocal", "syncToRemote", "syncToLocal", "template", "SyncInfo", "message", "ev", "button", "action", "uploadCharacter", "err", "deleteRemote", "downloadCharacter", "deleteLocal", "syncToRemote", "syncToLocal", "label", "key", "local", "remote", "latest", "charName", "SyncInfo_default", "ActionButton", "el", "menu", "ev", "forward", "template", "buttonActions", "ActionMenu", "buttons", "btn", "emitter", "target", "button", "action", "isAuthed", "signOut", "signIn", "currentCharKey", "getCurrentCharacterKey", "getCharacterMatchings", "matches", "frag", "match", "info", "SyncInfo_default", "error", "form", "checkboxes", "getAllCharactersLocal", "char", "li", "data", "p", "text", "url", "a", "currentlyUnsaved", "unsavedDialog", "content", "alert", "select", "getGameOptions", "char_type", "option", "formData", "charKey", "list", "cButton", "ConfirmButton_default", "modal", "items", "authbutton", "b", "currentBtn", "newIndex", "template", "NoteListItem", "CharacterNote", "note", "a", "onContent", "NoteListItem_default", "setCursorAtContentEnd", "el", "theNodes", "contentRange", "windowSelection", "setCursorAtContentEnd_default", "template", "NoteList", "prop", "value", "items", "array", "item", "content", "note", "NoteListItem_default", "a", "ev", "el", "newList", "nextList", "prevItem", "setCursorAtContentEnd_default", "detail", "template", "SimpleList", "prop", "value", "items", "array", "item", "content", "a", "ev", "el", "nextItem", "prevItem", "setCursorAtContentEnd_default", "detail", "template", "TableEditable", "headRow", "name", "th", "prop", "value", "entries", "row", "cells", "rowData", "isEmpty", "cell", "i", "key", "text", "content", "newCell", "a", "ev", "el", "td", "nextCell", "nextRow", "prevCell", "setCursorAtContentEnd_default", "prevRow", "delRow", "detail", "template", "SkillListing", "val", "mod", "ev", "expert", "detail", "roller", "die", "template", "AttributeListing", "val", "mod", "ev", "detail", "roller", "die", "randomInteger", "min", "max", "DiceResult", "die", "value", "DiceRoller", "randomInteger", "rolls", "diemod", "m", "count", "a", "b", "number", "modifier", "mod_op", "i", "sum", "total", "cur", "string", "getDiceResult", "die", "roller", "DiceRoller", "DiceResult", "Dragger", "dragElement", "handleSelector", "ev", "dragHandle", "template", "Die", "Dragger", "x1", "y1", "x", "y", "randomInteger", "prop", "value", "Die_default", "template", "DiceRoller", "buttons", "prop", "value", "ev", "die", "roll", "getDiceResult", "Die_default", "diceResult", "index", "d", "dieEl", "template", "EditableField", "prop", "value", "val", "ev", "currentVal", "detail", "template", "FooterNav", "ev", "link", "targetPane", "sheetView", "target_id", "links", "li", "a", "el", "template", "Modal", "html", "button", "node", "assigned", "element", "keyboardOnly", "tagName", "disabled", "tabIndex", "contentEditable", "single", "focusables", "children", "child", "childFocusables", "focusable", "ev", "a", "currentEl", "content", "includeCloseButton", "f", "el", "e_SRD_Spells_default", "template", "SpellItem", "#setupElements", "#loadData", "#populateSpellItem", "#setupEventListeners", "#removeEventListeners", "getCurrentCharacter", "e_SRD_Spells_default", "spell", "#setElementContent", "selector", "content", "#updateAddedIndicator", "ev", "level", "panelStyle", "template", "AddSpellButton", "ev", "modal", "content", "list", "spellLevel", "e_SRD_Spells_default", "spell", "spellItem", "error", "item", "emitter", "EventEmitter", "Manager_default"] } diff --git a/dist/service_worker.js b/dist/service_worker.js index cba2141..f4be3fb 100644 --- a/dist/service_worker.js +++ b/dist/service_worker.js @@ -1,2 +1,2 @@ -(()=>{var c="4.5.2";var r={cacheName:c,staticCacheItems:["/index.html","/index.js","/styles.css","/"]};self.addEventListener("install",e=>{function s(){return caches.open(r.cacheName).then(t=>t.addAll(r.staticCacheItems))}e.waitUntil(s(e).then(()=>self.skipWaiting()))});self.addEventListener("activate",function(e){let s=[r.cacheName];e.waitUntil(caches.keys().then(function(t){return Promise.all(t.map(function(i){if(s.indexOf(i)===-1)return caches.delete(i)}))}).then(()=>self.clients.claim()))});self.addEventListener("fetch",e=>{if(e.request.method==="POST"){fetch(e.request);return}e.respondWith(caches.match(e.request).then(function(s){return s||fetch(e.request).then(function(t){return caches.open(r.cacheName).then(function(i){return i.put(e.request,t.clone()),t})})}).catch(function(s){console.log("Service worker fetch failed.")}))});})(); +(()=>{var c="4.5.3";var r={cacheName:c,staticCacheItems:["/index.html","/index.js","/styles.css","/"]};self.addEventListener("install",e=>{function s(){return caches.open(r.cacheName).then(t=>t.addAll(r.staticCacheItems))}e.waitUntil(s(e).then(()=>self.skipWaiting()))});self.addEventListener("activate",function(e){let s=[r.cacheName];e.waitUntil(caches.keys().then(function(t){return Promise.all(t.map(function(i){if(s.indexOf(i)===-1)return caches.delete(i)}))}).then(()=>self.clients.claim()))});self.addEventListener("fetch",e=>{if(e.request.method==="POST"){fetch(e.request);return}e.respondWith(caches.match(e.request).then(function(s){return s||fetch(e.request).then(function(t){return caches.open(r.cacheName).then(function(i){return i.put(e.request,t.clone()),t})})}).catch(function(s){console.log("Service worker fetch failed.")}))});})(); //# sourceMappingURL=service_worker.js.map diff --git a/dist/service_worker.js.map b/dist/service_worker.js.map index d76e647..d48520b 100644 --- a/dist/service_worker.js.map +++ b/dist/service_worker.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../package.json", "../src/service_worker.js"], - "sourcesContent": ["{\n \"name\": \"character-sheet-app\",\n \"version\": \"4.5.2\",\n \"description\": \"Online character sheet for Tabletop Role-Playing Games\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/derikb/character-sheet-app.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/derikb/character-sheet-app/issues\"\n },\n \"homepage\": \"https://github.com/derikb/character-sheet-app#readme\",\n \"keywords\": [\n \"d&d\",\n \"rpg\",\n \"ttrpg\",\n \"character sheet\"\n ],\n \"author\": \"Derik A Badman\",\n \"license\": \"GPL-3.0\",\n \"dependencies\": {\n \"firebase\": \"^10.1.0\",\n \"rpg-table-randomizer\": \"^1.3.2\"\n },\n \"devDependencies\": {\n \"@stylistic/eslint-plugin-js\": \"^2.1.0\",\n \"commit-and-tag-version\": \"^12.0.0\",\n \"esbuild\": \"^0.21\",\n \"eslint\": \"^9.4.0\",\n \"globals\": \"^15.3.0\",\n \"normalize.css\": \"^8.0.1\"\n },\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"start\": \"esbuild --serve=8080 --servedir=./dist ./src/styles.css ./src/index.js ./src/service_worker.js --outdir=./dist --loader:.svg=dataurl --loader:.html=file --bundle\",\n \"build\": \"esbuild ./src/styles.css ./src/index.js ./src/service_worker.js --outdir=./dist --loader:.svg=dataurl --loader:.html=file --minify --sourcemap --bundle\",\n \"release\": \"commit-and-tag-version -a\",\n \"eslint\": \"eslint ./src\"\n },\n \"commit-and-tag-version\": {\n \"scripts\": {\n \"postbump\": \"npm run build && git add ./dist/service_worker.js ./dist/service_worker.js.map ./dist/index.js ./dist/index.js.map ./dist/styles.css ./dist/styles.css.map\"\n },\n \"bumpFiles\": [\n \"package.json\",\n \"package-lock.json\"\n ]\n }\n}\n", "/**\n * Service worker for character sheet app\n */\nimport { version } from '../package.json';\n/**\n * Config data\n * Update cacheName when we want to make sure to get new data in the cache\n * Caching all the files we use except the service worker itself\n */\nconst config = {\n cacheName: version,\n staticCacheItems: [\n '/index.html',\n '/index.js',\n '/styles.css',\n '/'\n ]\n};\n\n/**\n * Event: install\n * precaches all the files we use in the app\n */\nself.addEventListener('install', (e) => {\n function onInstall () {\n return caches.open(config.cacheName)\n .then(cache => cache.addAll(config.staticCacheItems));\n }\n e.waitUntil(\n onInstall(e)\n .then(() => self.skipWaiting())\n );\n});\n/**\n * Event: activate\n * This clears out any old caches\n */\nself.addEventListener('activate', function (event) {\n const cacheWhitelist = [config.cacheName];\n\n event.waitUntil(\n caches.keys().then(function (cacheNames) {\n return Promise.all(\n cacheNames.map(function (cacheName) {\n if (cacheWhitelist.indexOf(cacheName) === -1) {\n return caches.delete(cacheName);\n }\n return undefined;\n })\n );\n })\n .then(() => self.clients.claim())\n );\n});\n/**\n * Event: fetch\n * Just fetches from the cache if it can, since the whole app is static\n * @param {FetchEvent} event\n */\nself.addEventListener('fetch', (event) => {\n // Ignore POSTs (mostly to external DBs, etc.)\n if (event.request.method === 'POST') {\n fetch(event.request);\n return;\n }\n event.respondWith(\n caches.match(event.request)\n .then(function (resp) {\n return resp || fetch(event.request)\n .then(function (response) {\n return caches.open(config.cacheName)\n .then(function (cache) {\n cache.put(event.request, response.clone());\n return response;\n });\n });\n }).catch(function (e) {\n console.log('Service worker fetch failed.');\n })\n );\n});\n"], + "sourcesContent": ["{\n \"name\": \"character-sheet-app\",\n \"version\": \"4.5.3\",\n \"description\": \"Online character sheet for Tabletop Role-Playing Games\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/derikb/character-sheet-app.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/derikb/character-sheet-app/issues\"\n },\n \"homepage\": \"https://github.com/derikb/character-sheet-app#readme\",\n \"keywords\": [\n \"d&d\",\n \"rpg\",\n \"ttrpg\",\n \"character sheet\"\n ],\n \"author\": \"Derik A Badman\",\n \"license\": \"GPL-3.0\",\n \"dependencies\": {\n \"firebase\": \"^10.1.0\",\n \"rpg-table-randomizer\": \"^1.3.2\"\n },\n \"devDependencies\": {\n \"@stylistic/eslint-plugin-js\": \"^2.1.0\",\n \"commit-and-tag-version\": \"^12.0.0\",\n \"esbuild\": \"^0.21\",\n \"eslint\": \"^9.4.0\",\n \"globals\": \"^15.3.0\",\n \"normalize.css\": \"^8.0.1\"\n },\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"start\": \"esbuild --serve=8080 --servedir=./dist ./src/styles.css ./src/index.js ./src/service_worker.js --outdir=./dist --loader:.svg=dataurl --loader:.html=file --bundle\",\n \"build\": \"esbuild ./src/styles.css ./src/index.js ./src/service_worker.js --outdir=./dist --loader:.svg=dataurl --loader:.html=file --minify --sourcemap --bundle\",\n \"release\": \"commit-and-tag-version -a\",\n \"eslint\": \"eslint ./src\"\n },\n \"commit-and-tag-version\": {\n \"scripts\": {\n \"postbump\": \"npm run build && git add ./dist/service_worker.js ./dist/service_worker.js.map ./dist/index.js ./dist/index.js.map ./dist/styles.css ./dist/styles.css.map\"\n },\n \"bumpFiles\": [\n \"package.json\",\n \"package-lock.json\"\n ]\n }\n}\n", "/**\n * Service worker for character sheet app\n */\nimport { version } from '../package.json';\n/**\n * Config data\n * Update cacheName when we want to make sure to get new data in the cache\n * Caching all the files we use except the service worker itself\n */\nconst config = {\n cacheName: version,\n staticCacheItems: [\n '/index.html',\n '/index.js',\n '/styles.css',\n '/'\n ]\n};\n\n/**\n * Event: install\n * precaches all the files we use in the app\n */\nself.addEventListener('install', (e) => {\n function onInstall () {\n return caches.open(config.cacheName)\n .then(cache => cache.addAll(config.staticCacheItems));\n }\n e.waitUntil(\n onInstall(e)\n .then(() => self.skipWaiting())\n );\n});\n/**\n * Event: activate\n * This clears out any old caches\n */\nself.addEventListener('activate', function (event) {\n const cacheWhitelist = [config.cacheName];\n\n event.waitUntil(\n caches.keys().then(function (cacheNames) {\n return Promise.all(\n cacheNames.map(function (cacheName) {\n if (cacheWhitelist.indexOf(cacheName) === -1) {\n return caches.delete(cacheName);\n }\n return undefined;\n })\n );\n })\n .then(() => self.clients.claim())\n );\n});\n/**\n * Event: fetch\n * Just fetches from the cache if it can, since the whole app is static\n * @param {FetchEvent} event\n */\nself.addEventListener('fetch', (event) => {\n // Ignore POSTs (mostly to external DBs, etc.)\n if (event.request.method === 'POST') {\n fetch(event.request);\n return;\n }\n event.respondWith(\n caches.match(event.request)\n .then(function (resp) {\n return resp || fetch(event.request)\n .then(function (response) {\n return caches.open(config.cacheName)\n .then(function (cache) {\n cache.put(event.request, response.clone());\n return response;\n });\n });\n }).catch(function (e) {\n console.log('Service worker fetch failed.');\n })\n );\n});\n"], "mappings": "MAEE,IAAAA,EAAW,QCOb,IAAMC,EAAS,CACX,UAAWC,EACX,iBAAkB,CACd,cACA,YACA,cACA,GACJ,CACJ,EAMA,KAAK,iBAAiB,UAAY,GAAM,CACpC,SAASC,GAAa,CAClB,OAAO,OAAO,KAAKF,EAAO,SAAS,EAC9B,KAAKG,GAASA,EAAM,OAAOH,EAAO,gBAAgB,CAAC,CAC5D,CACA,EAAE,UACEE,EAAU,CAAC,EACN,KAAK,IAAM,KAAK,YAAY,CAAC,CACtC,CACJ,CAAC,EAKD,KAAK,iBAAiB,WAAY,SAAUE,EAAO,CAC/C,IAAMC,EAAiB,CAACL,EAAO,SAAS,EAExCI,EAAM,UACF,OAAO,KAAK,EAAE,KAAK,SAAUE,EAAY,CACrC,OAAO,QAAQ,IACXA,EAAW,IAAI,SAAUC,EAAW,CAChC,GAAIF,EAAe,QAAQE,CAAS,IAAM,GACtC,OAAO,OAAO,OAAOA,CAAS,CAGtC,CAAC,CACL,CACJ,CAAC,EACI,KAAK,IAAM,KAAK,QAAQ,MAAM,CAAC,CACxC,CACJ,CAAC,EAMD,KAAK,iBAAiB,QAAUH,GAAU,CAEtC,GAAIA,EAAM,QAAQ,SAAW,OAAQ,CACjC,MAAMA,EAAM,OAAO,EACnB,MACJ,CACAA,EAAM,YACF,OAAO,MAAMA,EAAM,OAAO,EACrB,KAAK,SAAUI,EAAM,CAClB,OAAOA,GAAQ,MAAMJ,EAAM,OAAO,EAC7B,KAAK,SAAUK,EAAU,CACtB,OAAO,OAAO,KAAKT,EAAO,SAAS,EAC9B,KAAK,SAAUG,EAAO,CACnB,OAAAA,EAAM,IAAIC,EAAM,QAASK,EAAS,MAAM,CAAC,EAClCA,CACX,CAAC,CACT,CAAC,CACT,CAAC,EAAE,MAAM,SAAUC,EAAG,CAClB,QAAQ,IAAI,8BAA8B,CAC9C,CAAC,CACT,CACJ,CAAC", "names": ["version", "config", "version", "onInstall", "cache", "event", "cacheWhitelist", "cacheNames", "cacheName", "resp", "response", "e"] } diff --git a/package-lock.json b/package-lock.json index 4830890..f4e3154 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "character-sheet-app", - "version": "4.5.2", + "version": "4.5.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "character-sheet-app", - "version": "4.5.2", + "version": "4.5.3", "license": "GPL-3.0", "dependencies": { "firebase": "^10.1.0", @@ -26,6 +26,7 @@ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-2.0.2.tgz", "integrity": "sha512-x1KXOatwofR6ZAYzXRBL5wrdV0vwNxlTCK9NCuLqAzQYARqGcvFwiJA6A1ERuh+dgeA4Dxm3JBYictIes+SqUQ==", "dev": true, + "license": "MIT", "dependencies": { "bidi-js": "^1.0.3", "css-tree": "^2.3.1", @@ -37,6 +38,7 @@ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", "dev": true, + "license": "MIT", "dependencies": { "@babel/highlight": "^7.24.7", "picocolors": "^1.0.0" @@ -50,6 +52,7 @@ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -59,6 +62,7 @@ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-validator-identifier": "^7.24.7", "chalk": "^2.4.2", @@ -77,6 +81,7 @@ "ppc64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "aix" @@ -93,6 +98,7 @@ "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" @@ -109,6 +115,7 @@ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" @@ -125,6 +132,7 @@ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" @@ -141,6 +149,7 @@ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" @@ -157,6 +166,7 @@ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" @@ -173,6 +183,7 @@ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "freebsd" @@ -189,6 +200,7 @@ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "freebsd" @@ -205,6 +217,7 @@ "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -221,6 +234,7 @@ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -237,6 +251,7 @@ "ia32" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -253,6 +268,7 @@ "loong64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -269,6 +285,7 @@ "mips64el" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -285,6 +302,7 @@ "ppc64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -301,6 +319,7 @@ "riscv64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -317,6 +336,7 @@ "s390x" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -333,6 +353,7 @@ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" @@ -349,6 +370,7 @@ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "netbsd" @@ -365,6 +387,7 @@ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "openbsd" @@ -381,6 +404,7 @@ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "sunos" @@ -397,6 +421,7 @@ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" @@ -413,6 +438,7 @@ "ia32" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" @@ -429,6 +455,7 @@ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" @@ -442,6 +469,7 @@ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", "dev": true, + "license": "MIT", "dependencies": { "eslint-visitor-keys": "^3.3.0" }, @@ -457,6 +485,7 @@ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true, + "license": "Apache-2.0", "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, @@ -465,23 +494,25 @@ } }, "node_modules/@eslint-community/regexpp": { - "version": "4.10.1", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.10.1.tgz", - "integrity": "sha512-Zm2NGpWELsQAD1xsJzGQpYfvICSsFkEpU0jxBjfdC6uNEWXcHnfs9hScFWtXVDVl+rBQJGrl4g1vcKIejpH9dA==", + "version": "4.11.0", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.11.0.tgz", + "integrity": "sha512-G/M/tIiMrTAxEWRfLfQJMmGNX28IxBg4PBz8XqQhqUHLFI6TL2htpIB1iQCj144V5ee/JaKyT9/WZ0MGZWfA7A==", "dev": true, + "license": "MIT", "engines": { "node": "^12.0.0 || ^14.0.0 || >=16.0.0" } }, "node_modules/@eslint/config-array": { - "version": "0.16.0", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.16.0.tgz", - "integrity": "sha512-/jmuSd74i4Czf1XXn7wGRWZCuyaUZ330NH1Bek0Pplatt4Sy1S5haN21SCLLdbeKslQ+S0wEJ+++v5YibSi+Lg==", + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.17.0.tgz", + "integrity": "sha512-A68TBu6/1mHHuc5YJL0U0VVeGNiklLAL6rRmhTCP2B5XjWLMnrX+HkO+IAXyHvks5cyyY1jjK5ITPQ1HGS2EVA==", "dev": true, + "license": "Apache-2.0", "dependencies": { "@eslint/object-schema": "^2.1.4", "debug": "^4.3.1", - "minimatch": "^3.0.5" + "minimatch": "^3.1.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -492,6 +523,7 @@ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.1.0.tgz", "integrity": "sha512-4Bfj15dVJdoy3RfZmmo86RK1Fwzn6SstsvK9JS+BaVKqC6QQQQyXekNaC+g+LKNgkQ+2VhGAzm6hO40AhMR3zQ==", "dev": true, + "license": "MIT", "dependencies": { "ajv": "^6.12.4", "debug": "^4.3.2", @@ -515,6 +547,7 @@ "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -523,10 +556,11 @@ } }, "node_modules/@eslint/js": { - "version": "9.5.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.5.0.tgz", - "integrity": "sha512-A7+AOT2ICkodvtsWnxZP4Xxk3NbZ3VMHd8oihydLRGrJgqqdEz1qSeEgXYyT/Cu8h1TWWsQRejIx48mtjZ5y1w==", + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.6.0.tgz", + "integrity": "sha512-D9B0/3vNg44ZeWbYMpBoXqNP4j6eQD5vNwIlGAuFRRzK/WtT/jvDQW3Bi9kkf3PMDMlM7Yi+73VLUsn5bJcl8A==", "dev": true, + "license": "MIT", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } @@ -536,6 +570,7 @@ "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.4.tgz", "integrity": "sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==", "dev": true, + "license": "Apache-2.0", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } @@ -544,6 +579,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", + "license": "MIT", "engines": { "node": ">=14" } @@ -552,6 +588,7 @@ "version": "0.10.4", "resolved": "https://registry.npmjs.org/@firebase/analytics/-/analytics-0.10.4.tgz", "integrity": "sha512-OJEl/8Oye/k+vJ1zV/1L6eGpc1XzAj+WG2TPznJ7PszL7sOFLBXkL9IjHfOCGDGpXeO3btozy/cYUqv4zgNeHg==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/installations": "0.6.7", @@ -567,6 +604,7 @@ "version": "0.2.10", "resolved": "https://registry.npmjs.org/@firebase/analytics-compat/-/analytics-compat-0.2.10.tgz", "integrity": "sha512-ia68RcLQLLMFWrM10JfmFod7eJGwqr4/uyrtzHpTDnxGX/6gNCBTOuxdAbyWIqXI5XmcMQdz9hDijGKOHgDfPw==", + "license": "Apache-2.0", "dependencies": { "@firebase/analytics": "0.10.4", "@firebase/analytics-types": "0.8.2", @@ -581,12 +619,14 @@ "node_modules/@firebase/analytics-types": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/@firebase/analytics-types/-/analytics-types-0.8.2.tgz", - "integrity": "sha512-EnzNNLh+9/sJsimsA/FGqzakmrAUKLeJvjRHlg8df1f97NLUlFidk9600y0ZgWOp3CAxn6Hjtk+08tixlUOWyw==" + "integrity": "sha512-EnzNNLh+9/sJsimsA/FGqzakmrAUKLeJvjRHlg8df1f97NLUlFidk9600y0ZgWOp3CAxn6Hjtk+08tixlUOWyw==", + "license": "Apache-2.0" }, "node_modules/@firebase/app": { "version": "0.10.5", "resolved": "https://registry.npmjs.org/@firebase/app/-/app-0.10.5.tgz", "integrity": "sha512-iY/fNot+hWPk9sTX8aHMqlcX9ynRvpGkskWAdUZ2eQQdLo8d1hSFYcYNwPv0Q/frGMasw8udKWMcFOEpC9fG8g==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/logger": "0.4.2", @@ -599,6 +639,7 @@ "version": "0.8.4", "resolved": "https://registry.npmjs.org/@firebase/app-check/-/app-check-0.8.4.tgz", "integrity": "sha512-2tjRDaxcM5G7BEpytiDcIl+NovV99q8yEqRMKDbn4J4i/XjjuThuB4S+4PkmTnZiCbdLXQiBhkVxNlUDcfog5Q==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/logger": "0.4.2", @@ -613,6 +654,7 @@ "version": "0.3.11", "resolved": "https://registry.npmjs.org/@firebase/app-check-compat/-/app-check-compat-0.3.11.tgz", "integrity": "sha512-t01zaH3RJpKEey0nGduz3Is+uSz7Sj4U5nwOV6lWb+86s5xtxpIvBJzu/lKxJfYyfZ29eJwpdjEgT1/lm4iQyA==", + "license": "Apache-2.0", "dependencies": { "@firebase/app-check": "0.8.4", "@firebase/app-check-types": "0.5.2", @@ -628,17 +670,20 @@ "node_modules/@firebase/app-check-interop-types": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@firebase/app-check-interop-types/-/app-check-interop-types-0.3.2.tgz", - "integrity": "sha512-LMs47Vinv2HBMZi49C09dJxp0QT5LwDzFaVGf/+ITHe3BlIhUiLNttkATSXplc89A2lAaeTqjgqVkiRfUGyQiQ==" + "integrity": "sha512-LMs47Vinv2HBMZi49C09dJxp0QT5LwDzFaVGf/+ITHe3BlIhUiLNttkATSXplc89A2lAaeTqjgqVkiRfUGyQiQ==", + "license": "Apache-2.0" }, "node_modules/@firebase/app-check-types": { "version": "0.5.2", "resolved": "https://registry.npmjs.org/@firebase/app-check-types/-/app-check-types-0.5.2.tgz", - "integrity": "sha512-FSOEzTzL5bLUbD2co3Zut46iyPWML6xc4x+78TeaXMSuJap5QObfb+rVvZJtla3asN4RwU7elaQaduP+HFizDA==" + "integrity": "sha512-FSOEzTzL5bLUbD2co3Zut46iyPWML6xc4x+78TeaXMSuJap5QObfb+rVvZJtla3asN4RwU7elaQaduP+HFizDA==", + "license": "Apache-2.0" }, "node_modules/@firebase/app-compat": { "version": "0.2.35", "resolved": "https://registry.npmjs.org/@firebase/app-compat/-/app-compat-0.2.35.tgz", "integrity": "sha512-vgay/WRjeH0r97/Q6L6df2CMx7oyNFDsE5yPQ9oR1G+zx2eT0s8vNNh0WlKqQxUEWaOLRnXhQ8gy7uu0cBgTRg==", + "license": "Apache-2.0", "dependencies": { "@firebase/app": "0.10.5", "@firebase/component": "0.6.7", @@ -650,12 +695,14 @@ "node_modules/@firebase/app-types": { "version": "0.9.2", "resolved": "https://registry.npmjs.org/@firebase/app-types/-/app-types-0.9.2.tgz", - "integrity": "sha512-oMEZ1TDlBz479lmABwWsWjzHwheQKiAgnuKxE0pz0IXCVx7/rtlkx1fQ6GfgK24WCrxDKMplZrT50Kh04iMbXQ==" + "integrity": "sha512-oMEZ1TDlBz479lmABwWsWjzHwheQKiAgnuKxE0pz0IXCVx7/rtlkx1fQ6GfgK24WCrxDKMplZrT50Kh04iMbXQ==", + "license": "Apache-2.0" }, "node_modules/@firebase/auth": { "version": "1.7.4", "resolved": "https://registry.npmjs.org/@firebase/auth/-/auth-1.7.4.tgz", "integrity": "sha512-d2Fw17s5QesojwebrA903el20Li9/YGgkoOGJjagM4I1qAT36APa/FcZ+OX86KxbYKCtQKTMqraU8pxG7C2JWA==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/logger": "0.4.2", @@ -677,6 +724,7 @@ "version": "0.5.9", "resolved": "https://registry.npmjs.org/@firebase/auth-compat/-/auth-compat-0.5.9.tgz", "integrity": "sha512-RX8Zh/3zz2CsVbmYfgHkfUm4fAEPCl+KHVIImNygV5jTGDF6oKOhBIpf4Yigclyu8ESQKZ4elyN0MBYm9/7zGw==", + "license": "Apache-2.0", "dependencies": { "@firebase/auth": "1.7.4", "@firebase/auth-types": "0.12.2", @@ -692,12 +740,14 @@ "node_modules/@firebase/auth-interop-types": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/@firebase/auth-interop-types/-/auth-interop-types-0.2.3.tgz", - "integrity": "sha512-Fc9wuJGgxoxQeavybiuwgyi+0rssr76b+nHpj+eGhXFYAdudMWyfBHvFL/I5fEHniUM/UQdFzi9VXJK2iZF7FQ==" + "integrity": "sha512-Fc9wuJGgxoxQeavybiuwgyi+0rssr76b+nHpj+eGhXFYAdudMWyfBHvFL/I5fEHniUM/UQdFzi9VXJK2iZF7FQ==", + "license": "Apache-2.0" }, "node_modules/@firebase/auth-types": { "version": "0.12.2", "resolved": "https://registry.npmjs.org/@firebase/auth-types/-/auth-types-0.12.2.tgz", "integrity": "sha512-qsEBaRMoGvHO10unlDJhaKSuPn4pyoTtlQuP1ghZfzB6rNQPuhp/N/DcFZxm9i4v0SogjCbf9reWupwIvfmH6w==", + "license": "Apache-2.0", "peerDependencies": { "@firebase/app-types": "0.x", "@firebase/util": "1.x" @@ -707,6 +757,7 @@ "version": "0.6.7", "resolved": "https://registry.npmjs.org/@firebase/component/-/component-0.6.7.tgz", "integrity": "sha512-baH1AA5zxfaz4O8w0vDwETByrKTQqB5CDjRls79Sa4eAGAoERw4Tnung7XbMl3jbJ4B/dmmtsMrdki0KikwDYA==", + "license": "Apache-2.0", "dependencies": { "@firebase/util": "1.9.6", "tslib": "^2.1.0" @@ -716,6 +767,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/@firebase/database/-/database-1.0.5.tgz", "integrity": "sha512-cAfwBqMQuW6HbhwI3Cb/gDqZg7aR0OmaJ85WUxlnoYW2Tm4eR0hFl5FEijI3/gYPUiUcUPQvTkGV222VkT7KPw==", + "license": "Apache-2.0", "dependencies": { "@firebase/app-check-interop-types": "0.3.2", "@firebase/auth-interop-types": "0.2.3", @@ -730,6 +782,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/@firebase/database-compat/-/database-compat-1.0.5.tgz", "integrity": "sha512-NDSMaDjQ+TZEMDMmzJwlTL05kh1+0Y84C+kVMaOmNOzRGRM7VHi29I6YUhCetXH+/b1Wh4ZZRyp1CuWkd8s6hg==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/database": "1.0.5", @@ -743,6 +796,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/@firebase/database-types/-/database-types-1.0.3.tgz", "integrity": "sha512-39V/Riv2R3O/aUjYKh0xypj7NTNXNAK1bcgY5Kx+hdQPRS/aPTS8/5c0CGFYKgVuFbYlnlnhrCTYsh2uNhGwzA==", + "license": "Apache-2.0", "dependencies": { "@firebase/app-types": "0.9.2", "@firebase/util": "1.9.6" @@ -752,6 +806,7 @@ "version": "4.6.3", "resolved": "https://registry.npmjs.org/@firebase/firestore/-/firestore-4.6.3.tgz", "integrity": "sha512-d/+N2iUsiJ/Dc7fApdpdmmTXzwuTCromsdA1lKwYfZtMIOd1fI881NSLwK2wV4I38wkLnvfKJUV6WpU1f3/ONg==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/logger": "0.4.2", @@ -773,6 +828,7 @@ "version": "0.3.32", "resolved": "https://registry.npmjs.org/@firebase/firestore-compat/-/firestore-compat-0.3.32.tgz", "integrity": "sha512-at71mwK7a/mUXH0OgyY0+gUzedm/EUydDFYSFsBoO8DYowZ23Mgd6P4Rzq/Ll3zI/3xJN7LGe7Qp4iE/V/3Arg==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/firestore": "4.6.3", @@ -788,6 +844,7 @@ "version": "3.0.2", "resolved": "https://registry.npmjs.org/@firebase/firestore-types/-/firestore-types-3.0.2.tgz", "integrity": "sha512-wp1A+t5rI2Qc/2q7r2ZpjUXkRVPtGMd6zCLsiWurjsQpqPgFin3AhNibKcIzoF2rnToNa/XYtyWXuifjOOwDgg==", + "license": "Apache-2.0", "peerDependencies": { "@firebase/app-types": "0.x", "@firebase/util": "1.x" @@ -797,6 +854,7 @@ "version": "0.11.5", "resolved": "https://registry.npmjs.org/@firebase/functions/-/functions-0.11.5.tgz", "integrity": "sha512-qrHJ+l62mZiU5UZiVi84t/iLXZlhRuSvBQsa2qvNLgPsEWR7wdpWhRmVdB7AU8ndkSHJjGlMICqrVnz47sgU7Q==", + "license": "Apache-2.0", "dependencies": { "@firebase/app-check-interop-types": "0.3.2", "@firebase/auth-interop-types": "0.2.3", @@ -814,6 +872,7 @@ "version": "0.3.11", "resolved": "https://registry.npmjs.org/@firebase/functions-compat/-/functions-compat-0.3.11.tgz", "integrity": "sha512-Qn+ts/M6Lj2/6i1cp5V5TRR+Hi9kyXyHbo+w9GguINJ87zxrCe6ulx3TI5AGQkoQa8YFHUhT3DMGmLFiJjWTSQ==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/functions": "0.11.5", @@ -828,12 +887,14 @@ "node_modules/@firebase/functions-types": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/@firebase/functions-types/-/functions-types-0.6.2.tgz", - "integrity": "sha512-0KiJ9lZ28nS2iJJvimpY4nNccV21rkQyor5Iheu/nq8aKXJqtJdeSlZDspjPSBBiHRzo7/GMUttegnsEITqR+w==" + "integrity": "sha512-0KiJ9lZ28nS2iJJvimpY4nNccV21rkQyor5Iheu/nq8aKXJqtJdeSlZDspjPSBBiHRzo7/GMUttegnsEITqR+w==", + "license": "Apache-2.0" }, "node_modules/@firebase/installations": { "version": "0.6.7", "resolved": "https://registry.npmjs.org/@firebase/installations/-/installations-0.6.7.tgz", "integrity": "sha512-i6iGoXRu5mX4rTsiMSSKrgh9pSEzD4hwBEzRh5kEhOTr8xN/wvQcCPZDSMVYKwM2XyCPBLVq0JzjyerwL0Rihg==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/util": "1.9.6", @@ -848,6 +909,7 @@ "version": "0.2.7", "resolved": "https://registry.npmjs.org/@firebase/installations-compat/-/installations-compat-0.2.7.tgz", "integrity": "sha512-RPcbD+3nqHbnhVjIOpWK2H5qzZ8pAAAScceiWph0VNTqpKyPQ5tDcp4V5fS0ELpfgsHYvroMLDKfeHxpfvm8cw==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/installations": "0.6.7", @@ -863,6 +925,7 @@ "version": "0.5.2", "resolved": "https://registry.npmjs.org/@firebase/installations-types/-/installations-types-0.5.2.tgz", "integrity": "sha512-que84TqGRZJpJKHBlF2pkvc1YcXrtEDOVGiDjovP/a3s6W4nlbohGXEsBJo0JCeeg/UG9A+DEZVDUV9GpklUzA==", + "license": "Apache-2.0", "peerDependencies": { "@firebase/app-types": "0.x" } @@ -871,6 +934,7 @@ "version": "0.4.2", "resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.4.2.tgz", "integrity": "sha512-Q1VuA5M1Gjqrwom6I6NUU4lQXdo9IAQieXlujeHZWvRt1b7qQ0KwBaNAjgxG27jgF9/mUwsNmO8ptBCGVYhB0A==", + "license": "Apache-2.0", "dependencies": { "tslib": "^2.1.0" } @@ -879,6 +943,7 @@ "version": "0.12.9", "resolved": "https://registry.npmjs.org/@firebase/messaging/-/messaging-0.12.9.tgz", "integrity": "sha512-IH+JJmzbFGZXV3+TDyKdqqKPVfKRqBBg2BfYYOy7cm7J+SwV+uJMe8EnDKYeQLEQhtpwciPfJ3qQXJs2lbxDTw==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/installations": "0.6.7", @@ -895,6 +960,7 @@ "version": "0.2.9", "resolved": "https://registry.npmjs.org/@firebase/messaging-compat/-/messaging-compat-0.2.9.tgz", "integrity": "sha512-5jN6wyhwPgBH02zOtmmoOeyfsmoD7ty48D1m0vVPsFg55RqN2Z3Q9gkZ5GmPklFPjTPLcxB1ObcHOZvThTkm7g==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/messaging": "0.12.9", @@ -908,12 +974,14 @@ "node_modules/@firebase/messaging-interop-types": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/@firebase/messaging-interop-types/-/messaging-interop-types-0.2.2.tgz", - "integrity": "sha512-l68HXbuD2PPzDUOFb3aG+nZj5KA3INcPwlocwLZOzPp9rFM9yeuI9YLl6DQfguTX5eAGxO0doTR+rDLDvQb5tA==" + "integrity": "sha512-l68HXbuD2PPzDUOFb3aG+nZj5KA3INcPwlocwLZOzPp9rFM9yeuI9YLl6DQfguTX5eAGxO0doTR+rDLDvQb5tA==", + "license": "Apache-2.0" }, "node_modules/@firebase/performance": { "version": "0.6.7", "resolved": "https://registry.npmjs.org/@firebase/performance/-/performance-0.6.7.tgz", "integrity": "sha512-d+Q4ltjdJZqjzcdms5i0UC9KLYX7vKGcygZ+7zHA/Xk+bAbMD2CPU0nWTnlNFWifZWIcXZ/2mAMvaGMW3lypUA==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/installations": "0.6.7", @@ -929,6 +997,7 @@ "version": "0.2.7", "resolved": "https://registry.npmjs.org/@firebase/performance-compat/-/performance-compat-0.2.7.tgz", "integrity": "sha512-cb8ge/5iTstxfIGW+iiY+7l3FtN8gobNh9JSQNZgLC9xmcfBYWEs8IeEWMI6S8T+At0oHc3lv+b2kpRMUWr8zQ==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/logger": "0.4.2", @@ -944,12 +1013,14 @@ "node_modules/@firebase/performance-types": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/@firebase/performance-types/-/performance-types-0.2.2.tgz", - "integrity": "sha512-gVq0/lAClVH5STrIdKnHnCo2UcPLjJlDUoEB/tB4KM+hAeHUxWKnpT0nemUPvxZ5nbdY/pybeyMe8Cs29gEcHA==" + "integrity": "sha512-gVq0/lAClVH5STrIdKnHnCo2UcPLjJlDUoEB/tB4KM+hAeHUxWKnpT0nemUPvxZ5nbdY/pybeyMe8Cs29gEcHA==", + "license": "Apache-2.0" }, "node_modules/@firebase/remote-config": { "version": "0.4.7", "resolved": "https://registry.npmjs.org/@firebase/remote-config/-/remote-config-0.4.7.tgz", "integrity": "sha512-5oPNrPFLsbsjpq0lUEIXoDF2eJK7vAbyXe/DEuZQxnwJlfR7aQbtUlEkRgQWcicXpyDmAmDLo7q7lDbCYa6CpA==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/installations": "0.6.7", @@ -965,6 +1036,7 @@ "version": "0.2.7", "resolved": "https://registry.npmjs.org/@firebase/remote-config-compat/-/remote-config-compat-0.2.7.tgz", "integrity": "sha512-Fq0oneQ4SluLnfr5/HfzRS1TZf1ANj1rWbCCW3+oC98An3nE+sCdp+FSuHsEVNwgMg4Tkwx9Oom2lkKeU+Vn+w==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/logger": "0.4.2", @@ -980,12 +1052,14 @@ "node_modules/@firebase/remote-config-types": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@firebase/remote-config-types/-/remote-config-types-0.3.2.tgz", - "integrity": "sha512-0BC4+Ud7y2aPTyhXJTMTFfrGGLqdYXrUB9sJVAB8NiqJswDTc4/2qrE/yfUbnQJhbSi6ZaTTBKyG3n1nplssaA==" + "integrity": "sha512-0BC4+Ud7y2aPTyhXJTMTFfrGGLqdYXrUB9sJVAB8NiqJswDTc4/2qrE/yfUbnQJhbSi6ZaTTBKyG3n1nplssaA==", + "license": "Apache-2.0" }, "node_modules/@firebase/storage": { "version": "0.12.5", "resolved": "https://registry.npmjs.org/@firebase/storage/-/storage-0.12.5.tgz", "integrity": "sha512-nGWBOGFNr10j0LA4NJ3/Yh3us/lb0Q1xSIKZ38N6FcS+vY54nqJ7k3zE3PENregHC8+8txRow++A568G3v8hOA==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/util": "1.9.6", @@ -1000,6 +1074,7 @@ "version": "0.3.8", "resolved": "https://registry.npmjs.org/@firebase/storage-compat/-/storage-compat-0.3.8.tgz", "integrity": "sha512-qDfY9kMb6Ch2hZb40sBjDQ8YPxbjGOxuT+gU1Z0iIVSSpSX0f4YpGJCypUXiA0T11n6InCXB+T/Dknh2yxVTkg==", + "license": "Apache-2.0", "dependencies": { "@firebase/component": "0.6.7", "@firebase/storage": "0.12.5", @@ -1015,6 +1090,7 @@ "version": "0.8.2", "resolved": "https://registry.npmjs.org/@firebase/storage-types/-/storage-types-0.8.2.tgz", "integrity": "sha512-0vWu99rdey0g53lA7IShoA2Lol1jfnPovzLDUBuon65K7uKG9G+L5uO05brD9pMw+l4HRFw23ah3GwTGpEav6g==", + "license": "Apache-2.0", "peerDependencies": { "@firebase/app-types": "0.x", "@firebase/util": "1.x" @@ -1024,6 +1100,7 @@ "version": "1.9.6", "resolved": "https://registry.npmjs.org/@firebase/util/-/util-1.9.6.tgz", "integrity": "sha512-IBr1MZbp4d5MjBCXL3TW1dK/PDXX4yOGbiwRNh1oAbE/+ci5Uuvy9KIrsFYY80as1I0iOaD5oOMA9Q8j4TJWcw==", + "license": "Apache-2.0", "dependencies": { "tslib": "^2.1.0" } @@ -1032,6 +1109,7 @@ "version": "0.0.2", "resolved": "https://registry.npmjs.org/@firebase/vertexai-preview/-/vertexai-preview-0.0.2.tgz", "integrity": "sha512-NOOL63kFQRq45ioi5P+hlqj/4LNmvn1URhGjQdvyV54c1Irvoq26aW861PRRLjrSMIeNeiLtCLD5pe+ediepAg==", + "license": "Apache-2.0", "dependencies": { "@firebase/app-check-interop-types": "0.3.2", "@firebase/component": "0.6.7", @@ -1050,12 +1128,14 @@ "node_modules/@firebase/webchannel-wrapper": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@firebase/webchannel-wrapper/-/webchannel-wrapper-1.0.0.tgz", - "integrity": "sha512-zuWxyfXNbsKbm96HhXzainONPFqRcoZblQ++e9cAIGUuHfl2cFSBzW01jtesqWG/lqaUyX3H8O1y9oWboGNQBA==" + "integrity": "sha512-zuWxyfXNbsKbm96HhXzainONPFqRcoZblQ++e9cAIGUuHfl2cFSBzW01jtesqWG/lqaUyX3H8O1y9oWboGNQBA==", + "license": "Apache-2.0" }, "node_modules/@grpc/grpc-js": { "version": "1.9.15", "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.9.15.tgz", "integrity": "sha512-nqE7Hc0AzI+euzUwDAy0aY5hCp10r734gMGRdU+qOPX0XSceI2ULrcXB5U2xSc5VkWwalCj4M7GzCAygZl2KoQ==", + "license": "Apache-2.0", "dependencies": { "@grpc/proto-loader": "^0.7.8", "@types/node": ">=12.12.47" @@ -1068,6 +1148,7 @@ "version": "0.7.13", "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.13.tgz", "integrity": "sha512-AiXO/bfe9bmxBjxxtYxFAXGZvMaN5s8kO+jBHAJCON8rJoB5YS/D6X7ZNc6XQkuHNmyl4CYaMI1fJ/Gn27RGGw==", + "license": "Apache-2.0", "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", @@ -1086,6 +1167,7 @@ "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", "dev": true, + "license": "Apache-2.0", "engines": { "node": ">=12.22" }, @@ -1099,6 +1181,7 @@ "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.0.tgz", "integrity": "sha512-d2CGZR2o7fS6sWB7DG/3a95bGKQyHMACZ5aW8qGkkqQpUoZV6C0X7Pc7l4ZNMZkfNBf4VWNe9E1jRsf0G146Ew==", "dev": true, + "license": "Apache-2.0", "engines": { "node": ">=18.18" }, @@ -1112,6 +1195,7 @@ "resolved": "https://registry.npmjs.org/@hutson/parse-repository-url/-/parse-repository-url-3.0.2.tgz", "integrity": "sha512-H9XAx3hc0BQHY6l+IFSWHDySypcXsvsuLhgYLUGywmJ5pswRVQJUHpOsobnLYp2ZUaUlKiKDrgWWhosOwAEM8Q==", "dev": true, + "license": "Apache-2.0", "engines": { "node": ">=6.9.0" } @@ -1121,6 +1205,7 @@ "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "dev": true, + "license": "MIT", "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" @@ -1134,6 +1219,7 @@ "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "dev": true, + "license": "MIT", "engines": { "node": ">= 8" } @@ -1143,6 +1229,7 @@ "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dev": true, + "license": "MIT", "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" @@ -1154,27 +1241,32 @@ "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==" + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" }, "node_modules/@protobufjs/base64": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", - "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==" + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" }, "node_modules/@protobufjs/codegen": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", - "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==" + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==", + "license": "BSD-3-Clause" }, "node_modules/@protobufjs/eventemitter": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", - "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==" + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==", + "license": "BSD-3-Clause" }, "node_modules/@protobufjs/fetch": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "license": "BSD-3-Clause", "dependencies": { "@protobufjs/aspromise": "^1.1.1", "@protobufjs/inquire": "^1.1.0" @@ -1183,33 +1275,39 @@ "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==" + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" }, "node_modules/@protobufjs/inquire": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", - "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==" + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==", + "license": "BSD-3-Clause" }, "node_modules/@protobufjs/path": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", - "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==" + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" }, "node_modules/@protobufjs/pool": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", - "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==" + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" }, "node_modules/@protobufjs/utf8": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", - "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==" + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==", + "license": "BSD-3-Clause" }, "node_modules/@stylistic/eslint-plugin-js": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin-js/-/eslint-plugin-js-2.2.0.tgz", - "integrity": "sha512-pdkNeVORubs+k7jmhHivYXggoFvw1ykAyGBQomodOYO8MhO8/IM798XVyjadC6EeTeBiXlEWYRy/4QV34hDz+A==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin-js/-/eslint-plugin-js-2.3.0.tgz", + "integrity": "sha512-lQwoiYb0Fs6Yc5QS3uT8+T9CPKK2Eoxc3H8EnYJgM26v/DgtW+1lvy2WNgyBflU+ThShZaHm3a6CdD9QeKx23w==", "dev": true, + "license": "MIT", "dependencies": { "@types/eslint": "^8.56.10", "acorn": "^8.11.3", @@ -1228,6 +1326,7 @@ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.56.10.tgz", "integrity": "sha512-Shavhk87gCtY2fhXDctcfS3e6FdxWkCx1iUZ9eEUbh7rTqlZT0/IzOkCOVt0fCjcFuZ9FPYfuezTBImfHCDBGQ==", "dev": true, + "license": "MIT", "dependencies": { "@types/estree": "*", "@types/json-schema": "*" @@ -1237,24 +1336,28 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@types/minimist": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.5.tgz", "integrity": "sha512-hov8bUuiLiyFPGyFPE1lwWhmzYbirOXQNNo40+y3zow8aFVTeyn3VWL0VFFfdNddA8S4Vf0Tc062rzyNr7Paag==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/@types/node": { - "version": "20.14.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.2.tgz", - "integrity": "sha512-xyu6WAMVwv6AKFLB+e/7ySZVr/0zLCzOa7rSpq6jNwpqOrUbcACDWC+53d4n2QHOnDou0fbIsg8wZu/sxrnI4Q==", + "version": "20.14.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.9.tgz", + "integrity": "sha512-06OCtnTXtWOZBJlRApleWndH4JsRVs1pDCc8dLSQp+7PpUpX3ePdHyeNSFTeSe7FtKyQkrlPvHwJOW3SLd8Oyg==", + "license": "MIT", "dependencies": { "undici-types": "~5.26.4" } @@ -1263,13 +1366,15 @@ "version": "2.4.4", "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.4.tgz", "integrity": "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/acorn": { "version": "8.12.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.0.tgz", "integrity": "sha512-RTvkC4w+KNXrM39/lWCUaG0IbRkWdCv7W/IOW9oU6SawyxulvkQy5HQPVTKxEjczcUvapcrw3cFx/60VN/NRNw==", "dev": true, + "license": "MIT", "bin": { "acorn": "bin/acorn" }, @@ -1282,6 +1387,7 @@ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", "dev": true, + "license": "MIT", "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } @@ -1290,13 +1396,15 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/add-stream/-/add-stream-1.0.0.tgz", "integrity": "sha512-qQLMr+8o0WC4FZGQTcJiKBVC59JylcPSrTtk6usvmIDFUOCKegapy1VHQwRbFMOFyb/inzUVqHs+eMYKDM1YeQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/agent-base": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", "dev": true, + "license": "MIT", "dependencies": { "debug": "^4.3.4" }, @@ -1309,6 +1417,7 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, + "license": "MIT", "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -1324,6 +1433,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", "engines": { "node": ">=8" } @@ -1333,6 +1443,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^1.9.0" }, @@ -1344,19 +1455,22 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true + "dev": true, + "license": "Python-2.0" }, "node_modules/array-ify": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/array-ify/-/array-ify-1.0.0.tgz", "integrity": "sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/arrify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", "integrity": "sha512-3CYzex9M9FGQjCGMGyi6/31c8GJbgb0qGyrx5HWxPd0aCwh4cB2YjMb2Xf9UuoogrMrlO9cTqnB5rI5GHZTcUA==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -1365,19 +1479,22 @@ "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/bidi-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", "dev": true, + "license": "MIT", "dependencies": { "require-from-string": "^2.0.2" } @@ -1387,6 +1504,7 @@ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, + "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -1396,13 +1514,15 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -1412,6 +1532,7 @@ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -1421,6 +1542,7 @@ "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-6.2.2.tgz", "integrity": "sha512-YrwaA0vEKazPBkn0ipTiMpSajYDSe+KjQfrjhcBMxJt/znbvlHd8Pw/Vamaz5EB4Wfhs3SUR3Z9mwRu/P3s3Yg==", "dev": true, + "license": "MIT", "dependencies": { "camelcase": "^5.3.1", "map-obj": "^4.0.0", @@ -1438,6 +1560,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -1451,6 +1574,7 @@ "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", "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", @@ -1465,6 +1589,7 @@ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, + "license": "MIT", "dependencies": { "color-name": "1.1.3" } @@ -1473,13 +1598,15 @@ "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", "dev": true, + "license": "MIT", "dependencies": { "delayed-stream": "~1.0.0" }, @@ -1492,6 +1619,7 @@ "resolved": "https://registry.npmjs.org/commit-and-tag-version/-/commit-and-tag-version-12.4.1.tgz", "integrity": "sha512-+NAbDJ2KiXDvV45S8r6o1DWbeEXijxb+Vxp9dsogISuSeRZ5JOPiaQsHoDKhZ58FuBtmp6ITe/hpeFu2gT82xA==", "dev": true, + "license": "ISC", "dependencies": { "chalk": "^2.4.2", "conventional-changelog": "3.1.25", @@ -1522,6 +1650,7 @@ "resolved": "https://registry.npmjs.org/compare-func/-/compare-func-2.0.0.tgz", "integrity": "sha512-zHig5N+tPWARooBnb0Zx1MFcdfpyJrfTJ3Y5L+IFvUm8rM74hHz66z0gw0x4tijh5CorKkKUCnW82R2vmpeCRA==", "dev": true, + "license": "MIT", "dependencies": { "array-ify": "^1.0.0", "dot-prop": "^5.1.0" @@ -1531,7 +1660,8 @@ "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/concat-stream": { "version": "2.0.0", @@ -1541,6 +1671,7 @@ "engines": [ "node >= 6.0" ], + "license": "MIT", "dependencies": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", @@ -1553,6 +1684,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog/-/conventional-changelog-3.1.25.tgz", "integrity": "sha512-ryhi3fd1mKf3fSjbLXOfK2D06YwKNic1nC9mWqybBHdObPd8KJ2vjaXZfYj1U23t+V8T8n0d7gwnc9XbIdFbyQ==", "dev": true, + "license": "MIT", "dependencies": { "conventional-changelog-angular": "^5.0.12", "conventional-changelog-atom": "^2.0.8", @@ -1575,6 +1707,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-angular/-/conventional-changelog-angular-5.0.13.tgz", "integrity": "sha512-i/gipMxs7s8L/QeuavPF2hLnJgH6pEZAttySB6aiQLWcX3puWDL3ACVmvBhJGxnAy52Qc15ua26BufY6KpmrVA==", "dev": true, + "license": "ISC", "dependencies": { "compare-func": "^2.0.0", "q": "^1.5.1" @@ -1588,6 +1721,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-atom/-/conventional-changelog-atom-2.0.8.tgz", "integrity": "sha512-xo6v46icsFTK3bb7dY/8m2qvc8sZemRgdqLb/bjpBsH2UyOS8rKNTgcb5025Hri6IpANPApbXMg15QLb1LJpBw==", "dev": true, + "license": "ISC", "dependencies": { "q": "^1.5.1" }, @@ -1600,6 +1734,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-codemirror/-/conventional-changelog-codemirror-2.0.8.tgz", "integrity": "sha512-z5DAsn3uj1Vfp7po3gpt2Boc+Bdwmw2++ZHa5Ak9k0UKsYAO5mH1UBTN0qSCuJZREIhX6WU4E1p3IW2oRCNzQw==", "dev": true, + "license": "ISC", "dependencies": { "q": "^1.5.1" }, @@ -1611,13 +1746,15 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/conventional-changelog-config-spec/-/conventional-changelog-config-spec-2.1.0.tgz", "integrity": "sha512-IpVePh16EbbB02V+UA+HQnnPIohgXvJRxHcS5+Uwk4AT5LjzCZJm5sp/yqs5C6KZJ1jMsV4paEV13BN1pvDuxQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/conventional-changelog-conventionalcommits": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/conventional-changelog-conventionalcommits/-/conventional-changelog-conventionalcommits-6.1.0.tgz", "integrity": "sha512-3cS3GEtR78zTfMzk0AizXKKIdN4OvSh7ibNz6/DPbhWWQu7LqE/8+/GqSodV+sywUR2gpJAdP/1JFf4XtN7Zpw==", "dev": true, + "license": "ISC", "dependencies": { "compare-func": "^2.0.0" }, @@ -1630,6 +1767,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-core/-/conventional-changelog-core-4.2.4.tgz", "integrity": "sha512-gDVS+zVJHE2v4SLc6B0sLsPiloR0ygU7HaDW14aNJE1v4SlqJPILPl/aJC7YdtRE4CybBf8gDwObBvKha8Xlyg==", "dev": true, + "license": "MIT", "dependencies": { "add-stream": "^1.0.0", "conventional-changelog-writer": "^5.0.0", @@ -1655,6 +1793,7 @@ "resolved": "https://registry.npmjs.org/git-semver-tags/-/git-semver-tags-4.1.1.tgz", "integrity": "sha512-OWyMt5zBe7xFs8vglMmhM9lRQzCWL3WjHtxNNfJTMngGym7pC1kh8sP6jevfydJ6LP3ZvGxfb6ABYgPUM0mtsA==", "dev": true, + "license": "MIT", "dependencies": { "meow": "^8.0.0", "semver": "^6.0.0" @@ -1671,6 +1810,7 @@ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true, + "license": "ISC", "bin": { "semver": "bin/semver.js" } @@ -1680,6 +1820,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-ember/-/conventional-changelog-ember-2.0.9.tgz", "integrity": "sha512-ulzIReoZEvZCBDhcNYfDIsLTHzYHc7awh+eI44ZtV5cx6LVxLlVtEmcO+2/kGIHGtw+qVabJYjdI5cJOQgXh1A==", "dev": true, + "license": "ISC", "dependencies": { "q": "^1.5.1" }, @@ -1692,6 +1833,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-eslint/-/conventional-changelog-eslint-3.0.9.tgz", "integrity": "sha512-6NpUCMgU8qmWmyAMSZO5NrRd7rTgErjrm4VASam2u5jrZS0n38V7Y9CzTtLT2qwz5xEChDR4BduoWIr8TfwvXA==", "dev": true, + "license": "ISC", "dependencies": { "q": "^1.5.1" }, @@ -1704,6 +1846,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-express/-/conventional-changelog-express-2.0.6.tgz", "integrity": "sha512-SDez2f3iVJw6V563O3pRtNwXtQaSmEfTCaTBPCqn0oG0mfkq0rX4hHBq5P7De2MncoRixrALj3u3oQsNK+Q0pQ==", "dev": true, + "license": "ISC", "dependencies": { "q": "^1.5.1" }, @@ -1716,6 +1859,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-jquery/-/conventional-changelog-jquery-3.0.11.tgz", "integrity": "sha512-x8AWz5/Td55F7+o/9LQ6cQIPwrCjfJQ5Zmfqi8thwUEKHstEn4kTIofXub7plf1xvFA2TqhZlq7fy5OmV6BOMw==", "dev": true, + "license": "ISC", "dependencies": { "q": "^1.5.1" }, @@ -1728,6 +1872,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-jshint/-/conventional-changelog-jshint-2.0.9.tgz", "integrity": "sha512-wMLdaIzq6TNnMHMy31hql02OEQ8nCQfExw1SE0hYL5KvU+JCTuPaDO+7JiogGT2gJAxiUGATdtYYfh+nT+6riA==", "dev": true, + "license": "ISC", "dependencies": { "compare-func": "^2.0.0", "q": "^1.5.1" @@ -1741,6 +1886,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-preset-loader/-/conventional-changelog-preset-loader-2.3.4.tgz", "integrity": "sha512-GEKRWkrSAZeTq5+YjUZOYxdHq+ci4dNwHvpaBC3+ENalzFWuCWa9EZXSuZBpkr72sMdKB+1fyDV4takK1Lf58g==", "dev": true, + "license": "MIT", "engines": { "node": ">=10" } @@ -1750,6 +1896,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-writer/-/conventional-changelog-writer-5.0.1.tgz", "integrity": "sha512-5WsuKUfxW7suLblAbFnxAcrvf6r+0b7GvNaWUwUIk0bXMnENP/PEieGKVUQrjPqwPT4o3EPAASBXiY6iHooLOQ==", "dev": true, + "license": "MIT", "dependencies": { "conventional-commits-filter": "^2.0.7", "dateformat": "^3.0.0", @@ -1773,6 +1920,7 @@ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "dev": true, + "license": "ISC", "bin": { "semver": "bin/semver.js" } @@ -1782,6 +1930,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-conventionalcommits/-/conventional-changelog-conventionalcommits-4.6.3.tgz", "integrity": "sha512-LTTQV4fwOM4oLPad317V/QNQ1FY4Hju5qeBIM1uTHbrnCE+Eg4CdRZ3gO2pUeR+tzWdp80M2j3qFFEDWVqOV4g==", "dev": true, + "license": "ISC", "dependencies": { "compare-func": "^2.0.0", "lodash": "^4.17.15", @@ -1796,6 +1945,7 @@ "resolved": "https://registry.npmjs.org/conventional-commits-filter/-/conventional-commits-filter-2.0.7.tgz", "integrity": "sha512-ASS9SamOP4TbCClsRHxIHXRfcGCnIoQqkvAzCSbZzTFLfcTqJVugB0agRgsEELsqaeWgsXv513eS116wnlSSPA==", "dev": true, + "license": "MIT", "dependencies": { "lodash.ismatch": "^4.4.0", "modify-values": "^1.0.0" @@ -1809,6 +1959,7 @@ "resolved": "https://registry.npmjs.org/conventional-commits-parser/-/conventional-commits-parser-3.2.4.tgz", "integrity": "sha512-nK7sAtfi+QXbxHCYfhpZsfRtaitZLIA6889kFIouLvz6repszQDgxBu7wf2WbU+Dco7sAnNCJYERCwt54WPC2Q==", "dev": true, + "license": "MIT", "dependencies": { "is-text-path": "^1.0.1", "JSONStream": "^1.0.4", @@ -1829,6 +1980,7 @@ "resolved": "https://registry.npmjs.org/conventional-recommended-bump/-/conventional-recommended-bump-7.0.1.tgz", "integrity": "sha512-Ft79FF4SlOFvX4PkwFDRnaNiIVX7YbmqGU0RwccUaiGvgp3S0a8ipR2/Qxk31vclDNM+GSdJOVs2KrsUCjblVA==", "dev": true, + "license": "MIT", "dependencies": { "concat-stream": "^2.0.0", "conventional-changelog-preset-loader": "^3.0.0", @@ -1850,6 +2002,7 @@ "resolved": "https://registry.npmjs.org/conventional-changelog-preset-loader/-/conventional-changelog-preset-loader-3.0.0.tgz", "integrity": "sha512-qy9XbdSLmVnwnvzEisjxdDiLA4OmV3o8db+Zdg4WiFw14fP3B6XNz98X0swPPpkTd/pc1K7+adKgEDM1JCUMiA==", "dev": true, + "license": "MIT", "engines": { "node": ">=14" } @@ -1859,6 +2012,7 @@ "resolved": "https://registry.npmjs.org/conventional-commits-filter/-/conventional-commits-filter-3.0.0.tgz", "integrity": "sha512-1ymej8b5LouPx9Ox0Dw/qAO2dVdfpRFq28e5Y0jJEU8ZrLdy0vOSkkIInwmxErFGhg6SALro60ZrwYFVTUDo4Q==", "dev": true, + "license": "MIT", "dependencies": { "lodash.ismatch": "^4.4.0", "modify-values": "^1.0.1" @@ -1872,6 +2026,7 @@ "resolved": "https://registry.npmjs.org/conventional-commits-parser/-/conventional-commits-parser-4.0.0.tgz", "integrity": "sha512-WRv5j1FsVM5FISJkoYMR6tPk07fkKT0UodruX4je86V4owk451yjXAKzKAPOs9l7y59E2viHUS9eQ+dfUA9NSg==", "dev": true, + "license": "MIT", "dependencies": { "is-text-path": "^1.0.1", "JSONStream": "^1.3.5", @@ -1890,6 +2045,7 @@ "resolved": "https://registry.npmjs.org/git-raw-commits/-/git-raw-commits-3.0.0.tgz", "integrity": "sha512-b5OHmZ3vAgGrDn/X0kS+9qCfNKWe4K/jFnhwzVWWg0/k5eLa3060tZShrRg8Dja5kPc+YjS0Gc6y7cRr44Lpjw==", "dev": true, + "license": "MIT", "dependencies": { "dargs": "^7.0.0", "meow": "^8.1.2", @@ -1906,13 +2062,15 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, + "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -1927,6 +2085,7 @@ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.3.1.tgz", "integrity": "sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==", "dev": true, + "license": "MIT", "dependencies": { "mdn-data": "2.0.30", "source-map-js": "^1.0.1" @@ -1940,6 +2099,7 @@ "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.0.1.tgz", "integrity": "sha512-8ZYiJ3A/3OkDd093CBT/0UKDWry7ak4BdPTFP2+QEP7cmhouyq/Up709ASSj2cK02BbZiMgk7kYjZNS4QP5qrQ==", "dev": true, + "license": "MIT", "dependencies": { "rrweb-cssom": "^0.6.0" }, @@ -1952,6 +2112,7 @@ "resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz", "integrity": "sha512-2iy1EkLdlBzQGvbweYRFxmFath8+K7+AKB0TlhHWkNuH+TmovaMH/Wp7V7R4u7f4SnX3OgLsU9t1NI9ioDnUpg==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -1961,6 +2122,7 @@ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", "dev": true, + "license": "MIT", "dependencies": { "whatwg-mimetype": "^4.0.0", "whatwg-url": "^14.0.0" @@ -1974,6 +2136,7 @@ "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-3.0.3.tgz", "integrity": "sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q==", "dev": true, + "license": "MIT", "engines": { "node": "*" } @@ -1983,6 +2146,7 @@ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", "dev": true, + "license": "MIT", "dependencies": { "ms": "2.1.2" }, @@ -2000,6 +2164,7 @@ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -2009,6 +2174,7 @@ "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.1.tgz", "integrity": "sha512-WiPxgEirIV0/eIOMcnFBA3/IJZAZqKnwAwWyvvdi4lsr1WCN22nhdf/3db3DoZcUjTV2SqfzIwNyp6y2xs3nmg==", "dev": true, + "license": "MIT", "dependencies": { "decamelize": "^1.1.0", "map-obj": "^1.0.0" @@ -2025,6 +2191,7 @@ "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", "integrity": "sha512-7N/q3lyZ+LVCp7PzuxrJr4KMbBE2hW7BT7YNia330OFxIf4d3r5zVpicP2650l7CPN6RM9zOJRl3NGpqSiw3Eg==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -2033,19 +2200,22 @@ "version": "10.4.3", "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz", "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.4.0" } @@ -2055,6 +2225,7 @@ "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", "integrity": "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -2064,6 +2235,7 @@ "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -2073,6 +2245,7 @@ "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", "dev": true, + "license": "MIT", "dependencies": { "is-obj": "^2.0.0" }, @@ -2085,6 +2258,7 @@ "resolved": "https://registry.npmjs.org/dotgitignore/-/dotgitignore-2.1.0.tgz", "integrity": "sha512-sCm11ak2oY6DglEPpCB8TixLjWAxd3kJTs6UIcSasNYxXdFPV+YKlye92c8H4kKFqV5qYMIh7d+cYecEg0dIkA==", "dev": true, + "license": "ISC", "dependencies": { "find-up": "^3.0.0", "minimatch": "^3.0.4" @@ -2098,6 +2272,7 @@ "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", "dev": true, + "license": "MIT", "dependencies": { "locate-path": "^3.0.0" }, @@ -2110,6 +2285,7 @@ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", "dev": true, + "license": "MIT", "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" @@ -2123,6 +2299,7 @@ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, + "license": "MIT", "dependencies": { "p-try": "^2.0.0" }, @@ -2138,6 +2315,7 @@ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", "dev": true, + "license": "MIT", "dependencies": { "p-limit": "^2.0.0" }, @@ -2150,6 +2328,7 @@ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -2157,13 +2336,15 @@ "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==" + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" }, "node_modules/entities": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=0.12" }, @@ -2176,6 +2357,7 @@ "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", "dev": true, + "license": "MIT", "dependencies": { "is-arrayish": "^0.2.1" } @@ -2186,6 +2368,7 @@ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", "dev": true, "hasInstallScript": true, + "license": "MIT", "bin": { "esbuild": "bin/esbuild" }, @@ -2222,6 +2405,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", + "license": "MIT", "engines": { "node": ">=6" } @@ -2231,21 +2415,23 @@ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.8.0" } }, "node_modules/eslint": { - "version": "9.5.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.5.0.tgz", - "integrity": "sha512-+NAOZFrW/jFTS3dASCGBxX1pkFD0/fsO+hfAkJ4TyYKwgsXZbqzrw+seCYFCcPCYXvnD67tAnglU7GQTz6kcVw==", + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.6.0.tgz", + "integrity": "sha512-ElQkdLMEEqQNM9Njff+2Y4q2afHk7JpkPvrd7Xh7xefwgQynqPxwf55J7di9+MEibWUGdNjFF9ITG9Pck5M84w==", "dev": true, + "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", - "@eslint/config-array": "^0.16.0", + "@eslint/config-array": "^0.17.0", "@eslint/eslintrc": "^3.1.0", - "@eslint/js": "9.5.0", + "@eslint/js": "9.6.0", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.3.0", "@nodelib/fs.walk": "^1.2.8", @@ -2256,7 +2442,7 @@ "escape-string-regexp": "^4.0.0", "eslint-scope": "^8.0.1", "eslint-visitor-keys": "^4.0.0", - "espree": "^10.0.1", + "espree": "^10.1.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", @@ -2291,6 +2477,7 @@ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.0.1.tgz", "integrity": "sha512-pL8XjgP4ZOmmwfFE8mEhSxA7ZY4C+LWyqjQ3o4yWkkmD0qcMT9kkW3zWHOczhWcjTSgqycYAgwSlXvZltv65og==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" @@ -2307,6 +2494,7 @@ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz", "integrity": "sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw==", "dev": true, + "license": "Apache-2.0", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, @@ -2319,6 +2507,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -2334,6 +2523,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -2350,6 +2540,7 @@ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, + "license": "MIT", "dependencies": { "color-name": "~1.1.4" }, @@ -2361,13 +2552,15 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/eslint/node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", "dev": true, + "license": "MIT", "engines": { "node": ">=10" }, @@ -2380,6 +2573,7 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -2389,6 +2583,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -2397,12 +2592,13 @@ } }, "node_modules/espree": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.0.1.tgz", - "integrity": "sha512-MWkrWZbJsL2UwnjxTX3gG8FneachS/Mwg7tdGXce011sJd5b0JG54vat5KHnfSBODZ3Wvzd2WnjxyzsRoVv+ww==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.1.0.tgz", + "integrity": "sha512-M1M6CpiE6ffoigIOWYO9UDP8TMUw9kqb21tf+08IgDYjCsOvCuDt4jQcZmoYxx+w7zlKw9/N0KXfto+I8/FrXA==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { - "acorn": "^8.11.3", + "acorn": "^8.12.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^4.0.0" }, @@ -2418,6 +2614,7 @@ "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { "estraverse": "^5.1.0" }, @@ -2430,6 +2627,7 @@ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "estraverse": "^5.2.0" }, @@ -2442,6 +2640,7 @@ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=4.0" } @@ -2451,6 +2650,7 @@ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=0.10.0" } @@ -2459,25 +2659,29 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/fastq": { "version": "1.17.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", "dev": true, + "license": "ISC", "dependencies": { "reusify": "^1.0.4" } @@ -2486,6 +2690,7 @@ "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" }, @@ -2498,6 +2703,7 @@ "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", "dev": true, + "license": "MIT", "dependencies": { "escape-string-regexp": "^1.0.5" }, @@ -2513,6 +2719,7 @@ "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", "dev": true, + "license": "MIT", "dependencies": { "flat-cache": "^4.0.0" }, @@ -2525,6 +2732,7 @@ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, + "license": "MIT", "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" @@ -2540,6 +2748,7 @@ "version": "10.12.2", "resolved": "https://registry.npmjs.org/firebase/-/firebase-10.12.2.tgz", "integrity": "sha512-ZxEdtSvP1I9su1yf32D8TIdgxtPgxwr6z3jYAR1TXS/t+fVfpoPc/N1/N2bxOco9mNjUoc+od34v5Fn4GeKs6Q==", + "license": "Apache-2.0", "dependencies": { "@firebase/analytics": "0.10.4", "@firebase/analytics-compat": "0.2.10", @@ -2575,6 +2784,7 @@ "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", "dev": true, + "license": "MIT", "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.4" @@ -2587,13 +2797,15 @@ "version": "3.3.1", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.1.tgz", "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/form-data": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", "dev": true, + "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", @@ -2608,6 +2820,7 @@ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", "dev": true, + "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -2616,6 +2829,7 @@ "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", "engines": { "node": "6.* || 8.* || >= 10.*" } @@ -2625,6 +2839,7 @@ "resolved": "https://registry.npmjs.org/get-pkg-repo/-/get-pkg-repo-4.2.1.tgz", "integrity": "sha512-2+QbHjFRfGB74v/pYWjd5OhU3TDIC2Gv/YKUTk/tCvAz0pkn/Mz6P3uByuBimLOcPvN2jYdScl3xGFSrx0jEcA==", "dev": true, + "license": "MIT", "dependencies": { "@hutson/parse-repository-url": "^3.0.0", "hosted-git-info": "^4.0.0", @@ -2643,6 +2858,7 @@ "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, + "license": "ISC", "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", @@ -2654,6 +2870,7 @@ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, + "license": "MIT", "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -2668,13 +2885,15 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/get-pkg-repo/node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, + "license": "MIT", "dependencies": { "safe-buffer": "~5.1.0" } @@ -2684,6 +2903,7 @@ "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", "dev": true, + "license": "MIT", "dependencies": { "readable-stream": "~2.3.6", "xtend": "~4.0.1" @@ -2694,6 +2914,7 @@ "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", "dev": true, + "license": "MIT", "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", @@ -2712,6 +2933,7 @@ "resolved": "https://registry.npmjs.org/git-raw-commits/-/git-raw-commits-2.0.11.tgz", "integrity": "sha512-VnctFhw+xfj8Va1xtfEqCUD2XDrbAPSJx+hSrE5K7fGdjZruW7XV+QOrN7LF/RJyvspRiD2I0asWsxFp0ya26A==", "dev": true, + "license": "MIT", "dependencies": { "dargs": "^7.0.0", "lodash": "^4.17.15", @@ -2731,6 +2953,7 @@ "resolved": "https://registry.npmjs.org/git-remote-origin-url/-/git-remote-origin-url-2.0.0.tgz", "integrity": "sha512-eU+GGrZgccNJcsDH5LkXR3PB9M958hxc7sbA8DFJjrv9j4L2P/eZfKhM+QD6wyzpiv+b1BpK0XrYCxkovtjSLw==", "dev": true, + "license": "MIT", "dependencies": { "gitconfiglocal": "^1.0.0", "pify": "^2.3.0" @@ -2744,6 +2967,7 @@ "resolved": "https://registry.npmjs.org/git-semver-tags/-/git-semver-tags-5.0.1.tgz", "integrity": "sha512-hIvOeZwRbQ+7YEUmCkHqo8FOLQZCEn18yevLHADlFPZY02KJGsu5FZt9YW/lybfK2uhWFI7Qg/07LekJiTv7iA==", "dev": true, + "license": "MIT", "dependencies": { "meow": "^8.1.2", "semver": "^7.0.0" @@ -2760,6 +2984,7 @@ "resolved": "https://registry.npmjs.org/gitconfiglocal/-/gitconfiglocal-1.0.0.tgz", "integrity": "sha512-spLUXeTAVHxDtKsJc8FkFVgFtMdEN9qPGpL23VfSHx4fP4+Ds097IXLvymbnDH8FnmxX5Nr9bPw3A+AQ6mWEaQ==", "dev": true, + "license": "BSD", "dependencies": { "ini": "^1.3.2" } @@ -2769,6 +2994,7 @@ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "dev": true, + "license": "ISC", "dependencies": { "is-glob": "^4.0.3" }, @@ -2777,10 +3003,11 @@ } }, "node_modules/globals": { - "version": "15.4.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-15.4.0.tgz", - "integrity": "sha512-unnwvMZpv0eDUyjNyh9DH/yxUaRYrEjW/qK4QcdrHg3oO11igUQrCSgODHEqxlKg8v2CD2Sd7UkqqEBoz5U7TQ==", + "version": "15.6.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-15.6.0.tgz", + "integrity": "sha512-UzcJi88Hw//CurUIRa9Jxb0vgOCcuD/MNjwmXp633cyaRKkCWACkoqHCtfZv43b1kqXGg/fpOa8bwgacCeXsVg==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -2792,13 +3019,15 @@ "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/handlebars": { "version": "4.7.8", "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz", "integrity": "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==", "dev": true, + "license": "MIT", "dependencies": { "minimist": "^1.2.5", "neo-async": "^2.6.2", @@ -2820,6 +3049,7 @@ "resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz", "integrity": "sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -2829,6 +3059,7 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -2838,6 +3069,7 @@ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", "dev": true, + "license": "MIT", "dependencies": { "function-bind": "^1.1.2" }, @@ -2850,6 +3082,7 @@ "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==", "dev": true, + "license": "ISC", "dependencies": { "lru-cache": "^6.0.0" }, @@ -2862,6 +3095,7 @@ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", "dev": true, + "license": "MIT", "dependencies": { "whatwg-encoding": "^3.1.1" }, @@ -2872,13 +3106,15 @@ "node_modules/http-parser-js": { "version": "0.5.8", "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.8.tgz", - "integrity": "sha512-SGeBX54F94Wgu5RH3X5jsDtf4eHyRogWX1XGT3b4HuW3tQPM4AaBzoUji/4AAJNXCEOWZ5O0DgZmJw1947gD5Q==" + "integrity": "sha512-SGeBX54F94Wgu5RH3X5jsDtf4eHyRogWX1XGT3b4HuW3tQPM4AaBzoUji/4AAJNXCEOWZ5O0DgZmJw1947gD5Q==", + "license": "MIT" }, "node_modules/http-proxy-agent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", "dev": true, + "license": "MIT", "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" @@ -2888,10 +3124,11 @@ } }, "node_modules/https-proxy-agent": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.4.tgz", - "integrity": "sha512-wlwpilI7YdjSkWaQ/7omYBMTliDcmCN8OLihO6I9B86g06lMyAoqgoDpV0XqoaPOKj+0DIdAvnsWfyAAhmimcg==", + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", + "integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==", "dev": true, + "license": "MIT", "dependencies": { "agent-base": "^7.0.2", "debug": "4" @@ -2905,6 +3142,7 @@ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", "dev": true, + "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" }, @@ -2915,13 +3153,15 @@ "node_modules/idb": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz", - "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==" + "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==", + "license": "ISC" }, "node_modules/ignore": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.1.tgz", "integrity": "sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw==", "dev": true, + "license": "MIT", "engines": { "node": ">= 4" } @@ -2931,6 +3171,7 @@ "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", "dev": true, + "license": "MIT", "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" @@ -2947,6 +3188,7 @@ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.8.19" } @@ -2956,6 +3198,7 @@ "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -2964,27 +3207,34 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/ini": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/is-core-module": { - "version": "2.13.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", - "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.14.0.tgz", + "integrity": "sha512-a5dFJih5ZLYlRtDc0dZWP7RiKr6xIKzmn/oAYCDvdLThadVgyJwlaoQPmRtMSpz+rk0OGAgIu+TcM9HUF0fk1A==", "dev": true, + "license": "MIT", "dependencies": { - "hasown": "^2.0.0" + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -2995,6 +3245,7 @@ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -3003,6 +3254,7 @@ "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", "engines": { "node": ">=8" } @@ -3012,6 +3264,7 @@ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, + "license": "MIT", "dependencies": { "is-extglob": "^2.1.1" }, @@ -3024,6 +3277,7 @@ "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -3033,6 +3287,7 @@ "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -3042,6 +3297,7 @@ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", "integrity": "sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -3050,13 +3306,15 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/is-text-path": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-text-path/-/is-text-path-1.0.1.tgz", "integrity": "sha512-xFuJpne9oFz5qDaodwmmG08e3CawH/2ZV8Qqza1Ko7Sk8POWbkRdwIoAWVhqvq0XeUzANEhKo2n0IXUGBm7A/w==", "dev": true, + "license": "MIT", "dependencies": { "text-extensions": "^1.0.0" }, @@ -3068,25 +3326,29 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/js-yaml": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "dev": true, + "license": "MIT", "dependencies": { "argparse": "^2.0.1" }, @@ -3099,6 +3361,7 @@ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-23.2.0.tgz", "integrity": "sha512-L88oL7D/8ufIES+Zjz7v0aes+oBMh2Xnh3ygWvL0OaICOomKEPKuPnIfBJekiXr+BHbbMjrWn/xqrDQuxFTeyA==", "dev": true, + "license": "MIT", "dependencies": { "@asamuzakjp/dom-selector": "^2.0.1", "cssstyle": "^4.0.1", @@ -3138,37 +3401,43 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/json-parse-better-errors": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/jsonparse": { "version": "1.3.1", @@ -3177,13 +3446,15 @@ "dev": true, "engines": [ "node >= 0.2.0" - ] + ], + "license": "MIT" }, "node_modules/JSONStream": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", "dev": true, + "license": "(MIT OR Apache-2.0)", "dependencies": { "jsonparse": "^1.2.0", "through": ">=2.2.7 <3" @@ -3200,6 +3471,7 @@ "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", "dev": true, + "license": "MIT", "dependencies": { "json-buffer": "3.0.1" } @@ -3209,6 +3481,7 @@ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -3218,6 +3491,7 @@ "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, + "license": "MIT", "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" @@ -3230,13 +3504,15 @@ "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/load-json-file": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", "integrity": "sha512-Kx8hMakjX03tiGTLAIdJ+lL0htKnXjEZN6hk/tozf/WOuYGdZBJrZ+rCJRbVCugsjB3jMLn9746NsQIf5VjBMw==", "dev": true, + "license": "MIT", "dependencies": { "graceful-fs": "^4.1.2", "parse-json": "^4.0.0", @@ -3252,6 +3528,7 @@ "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -3261,6 +3538,7 @@ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, + "license": "MIT", "dependencies": { "p-locate": "^5.0.0" }, @@ -3275,35 +3553,41 @@ "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true + "dev": true, + "license": "MIT" }, "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==" + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT" }, "node_modules/lodash.ismatch": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/lodash.ismatch/-/lodash.ismatch-4.4.0.tgz", "integrity": "sha512-fPMfXjGQEV9Xsq/8MTSgUf255gawYRbjwMyDbcvDhXgV7enSZA0hynz6vMPnpAb5iONEzBHBPsT+0zes5Z301g==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/long": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz", - "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==" + "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==", + "license": "Apache-2.0" }, "node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", "dev": true, + "license": "ISC", "dependencies": { "yallist": "^4.0.0" }, @@ -3316,6 +3600,7 @@ "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-4.3.0.tgz", "integrity": "sha512-hdN1wVrZbb29eBGiGjJbeP8JbKjq1urkHJ/LIP/NY48MZ1QVXUsQBV1G1zvYFHn1XE06cwjBsOI2K3Ulnj1YXQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" }, @@ -3327,13 +3612,15 @@ "version": "2.0.30", "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.30.tgz", "integrity": "sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==", - "dev": true + "dev": true, + "license": "CC0-1.0" }, "node_modules/meow": { "version": "8.1.2", "resolved": "https://registry.npmjs.org/meow/-/meow-8.1.2.tgz", "integrity": "sha512-r85E3NdZ+mpYk1C6RjPFEMSE+s1iZMuHtsHAqY0DT3jZczl0diWUZ8g6oU7h0M9cD2EL+PzaYghhCLzR0ZNn5Q==", "dev": true, + "license": "MIT", "dependencies": { "@types/minimist": "^1.2.0", "camelcase-keys": "^6.2.2", @@ -3359,6 +3646,7 @@ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, + "license": "MIT", "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" @@ -3371,13 +3659,15 @@ "version": "2.8.9", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/meow/node_modules/locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, + "license": "MIT", "dependencies": { "p-locate": "^4.1.0" }, @@ -3390,6 +3680,7 @@ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, + "license": "MIT", "dependencies": { "p-try": "^2.0.0" }, @@ -3405,6 +3696,7 @@ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, + "license": "MIT", "dependencies": { "p-limit": "^2.2.0" }, @@ -3417,6 +3709,7 @@ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", "dev": true, + "license": "MIT", "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", @@ -3435,6 +3728,7 @@ "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", "integrity": "sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==", "dev": true, + "license": "MIT", "dependencies": { "@types/normalize-package-data": "^2.4.0", "normalize-package-data": "^2.5.0", @@ -3450,6 +3744,7 @@ "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-7.0.1.tgz", "integrity": "sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg==", "dev": true, + "license": "MIT", "dependencies": { "find-up": "^4.1.0", "read-pkg": "^5.2.0", @@ -3467,6 +3762,7 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", "dev": true, + "license": "(MIT OR CC0-1.0)", "engines": { "node": ">=8" } @@ -3476,6 +3772,7 @@ "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "hosted-git-info": "^2.1.4", "resolve": "^1.10.0", @@ -3488,6 +3785,7 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz", "integrity": "sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==", "dev": true, + "license": "(MIT OR CC0-1.0)", "engines": { "node": ">=8" } @@ -3497,6 +3795,7 @@ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", "dev": true, + "license": "ISC", "bin": { "semver": "bin/semver" } @@ -3506,6 +3805,7 @@ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -3515,6 +3815,7 @@ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, + "license": "MIT", "dependencies": { "mime-db": "1.52.0" }, @@ -3527,6 +3828,7 @@ "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -3536,6 +3838,7 @@ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, + "license": "ISC", "dependencies": { "brace-expansion": "^1.1.7" }, @@ -3548,6 +3851,7 @@ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", "dev": true, + "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -3557,6 +3861,7 @@ "resolved": "https://registry.npmjs.org/minimist-options/-/minimist-options-4.1.0.tgz", "integrity": "sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A==", "dev": true, + "license": "MIT", "dependencies": { "arrify": "^1.0.1", "is-plain-obj": "^1.1.0", @@ -3571,6 +3876,7 @@ "resolved": "https://registry.npmjs.org/modify-values/-/modify-values-1.0.1.tgz", "integrity": "sha512-xV2bxeN6F7oYjZWTe/YPAy6MN2M+sL4u/Rlm2AHCIVGfo2p1yGmBHQ6vHehl4bRTZBdHu3TSkWdYgkwpYzAGSw==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -3579,25 +3885,29 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/neo-async": { "version": "2.6.2", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/normalize-package-data": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-3.0.3.tgz", "integrity": "sha512-p2W1sgqij3zMMyRC067Dg16bfzVH+w7hyegmpIvZ4JNjqtGOVAIvLmjBx3yP7YTe9vKJgkoNOPjwQGogDoMXFA==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "hosted-git-info": "^4.0.1", "is-core-module": "^2.5.0", @@ -3612,13 +3922,15 @@ "version": "8.0.1", "resolved": "https://registry.npmjs.org/normalize.css/-/normalize.css-8.0.1.tgz", "integrity": "sha512-qizSNPO93t1YUuUhP22btGOo3chcvDFqFaj2TRybP0DMxkHOCTYwp3n34fel4a31ORXy4m1Xq0Gyqpb5m33qIg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", "dev": true, + "license": "MIT", "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", @@ -3636,6 +3948,7 @@ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, + "license": "MIT", "dependencies": { "yocto-queue": "^0.1.0" }, @@ -3651,6 +3964,7 @@ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "dev": true, + "license": "MIT", "dependencies": { "p-limit": "^3.0.2" }, @@ -3666,6 +3980,7 @@ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -3675,6 +3990,7 @@ "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", "dev": true, + "license": "MIT", "dependencies": { "callsites": "^3.0.0" }, @@ -3687,6 +4003,7 @@ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", "integrity": "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw==", "dev": true, + "license": "MIT", "dependencies": { "error-ex": "^1.3.1", "json-parse-better-errors": "^1.0.1" @@ -3700,6 +4017,7 @@ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", "dev": true, + "license": "MIT", "dependencies": { "entities": "^4.4.0" }, @@ -3712,6 +4030,7 @@ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -3721,6 +4040,7 @@ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -3729,13 +4049,15 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/path-type": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", "dev": true, + "license": "MIT", "dependencies": { "pify": "^3.0.0" }, @@ -3748,6 +4070,7 @@ "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -3756,13 +4079,15 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/pify": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -3772,6 +4097,7 @@ "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true, + "license": "MIT", "engines": { "node": ">= 0.8.0" } @@ -3780,13 +4106,15 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/protobufjs": { "version": "7.3.2", "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.3.2.tgz", "integrity": "sha512-RXyHaACeqXeqAKGLDl68rQKbmObRsTIn4TYVUUug1KfS47YWCo5MacGITEryugIgZqORCvJWEk4l449POg5Txg==", "hasInstallScript": true, + "license": "BSD-3-Clause", "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", @@ -3809,13 +4137,15 @@ "version": "1.9.0", "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -3826,6 +4156,7 @@ "integrity": "sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw==", "deprecated": "You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other.\n\n(For a CapTP with native promises, see @endo/eventual-send and @endo/captp)", "dev": true, + "license": "MIT", "engines": { "node": ">=0.6.0", "teleport": ">=0.2.0" @@ -3835,7 +4166,8 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/queue-microtask": { "version": "1.2.3", @@ -3855,13 +4187,15 @@ "type": "consulting", "url": "https://feross.org/support" } - ] + ], + "license": "MIT" }, "node_modules/quick-lru": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-4.0.1.tgz", "integrity": "sha512-ARhCpm70fzdcvNQfPoy49IaanKkTlRWF2JMzqhcJbhSFRZv7nPTvZJdcY7301IPmvW+/p0RgIWnQDLJxifsQ7g==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -3871,6 +4205,7 @@ "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", "integrity": "sha512-BLq/cCO9two+lBgiTYNqD6GdtK8s4NpaWrl6/rCO9w0TUS8oJl7cmToOZfRYllKTISY6nt1U7jQ53brmKqY6BA==", "dev": true, + "license": "MIT", "dependencies": { "load-json-file": "^4.0.0", "normalize-package-data": "^2.3.2", @@ -3885,6 +4220,7 @@ "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", "integrity": "sha512-YFzFrVvpC6frF1sz8psoHDBGF7fLPc+llq/8NB43oagqWkx8ar5zYtsTORtOjw9W2RHLpWP+zTWwBvf1bCmcSw==", "dev": true, + "license": "MIT", "dependencies": { "find-up": "^2.0.0", "read-pkg": "^3.0.0" @@ -3898,6 +4234,7 @@ "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", "integrity": "sha512-NWzkk0jSJtTt08+FBFMvXoeZnOJD+jTtsRmBYbAIzJdX6l7dLgR7CTubCM5/eDdPUBvLCeVasP1brfVR/9/EZQ==", "dev": true, + "license": "MIT", "dependencies": { "locate-path": "^2.0.0" }, @@ -3910,6 +4247,7 @@ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", "integrity": "sha512-NCI2kiDkyR7VeEKm27Kda/iQHyKJe1Bu0FlTbYp3CqJu+9IFe9bLyAjMxf5ZDDbEg+iMPzB5zYyUTSm8wVTKmA==", "dev": true, + "license": "MIT", "dependencies": { "p-locate": "^2.0.0", "path-exists": "^3.0.0" @@ -3923,6 +4261,7 @@ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", "dev": true, + "license": "MIT", "dependencies": { "p-try": "^1.0.0" }, @@ -3935,6 +4274,7 @@ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", "integrity": "sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg==", "dev": true, + "license": "MIT", "dependencies": { "p-limit": "^1.1.0" }, @@ -3947,6 +4287,7 @@ "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", "integrity": "sha512-U1etNYuMJoIz3ZXSrrySFjsXQTWOx2/jdi86L+2pRvph/qMKL6sbcCYdH23fqsbm8TH2Gn0OybpT4eSFlCVHww==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -3956,6 +4297,7 @@ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -3964,13 +4306,15 @@ "version": "2.8.9", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/read-pkg/node_modules/normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "hosted-git-info": "^2.1.4", "resolve": "^1.10.0", @@ -3983,6 +4327,7 @@ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", "dev": true, + "license": "ISC", "bin": { "semver": "bin/semver" } @@ -3992,6 +4337,7 @@ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", "dev": true, + "license": "MIT", "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", @@ -4006,6 +4352,7 @@ "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", "dev": true, + "license": "MIT", "dependencies": { "indent-string": "^4.0.0", "strip-indent": "^3.0.0" @@ -4018,6 +4365,7 @@ "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", "engines": { "node": ">=0.10.0" } @@ -4027,6 +4375,7 @@ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -4035,13 +4384,15 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/resolve": { "version": "1.22.8", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", "dev": true, + "license": "MIT", "dependencies": { "is-core-module": "^2.13.0", "path-parse": "^1.0.7", @@ -4059,6 +4410,7 @@ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -4068,24 +4420,24 @@ "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", "dev": true, + "license": "MIT", "engines": { "iojs": ">=1.0.0", "node": ">=0.10.0" } }, "node_modules/rpg-table-randomizer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/rpg-table-randomizer/-/rpg-table-randomizer-1.4.0.tgz", - "integrity": "sha512-Hh2iUKOvJq7yYTj+oWk63oI5OglZo6Oub4zmBMF4a5wAHxI1TObLQAXh/ygCQyCoJi27vPmzLQDZCoETTGh20A==", - "dependencies": { - "uuid": "^9.0.0" - } + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/rpg-table-randomizer/-/rpg-table-randomizer-1.5.0.tgz", + "integrity": "sha512-73v7ng090r2kE9ZyWx2wCL9GuU6SyudtuIS4idtN7BxFye3H0pWXPZ+E2SAarT8wYq9zSucJqkxbqZxACsRn/g==", + "license": "GPL-3.0" }, "node_modules/rrweb-cssom": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.6.0.tgz", "integrity": "sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/run-parallel": { "version": "1.2.0", @@ -4106,6 +4458,7 @@ "url": "https://feross.org/support" } ], + "license": "MIT", "dependencies": { "queue-microtask": "^1.2.2" } @@ -4127,19 +4480,22 @@ "type": "consulting", "url": "https://feross.org/support" } - ] + ], + "license": "MIT" }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", "dev": true, + "license": "ISC", "dependencies": { "xmlchars": "^2.2.0" }, @@ -4152,6 +4508,7 @@ "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", "dev": true, + "license": "ISC", "bin": { "semver": "bin/semver.js" }, @@ -4164,6 +4521,7 @@ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, + "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" }, @@ -4176,6 +4534,7 @@ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -4185,6 +4544,7 @@ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, + "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } @@ -4194,6 +4554,7 @@ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.0.tgz", "integrity": "sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg==", "dev": true, + "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } @@ -4203,6 +4564,7 @@ "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", "integrity": "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==", "dev": true, + "license": "Apache-2.0", "dependencies": { "spdx-expression-parse": "^3.0.0", "spdx-license-ids": "^3.0.0" @@ -4212,13 +4574,15 @@ "version": "2.5.0", "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", - "dev": true + "dev": true, + "license": "CC-BY-3.0" }, "node_modules/spdx-expression-parse": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", "dev": true, + "license": "MIT", "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" @@ -4228,13 +4592,15 @@ "version": "3.0.18", "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.18.tgz", "integrity": "sha512-xxRs31BqRYHwiMzudOrpSiHtZ8i/GeionCBDSilhYRj+9gIcI8wCZTlXZKu9vZIVqViP3dcp9qE5G6AlIaD+TQ==", - "dev": true + "dev": true, + "license": "CC0-1.0" }, "node_modules/split": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==", "dev": true, + "license": "MIT", "dependencies": { "through": "2" }, @@ -4247,6 +4613,7 @@ "resolved": "https://registry.npmjs.org/split2/-/split2-3.2.2.tgz", "integrity": "sha512-9NThjpgZnifTkJpzTZ7Eue85S49QwpNhZTq6GRJwObb6jnLFNGB7Qm73V5HewTROPyxD0C29xqmaI68bQtV+hg==", "dev": true, + "license": "ISC", "dependencies": { "readable-stream": "^3.0.0" } @@ -4256,6 +4623,7 @@ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", "dev": true, + "license": "MIT", "dependencies": { "safe-buffer": "~5.2.0" } @@ -4264,6 +4632,7 @@ "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", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -4277,6 +4646,7 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -4289,6 +4659,7 @@ "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -4298,6 +4669,7 @@ "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", "dev": true, + "license": "MIT", "dependencies": { "min-indent": "^1.0.0" }, @@ -4310,6 +4682,7 @@ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" }, @@ -4322,6 +4695,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^3.0.0" }, @@ -4334,6 +4708,7 @@ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", "dev": true, + "license": "MIT", "engines": { "node": ">= 0.4" }, @@ -4345,13 +4720,15 @@ "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/text-extensions": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/text-extensions/-/text-extensions-1.9.0.tgz", "integrity": "sha512-wiBrwC1EhBelW12Zy26JeOUkQ5mRu+5o8rpsJk5+2t+Y5vE7e842qtZDQ2g1NpX/29HdyFeJ4nSIhI47ENSxlQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10" } @@ -4360,19 +4737,22 @@ "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/through": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/through2": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", "dev": true, + "license": "MIT", "dependencies": { "readable-stream": "3" } @@ -4382,6 +4762,7 @@ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { "psl": "^1.1.33", "punycode": "^2.1.1", @@ -4397,6 +4778,7 @@ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.0.0.tgz", "integrity": "sha512-tk2G5R2KRwBd+ZN0zaEXpmzdKyOYksXwywulIX95MBODjSzMIuQnQ3m8JxgbhnL1LeVo7lqQKsYa1O3Htl7K5g==", "dev": true, + "license": "MIT", "dependencies": { "punycode": "^2.3.1" }, @@ -4409,6 +4791,7 @@ "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-3.0.1.tgz", "integrity": "sha512-c1PTsA3tYrIsLGkJkzHF+w9F2EyxfXGo4UyJc4pFL++FMjnq0HJS69T3M7d//gKrFKwy429bouPescbjecU+Zw==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -4416,13 +4799,15 @@ "node_modules/tslib": { "version": "2.6.3", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz", - "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==" + "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==", + "license": "0BSD" }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, + "license": "MIT", "dependencies": { "prelude-ls": "^1.2.1" }, @@ -4435,6 +4820,7 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.18.1.tgz", "integrity": "sha512-OIAYXk8+ISY+qTOwkHtKqzAuxchoMiD9Udx+FSGQDuiRR+PJKJHc2NJAXlbhkGwTt/4/nKZxELY1w3ReWOL8mw==", "dev": true, + "license": "(MIT OR CC0-1.0)", "engines": { "node": ">=10" }, @@ -4446,13 +4832,15 @@ "version": "0.0.6", "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/uglify-js": { "version": "3.18.0", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.18.0.tgz", "integrity": "sha512-SyVVbcNBCk0dzr9XL/R/ySrmYf0s372K6/hFklzgcp2lBFyXtw4I7BOdDjlLhE1aVqaI/SHWXWmYdlZxuyF38A==", "dev": true, + "license": "BSD-2-Clause", "optional": true, "bin": { "uglifyjs": "bin/uglifyjs" @@ -4465,6 +4853,7 @@ "version": "5.28.4", "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz", "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", + "license": "MIT", "dependencies": { "@fastify/busboy": "^2.0.0" }, @@ -4475,13 +4864,15 @@ "node_modules/undici-types": { "version": "5.26.5", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "license": "MIT" }, "node_modules/universalify": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", "dev": true, + "license": "MIT", "engines": { "node": ">= 4.0.0" } @@ -4491,6 +4882,7 @@ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", "dev": true, + "license": "BSD-2-Clause", "dependencies": { "punycode": "^2.1.0" } @@ -4500,6 +4892,7 @@ "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", "dev": true, + "license": "MIT", "dependencies": { "querystringify": "^2.1.1", "requires-port": "^1.0.0" @@ -4509,25 +4902,15 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true - }, - "node_modules/uuid": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", - "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "bin": { - "uuid": "dist/bin/uuid" - } + "dev": true, + "license": "MIT" }, "node_modules/validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", "dev": true, + "license": "Apache-2.0", "dependencies": { "spdx-correct": "^3.0.0", "spdx-expression-parse": "^3.0.0" @@ -4538,6 +4921,7 @@ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", "dev": true, + "license": "MIT", "dependencies": { "xml-name-validator": "^5.0.0" }, @@ -4550,6 +4934,7 @@ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", "dev": true, + "license": "BSD-2-Clause", "engines": { "node": ">=12" } @@ -4558,6 +4943,7 @@ "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", @@ -4571,6 +4957,7 @@ "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" } @@ -4580,6 +4967,7 @@ "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", "dev": true, + "license": "MIT", "dependencies": { "iconv-lite": "0.6.3" }, @@ -4592,6 +4980,7 @@ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" } @@ -4601,6 +4990,7 @@ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.0.0.tgz", "integrity": "sha512-1lfMEm2IEr7RIV+f4lUNPOqfFL+pO+Xw3fJSqmjX9AbXcXcYOkCe1P6+9VBZB6n94af16NfZf+sSk0JCBZC9aw==", "dev": true, + "license": "MIT", "dependencies": { "tr46": "^5.0.0", "webidl-conversions": "^7.0.0" @@ -4614,6 +5004,7 @@ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, + "license": "ISC", "dependencies": { "isexe": "^2.0.0" }, @@ -4629,6 +5020,7 @@ "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -4637,12 +5029,14 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", - "dev": true + "dev": true, + "license": "MIT" }, "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", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -4659,6 +5053,7 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -4673,6 +5068,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", "dependencies": { "color-name": "~1.1.4" }, @@ -4683,13 +5079,15 @@ "node_modules/wrap-ansi/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==" + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" }, "node_modules/ws": { - "version": "8.17.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.0.tgz", - "integrity": "sha512-uJq6108EgZMAl20KagGkzCKfMEjxmKvZHG7Tlq0Z6nOky7YF7aq4mOx6xK8TJ/i1LeK4Qus7INktacctDgY8Ow==", + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=10.0.0" }, @@ -4711,6 +5109,7 @@ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", "dev": true, + "license": "Apache-2.0", "engines": { "node": ">=18" } @@ -4719,13 +5118,15 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.4" } @@ -4734,6 +5135,7 @@ "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", "engines": { "node": ">=10" } @@ -4742,13 +5144,15 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/yaml": { "version": "2.4.5", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.4.5.tgz", "integrity": "sha512-aBx2bnqDzVOyNKfsysjA2ms5ZlnjSAW2eG3/L5G/CSujfjLJTJsEw1bGw8kCf04KodQWk1pxlGnZ56CRxiawmg==", "dev": true, + "license": "ISC", "bin": { "yaml": "bin.mjs" }, @@ -4760,6 +5164,7 @@ "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", @@ -4778,6 +5183,7 @@ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", "dev": true, + "license": "ISC", "engines": { "node": ">=10" } @@ -4786,6 +5192,7 @@ "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", "engines": { "node": ">=12" } @@ -4795,6 +5202,7 @@ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=10" }, diff --git a/package.json b/package.json index 3fbfe8a..7d9ef28 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "character-sheet-app", - "version": "4.5.2", + "version": "4.5.3", "description": "Online character sheet for Tabletop Role-Playing Games", "repository": { "type": "git",