diff --git a/dist/0.3.10/mavo-firebase-firestore.css b/dist/0.3.10/mavo-firebase-firestore.css new file mode 100644 index 0000000..0014e11 --- /dev/null +++ b/dist/0.3.10/mavo-firebase-firestore.css @@ -0,0 +1,4 @@ +.mv-bar.mv-ui button[class*="mv-firebase-auth"]::before { + content: "🔑 "; + filter: brightness(160%) grayscale(100%); +} diff --git a/dist/0.3.10/mavo-firebase-firestore.es5.js b/dist/0.3.10/mavo-firebase-firestore.es5.js new file mode 100644 index 0000000..1966e1e --- /dev/null +++ b/dist/0.3.10/mavo-firebase-firestore.es5.js @@ -0,0 +1,537 @@ +"use strict"; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +// @ts-check + +/** + * Firebase backend plugin for Mavo + * @author Dmitry Sharabin and contributors + * @version v0.3.10 + */ +(function ($) { + "use strict"; + + const PROVIDERS = { + "google": {}, + "facebook": {}, + "twitter": {}, + "github": {} + }; // Deprecated attributes: + // deprecated -> new attribute, url for help + + const DEPRECATED = { + "mv-firebase-key": { + attribute: "mv-storage-key", + url: "https://plugins.mavo.io/plugin/firebase-firestore#setup-mavo-application" + }, + "mv-firebase-auth": { + attribute: "mv-storage-providers", + url: "https://plugins.mavo.io/plugin/firebase-firestore#authentication-with-firebase-using-google-facebook-twitter-or-github-accounts" + }, + "mv-firebase": { + attribute: "mv-storage-options", + url: "https://plugins.mavo.io/plugin/firebase-firestore#customization" + }, + "mv-firebase-storage": { + attribute: "mv-storage-bucketname", + url: "https://plugins.mavo.io/plugin/firebase-firestore#customization" + } + }; + Mavo.Plugins.register("firebase-firestore", { + dependencies: ["https://cdn.jsdelivr.net/gh/DmitrySharabin/mavo-firebase-firestore/mavo-firebase-firestore.css"], + hooks: { + "init-start": function initStart(mavo) { + // Add buttons for auth providers to the Mavo bar + // Show them only if the Firebase backend is used and any auth provider is specified + Object.keys(PROVIDERS).forEach(p => { + const id = "firebase-auth-".concat(p); + Mavo.UI.Bar.controls[id] = { + create(custom) { + return custom || $.create("button", { + type: "button", + className: "mv-".concat(id), + textContent: mavo._(id) + }); + }, + + action() { + mavo.primaryBackend.provider = p; + mavo.primaryBackend.login(false); + }, + + permission: "login", + + condition() { + var _mavo$primaryBackend$, _mavo$primaryBackend$2; + + return Boolean(mavo.primaryBackend.project) && ((_mavo$primaryBackend$ = mavo.primaryBackend.authProviders) === null || _mavo$primaryBackend$ === void 0 ? void 0 : (_mavo$primaryBackend$2 = _mavo$primaryBackend$.includes) === null || _mavo$primaryBackend$2 === void 0 ? void 0 : _mavo$primaryBackend$2.call(_mavo$primaryBackend$, p)); + } + + }; + }); // Hide the Login button if either of auth providers is specified + + $.extend(Mavo.UI.Bar.controls.login, { + condition() { + var _mavo$primaryBackend$3; + + return Boolean(mavo.primaryBackend.project) ? !((_mavo$primaryBackend$3 = mavo.primaryBackend.authProviders) === null || _mavo$primaryBackend$3 === void 0 ? void 0 : _mavo$primaryBackend$3.length) : mavo.primaryBackend.permissions.login; + } + + }); + } + } + }); + + const _ = Mavo.Backend.register(class Firebase extends Mavo.Backend { + constructor(url, o) { + super(url, o); // Initialization code + + _defineProperty(this, "id", "Firebase"); + + this.permissions.on("read"); + this.defaults = { + collection: "mavo-apps", + filename: o.mavo.id, + bucketName: o.bucketname || o.mavo.element.getAttribute("mv-firebase-storage") || o.mavo.id, + features: { + auth: false, + storage: false, + realtime: false, + "offline-persistence": false, + "all-can-write": false, + "all-can-edit": false + }, + authProviders: _.getAuthProviders(o.providers || o.mavo.element.getAttribute("mv-firebase-auth") || "", PROVIDERS), + provider: undefined + }; + $.extend(this, this.defaults); // Warn an author about deprecated attributes + + for (const attribute in DEPRECATED) { + if (o.mavo.element.hasAttribute(attribute)) { + const newAttribute = DEPRECATED[attribute].attribute; + const url = DEPRECATED[attribute].url; + Mavo.warn("@".concat(attribute, " is deprecated. Please use @").concat(newAttribute, " instead. For details, see ").concat(url, ".")); + } + } // Which backend features should we support? + + + const template = o.options || o.mavo.element.getAttribute("mv-firebase") || ""; + this.features = _.getOptions(template, this.defaults.features); // If either of the auth providers is specified, we must enable the auth feature + + if (this.authProviders.length) { + this.features.auth = true; + } + + if (this.features.auth) { + this.permissions.on("login"); // If none of the auth providers is specified, by default Google is used + + if (!this.authProviders.length) { + this.provider = "google"; + } + } else { + this.permissions.on(["edit", "save"]); + } + + this.ready = // First of all, we need to download the Firebase core file + $.load("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js").then(async () => { + var _o$project, _o$collection, _o$filename, _this$key; + + // Then download the other parts if needed + await Promise.all([// Cloud Firestore + $.load("https://www.gstatic.com/firebasejs/8.2.0/firebase-firestore.js"), // Cloud Storage + $.include(!this.features.storage, "https://www.gstatic.com/firebasejs/8.2.0/firebase-storage.js"), // Authentication + $.include(!this.features.auth, "https://www.gstatic.com/firebasejs/8.2.0/firebase-auth.js")]); // Get the config info from the attribute value + + $.extend(this, _.parseSource(this.source, this.defaults)); // If an author provided backend metadata, use them + // since they have higher priority + + this.project = (_o$project = o.project) !== null && _o$project !== void 0 ? _o$project : this.project; + this.collection = (_o$collection = o.collection) !== null && _o$collection !== void 0 ? _o$collection : this.collection; + this.filename = (_o$filename = o.filename) !== null && _o$filename !== void 0 ? _o$filename : this.filename; // The app's Firebase configuration + + const config = { + apiKey: (_this$key = this.key) !== null && _this$key !== void 0 ? _this$key : o.mavo.element.getAttribute("mv-firebase-key"), + databaseURL: "https://".concat(this.project, ".firebaseio.com"), + projectId: this.project, + authDomain: "".concat(this.project, ".firebaseapp.com"), + storageBucket: "".concat(this.project, ".appspot.com") + }; // Initialize Cloud Firestore through Firebase + // We want all mavo apps with the same project ID share the same instance of Firebase app + // If there is no previously created Firebase app with the specified project ID, create one + + if (!firebase.apps.length) { + this.app = firebase.initializeApp(config); + } else { + this.app = firebase.apps.find(app => app.options.projectId === this.project) || firebase.initializeApp(config, this.project); + } + + if (this.features["offline-persistence"]) { + // To allow offline persistence, we MUST enable it foremost and only once + // Offline persistence is supported only by Chrome, Safari, and Firefox web browsers + try { + this.app.firestore().enablePersistence({ + synchronizeTabs: true + }); + } catch (error) { + if (error.code === "unimplemented") { + // The current browser does not support all of the + // features required to enable persistence + Mavo.warn(this.mavo._("firebase-offline-persistence-unimplemented")); + this.mavo.error("Firebase Offline Persistence: ".concat(error.message)); + } + } + } + + this.db = this.app.firestore().collection(this.collection); + + if (this.features.realtime) { + // Get realtime updates + this.unsubscribe = this.db.doc(this.filename).onSnapshot(doc => this.updatesHandler(doc), error => o.mavo.error("Firebase Realtime: ".concat(error.message))); + } else if (this.unsubscribe) { + // Stop listening to changes + this.unsubscribe(); + } + + if (this.features.storage) { + // Get a reference to the storage service, which is used to create references in the storage bucket, + // and create a storage reference from the storage service + this.storageBucketRef = this.app.storage().ref(); + } + + if (this.features.auth) { + const defaultPermissions = ["login"]; // By default, if the authentication feature is on, only signed-in users can edit and save the app's data. + // We want to let authors granularly override the default behavior, + // and we could enable the corresponding permissions + + if (this.features["all-can-write"]) { + defaultPermissions.push("save"); + } + + if (this.features["all-can-edit"]) { + defaultPermissions.push("edit"); + } // Set an authentication state observer and get user data + + + this.app.auth().onAuthStateChanged(user => { + if (user) { + // User is signed in + this.user = { + username: user.email, + name: user.displayName, + avatar: user.photoURL, + info: user // raw user object + + }; // Make the plugin work both with stable and future versions of Mavo. + + if (this instanceof EventTarget) { + $.fire(this, "mv-login"); + } else { + // Mavo v0.2.4- + $.fire(o.mavo.element, "mv-login", { + backend: this + }); + } + + this.permissions.off("login").on(["edit", "save", "logout"]); + } else { + // User is signed out + this.user = null; // Make the plugin work both with stable and future versions of Mavo. + + if (this instanceof EventTarget) { + $.fire(this, "mv-logout"); + } else { + // Mavo v0.2.4- + $.fire(o.mavo.element, "mv-logout", { + backend: this + }); + } + + this.permissions.off(["edit", "add", "delete", "save", "logout"]).on(defaultPermissions); + } + }); + } + + return Promise.resolve(); + }); + } + + update(url, o) { + var _o$project2, _o$collection2, _o$filename2; + + super.update(url, o); + $.extend(this, _.parseSource(this.source, this.defaults)); // If an author provided backend metadata, use them + // since they have higher priority + + this.project = (_o$project2 = o.project) !== null && _o$project2 !== void 0 ? _o$project2 : this.project; + this.collection = (_o$collection2 = o.collection) !== null && _o$collection2 !== void 0 ? _o$collection2 : this.collection; + this.filename = (_o$filename2 = o.filename) !== null && _o$filename2 !== void 0 ? _o$filename2 : this.filename; + + if (this.app) { + this.db = this.app.firestore().collection(this.collection); + + if (this.unsubscribe) { + // Stop listening to changes + this.unsubscribe(); // Get realtime updates for a new document + + this.unsubscribe = this.db.doc(this.filename).onSnapshot(doc => this.updatesHandler(doc), error => o.mavo.error("Firebase Realtime: ".concat(error.message))); + } + } + } + + async load() { + // Since we support offline persistence, we don't want end-users to think an app is hung when we are offline. + // So we hide the progress indicator after 300ms, and it seems that loading was performed (and it really was). + // I am not sure whether we would face this issue without making other parts of an app offline-ready, + // but in the sake of consistency and future use I add this code here + if (this.features["offline-persistence"] && !navigator.onLine) { + setTimeout(() => this.mavo.inProgress = false, 300); + } + + await this.ready; + + try { + const doc = await this.db.doc(this.filename).get(); + return doc.data() || {}; + } catch (error) { + Mavo.warn(this.mavo._("firebase-check-security-rules")); + this.mavo.error("Firebase Load Data: ".concat(error.message)); + return null; + } + } + /** + * Low-level saving code + * @param {*} serialized Data serialized according to this.format + * @param {*} path Path to store data + * @param {*} o Arbitrary options + */ + + + put(serialized, path = this.path, o = {}) { + // Since we support offline persistence, we don't want end-users to think an app is hung when we are offline. + // So we hide the progress indicator after 300ms, and it seems that saving was performed (and it really was) + if (this.features["offline-persistence"] && !navigator.onLine) { + setTimeout(() => this.mavo.inProgress = false, 300); + } + + if (o.isFile) { + if (!this.storageBucketRef) { + Mavo.warn(this.mavo._("firebase-enable-storage")); + return Promise.reject(Error("Firebase Storage: ".concat(this.mavo._("firebase-enable-storage")))); + } + + return this.storageBucketRef.child(path).put(serialized).then(snapshot => snapshot.ref.getDownloadURL()); + } + + return this.db.doc(this.filename).set(JSON.parse(serialized)).then(() => Promise.resolve()).catch(error => { + if (this.features.auth) { + Mavo.warn(this.mavo._("firebase-check-security-rules")); + } else { + Mavo.warn(this.mavo._("firebase-enable-auth")); + Mavo.warn(this.mavo._("firebase-check-security-rules")); + } + + this.mavo.error("Firebase Auth: ".concat(error.message)); + }); + } + /** + * Upload code + * @param {*} file File object to be uploaded + * @param {*} path Relative path to store uploads (e.g. "images") + */ + + + async upload(file, path) { + path = "".concat(this.bucketName, "/").concat(path); + + try { + const url = await this.put(file, path, { + isFile: true + }); + return url; + } catch (error) { + if (error.code) { + if (this.features.auth) { + Mavo.warn(this.mavo._("firebase-check-security-rules")); + } else { + Mavo.warn(this.mavo._("firebase-enable-auth")); + Mavo.warn(this.mavo._("firebase-check-security-rules")); + } + } + + this.mavo.error("".concat(error.message)); + return null; + } + } // Takes care of authentication. If passive is true, only checks if + // the user is already logged in, but does not present any login UI + + + async login(passive) { + await this.ready; + return new Promise((resolve, reject) => { + if (passive) { + resolve(this.user); + } else { + // Apply the default browser preference + firebase.auth().useDeviceLanguage(); + this.app.auth().signInWithPopup(_.buildProvider(this.provider)).catch(error => { + this.mavo.error("Firebase Auth: ".concat(error.message)); + reject(error); + }); + } + }); + } // Log current user out + + + logout() { + return this.app.auth().signOut().catch(error => { + this.mavo.error("Firebase Auth: ".concat(error.message)); + }); + } + /** + * A handler for realtime updates of a document + * @param {Object} snapshot A document snapshot + */ + + + updatesHandler(snapshot) { + const source = snapshot.metadata.hasPendingWrites ? "Local" : "Server"; + + if (source === "Server") { + if (Mavo.prototype.push) { + $.fire(this, "mv-remotedatachange", { + data: snapshot.data() + }); + } else { + // Backward compatibility for Mavo v0.2.4- + if (this.mavo.unsavedChanges) { + if (!confirm(this.mavo._("remote-data-conflict"))) { + return; + } + } // When an app author enables the autosave feature, + // we don't want data loss from race condition with autosave and realtime updates. + // We must save the state of the autosave feature for not to enable it by mistake + + + const autoSaveState = this.mavo.autoSave; + this.mavo.autoSave = false; + this.mavo.render(snapshot.data()); + this.mavo.autoSave = autoSaveState; + } + } + } // Mandatory and very important! This determines when the backend is used + // value: The mv-storage/mv-source/mv-init/mv-uploads value + + + static test(value) { + return /^https:\/\/.*\.firebaseio\.com\/?/.test(value) // Backward compatibility + || /^firebase:\/\/.*/.test(value); + } // Parse the mv-storage/mv-source/mv-init/mv-uploads value, return project ID, collection name, filename + + + static parseSource(source, defaults = {}) { + const ret = {}; + + if (/^https:\/\/.*\.firebaseio\.com\/?/.test(source)) { + const url = new URL(source); + ret.project = url.hostname.split(".").shift(); + source = url.pathname.slice(1); + } else { + source = source.replace("firebase://", ""); + } + + if (source.indexOf("/") > -1) { + const parts = source.split("/"); + ret.project = ret.project || parts.shift(); // If source without project ID has an odd number of parts, + // an app author specified only collection, so we should use the default filename. + // Otherwise, we have both: collection and filename + + ret.filename = parts.length % 2 ? defaults.filename : parts.pop(); + ret.collection = parts.join("/"); + } else { + ret.project = ret.project || source; + ret.collection = defaults.collection; + ret.filename = defaults.filename; + } + + return ret; + } + /** + * Parse the list of options + * @param {String} template The value to parse or an empty string + * @param {Object} defaults Default set of values + */ + + + static getOptions(template, defaults) { + var _template; + + const ret = defaults; + const all = Object.keys(defaults); + + if (template = (_template = template) === null || _template === void 0 ? void 0 : _template.trim()) { + let ids = template.split(/\s+/); // Drop duplicates (last one wins) + + ids = Mavo.Functions.unique(ids.reverse()).reverse(); + all.forEach(id => ids.includes(id) ? ret[id] = true : ret[id] = false); + return ret; + } // No template, return default set + + + return ret; + } + /** + * Parse the list of auth providers + * @param {String} template The value to parse or an empty string + * @param {Object} defaults Default set of auth providers + */ + + + static getAuthProviders(template, defaults) { + var _template2; + + const all = Object.keys(defaults); + + if (template = (_template2 = template) === null || _template2 === void 0 ? void 0 : _template2.trim()) { + let ids = template.split(/\s+/); // Convert all auth providers names to lowercase and drop duplicates + + ids = Mavo.Functions.unique(ids.map(id => id.toLowerCase())); // Drop not supported auth providers + + ids = ids.filter(id => all.includes(id)); + return ids; + } // No auth providers provided + + + return []; + } + /** + * Build an instance of the specified provider object. Fallback to Google + * @param {String} provider An auth provider name + */ + + + static buildProvider(provider = "google") { + // Make provider name title-cased + provider = provider.charAt(0).toUpperCase() + provider.slice(1); + return eval("new firebase.auth.".concat(provider, "AuthProvider()")); + } + + }); + + Mavo.Locale.register("en", { + "firebase-enable-auth": "You might need to enable authorization in your app. To do so, add mv-storage-options=\"auth\" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.", + "firebase-enable-storage": "It seems your app does not support uploads. To enable uploads, add mv-storage-options=\"storage\" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.", + "firebase-check-security-rules": "Please check the security rules for your app. They might be inappropriately set. For details, see https://plugins.mavo.io/plugin/firebase-firestore#security-rules-examples.", + "firebase-offline-persistence-unimplemented": "The current browser does not support all of the features required to enable offline persistence. This feature is supported only by Chrome, Safari, and Firefox web browsers.", + "firebase-auth-google": "Google", + "firebase-auth-facebook": "Facebook", + "firebase-auth-twitter": "Twitter", + "firebase-auth-github": "GitHub" + }); // We want to register this localization string for Mavo v0.2.4- only + + if (!Mavo.prototype.push) { + Mavo.Locale.register("en", { + "remote-data-conflict": "There is new data but you have unsaved changes. Loading it will overwrite your changes. Load new data?" + }); + } +})(Bliss); \ No newline at end of file diff --git a/dist/0.3.10/mavo-firebase-firestore.es5.min.js b/dist/0.3.10/mavo-firebase-firestore.es5.min.js new file mode 100644 index 0000000..fcf6040 --- /dev/null +++ b/dist/0.3.10/mavo-firebase-firestore.es5.min.js @@ -0,0 +1 @@ +"use strict";function _defineProperty(a,b,c){return b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}(function($){"use strict";const PROVIDERS={google:{},facebook:{},twitter:{},github:{}},DEPRECATED={"mv-firebase-key":{attribute:"mv-storage-key",url:"https://plugins.mavo.io/plugin/firebase-firestore#setup-mavo-application"},"mv-firebase-auth":{attribute:"mv-storage-providers",url:"https://plugins.mavo.io/plugin/firebase-firestore#authentication-with-firebase-using-google-facebook-twitter-or-github-accounts"},"mv-firebase":{attribute:"mv-storage-options",url:"https://plugins.mavo.io/plugin/firebase-firestore#customization"},"mv-firebase-storage":{attribute:"mv-storage-bucketname",url:"https://plugins.mavo.io/plugin/firebase-firestore#customization"}};Mavo.Plugins.register("firebase-firestore",{dependencies:["https://cdn.jsdelivr.net/gh/DmitrySharabin/mavo-firebase-firestore/mavo-firebase-firestore.css"],hooks:{"init-start":function(a){Object.keys(PROVIDERS).forEach(b=>{const c="firebase-auth-".concat(b);Mavo.UI.Bar.controls[c]={create(b){return b||$.create("button",{type:"button",className:"mv-".concat(c),textContent:a._(c)})},action(){a.primaryBackend.provider=b,a.primaryBackend.login(!1)},permission:"login",condition(){var c,d;return!!a.primaryBackend.project&&(null===(c=a.primaryBackend.authProviders)||void 0===c||null===(d=c.includes)||void 0===d?void 0:d.call(c,b))}}}),$.extend(Mavo.UI.Bar.controls.login,{condition(){var b;return!a.primaryBackend.project?a.primaryBackend.permissions.login:null===(b=a.primaryBackend.authProviders)||void 0===b||!b.length}})}}});const _=Mavo.Backend.register(class extends Mavo.Backend{constructor(a,b){for(const c in super(a,b),_defineProperty(this,"id","Firebase"),this.permissions.on("read"),this.defaults={collection:"mavo-apps",filename:b.mavo.id,bucketName:b.bucketname||b.mavo.element.getAttribute("mv-firebase-storage")||b.mavo.id,features:{auth:!1,storage:!1,realtime:!1,"offline-persistence":!1,"all-can-write":!1,"all-can-edit":!1},authProviders:_.getAuthProviders(b.providers||b.mavo.element.getAttribute("mv-firebase-auth")||"",PROVIDERS),provider:void 0},$.extend(this,this.defaults),DEPRECATED)if(b.mavo.element.hasAttribute(c)){const a=DEPRECATED[c].attribute,b=DEPRECATED[c].url;Mavo.warn("@".concat(c," is deprecated. Please use @").concat(a," instead. For details, see ").concat(b,"."))}const c=b.options||b.mavo.element.getAttribute("mv-firebase")||"";this.features=_.getOptions(c,this.defaults.features),this.authProviders.length&&(this.features.auth=!0),this.features.auth?(this.permissions.on("login"),!this.authProviders.length&&(this.provider="google")):this.permissions.on(["edit","save"]),this.ready=$.load("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js").then(async()=>{var a,c,d,e;await Promise.all([$.load("https://www.gstatic.com/firebasejs/8.2.0/firebase-firestore.js"),$.include(!this.features.storage,"https://www.gstatic.com/firebasejs/8.2.0/firebase-storage.js"),$.include(!this.features.auth,"https://www.gstatic.com/firebasejs/8.2.0/firebase-auth.js")]),$.extend(this,_.parseSource(this.source,this.defaults)),this.project=null!==(a=b.project)&&void 0!==a?a:this.project,this.collection=null!==(c=b.collection)&&void 0!==c?c:this.collection,this.filename=null!==(d=b.filename)&&void 0!==d?d:this.filename;const f={apiKey:null!==(e=this.key)&&void 0!==e?e:b.mavo.element.getAttribute("mv-firebase-key"),databaseURL:"https://".concat(this.project,".firebaseio.com"),projectId:this.project,authDomain:"".concat(this.project,".firebaseapp.com"),storageBucket:"".concat(this.project,".appspot.com")};if(this.app=firebase.apps.length?firebase.apps.find(a=>a.options.projectId===this.project)||firebase.initializeApp(f,this.project):firebase.initializeApp(f),this.features["offline-persistence"])try{this.app.firestore().enablePersistence({synchronizeTabs:!0})}catch(a){"unimplemented"===a.code&&(Mavo.warn(this.mavo._("firebase-offline-persistence-unimplemented")),this.mavo.error("Firebase Offline Persistence: ".concat(a.message)))}if(this.db=this.app.firestore().collection(this.collection),this.features.realtime?this.unsubscribe=this.db.doc(this.filename).onSnapshot(a=>this.updatesHandler(a),a=>b.mavo.error("Firebase Realtime: ".concat(a.message))):this.unsubscribe&&this.unsubscribe(),this.features.storage&&(this.storageBucketRef=this.app.storage().ref()),this.features.auth){const a=["login"];this.features["all-can-write"]&&a.push("save"),this.features["all-can-edit"]&&a.push("edit"),this.app.auth().onAuthStateChanged(c=>{c?(this.user={username:c.email,name:c.displayName,avatar:c.photoURL,info:c},this instanceof EventTarget?$.fire(this,"mv-login"):$.fire(b.mavo.element,"mv-login",{backend:this}),this.permissions.off("login").on(["edit","save","logout"])):(this.user=null,this instanceof EventTarget?$.fire(this,"mv-logout"):$.fire(b.mavo.element,"mv-logout",{backend:this}),this.permissions.off(["edit","add","delete","save","logout"]).on(a))})}return Promise.resolve()})}update(a,b){var c,d,e;super.update(a,b),$.extend(this,_.parseSource(this.source,this.defaults)),this.project=null!==(c=b.project)&&void 0!==c?c:this.project,this.collection=null!==(d=b.collection)&&void 0!==d?d:this.collection,this.filename=null!==(e=b.filename)&&void 0!==e?e:this.filename,this.app&&(this.db=this.app.firestore().collection(this.collection),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=this.db.doc(this.filename).onSnapshot(a=>this.updatesHandler(a),a=>b.mavo.error("Firebase Realtime: ".concat(a.message)))))}async load(){this.features["offline-persistence"]&&!navigator.onLine&&setTimeout(()=>this.mavo.inProgress=!1,300),await this.ready;try{const a=await this.db.doc(this.filename).get();return a.data()||{}}catch(a){return Mavo.warn(this.mavo._("firebase-check-security-rules")),this.mavo.error("Firebase Load Data: ".concat(a.message)),null}}put(a,b=this.path,c={}){return this.features["offline-persistence"]&&!navigator.onLine&&setTimeout(()=>this.mavo.inProgress=!1,300),c.isFile?this.storageBucketRef?this.storageBucketRef.child(b).put(a).then(a=>a.ref.getDownloadURL()):(Mavo.warn(this.mavo._("firebase-enable-storage")),Promise.reject(Error("Firebase Storage: ".concat(this.mavo._("firebase-enable-storage"))))):this.db.doc(this.filename).set(JSON.parse(a)).then(()=>Promise.resolve()).catch(a=>{this.features.auth?Mavo.warn(this.mavo._("firebase-check-security-rules")):(Mavo.warn(this.mavo._("firebase-enable-auth")),Mavo.warn(this.mavo._("firebase-check-security-rules"))),this.mavo.error("Firebase Auth: ".concat(a.message))})}async upload(a,b){b="".concat(this.bucketName,"/").concat(b);try{const c=await this.put(a,b,{isFile:!0});return c}catch(a){return a.code&&(this.features.auth?Mavo.warn(this.mavo._("firebase-check-security-rules")):(Mavo.warn(this.mavo._("firebase-enable-auth")),Mavo.warn(this.mavo._("firebase-check-security-rules")))),this.mavo.error("".concat(a.message)),null}}async login(a){return await this.ready,new Promise((b,c)=>{a?b(this.user):(firebase.auth().useDeviceLanguage(),this.app.auth().signInWithPopup(_.buildProvider(this.provider)).catch(a=>{this.mavo.error("Firebase Auth: ".concat(a.message)),c(a)}))})}logout(){return this.app.auth().signOut().catch(a=>{this.mavo.error("Firebase Auth: ".concat(a.message))})}updatesHandler(a){const b=a.metadata.hasPendingWrites?"Local":"Server";if("Server"==b)if(Mavo.prototype.push)$.fire(this,"mv-remotedatachange",{data:a.data()});else{if(this.mavo.unsavedChanges&&!confirm(this.mavo._("remote-data-conflict")))return;const b=this.mavo.autoSave;this.mavo.autoSave=!1,this.mavo.render(a.data()),this.mavo.autoSave=b}}static test(a){return /^https:\/\/.*\.firebaseio\.com\/?/.test(a)||/^firebase:\/\/.*/.test(a)}static parseSource(a,b={}){const c={};if(/^https:\/\/.*\.firebaseio\.com\/?/.test(a)){const b=new URL(a);c.project=b.hostname.split(".").shift(),a=b.pathname.slice(1)}else a=a.replace("firebase://","");if(-1b.includes(a)?d[a]=!0:d[a]=!1),d}return d}static getAuthProviders(a,b){var c;const d=Object.keys(b);if(a=null===(c=a)||void 0===c?void 0:c.trim()){let b=a.split(/\s+/);return b=Mavo.Functions.unique(b.map(a=>a.toLowerCase())),b=b.filter(a=>d.includes(a)),b}return[]}static buildProvider(provider="google"){return provider=provider.charAt(0).toUpperCase()+provider.slice(1),eval("new firebase.auth.".concat(provider,"AuthProvider()"))}});Mavo.Locale.register("en",{"firebase-enable-auth":"You might need to enable authorization in your app. To do so, add mv-storage-options=\"auth\" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.","firebase-enable-storage":"It seems your app does not support uploads. To enable uploads, add mv-storage-options=\"storage\" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.","firebase-check-security-rules":"Please check the security rules for your app. They might be inappropriately set. For details, see https://plugins.mavo.io/plugin/firebase-firestore#security-rules-examples.","firebase-offline-persistence-unimplemented":"The current browser does not support all of the features required to enable offline persistence. This feature is supported only by Chrome, Safari, and Firefox web browsers.","firebase-auth-google":"Google","firebase-auth-facebook":"Facebook","firebase-auth-twitter":"Twitter","firebase-auth-github":"GitHub"}),Mavo.prototype.push||Mavo.Locale.register("en",{"remote-data-conflict":"There is new data but you have unsaved changes. Loading it will overwrite your changes. Load new data?"})})(Bliss); \ No newline at end of file diff --git a/dist/0.3.10/mavo-firebase-firestore.js b/dist/0.3.10/mavo-firebase-firestore.js new file mode 100644 index 0000000..bf08019 --- /dev/null +++ b/dist/0.3.10/mavo-firebase-firestore.js @@ -0,0 +1,606 @@ +// @ts-check + +/** + * Firebase backend plugin for Mavo + * @author Dmitry Sharabin and contributors + * @version v0.3.10 + */ +(function ($) { + "use strict"; + + const PROVIDERS = { + "google": {}, + "facebook": {}, + "twitter": {}, + "github": {} + }; + + // Deprecated attributes: + // deprecated -> new attribute, url for help + const DEPRECATED = { + "mv-firebase-key": { + attribute: "mv-storage-key", + url: "https://plugins.mavo.io/plugin/firebase-firestore#setup-mavo-application" + }, + "mv-firebase-auth": { + attribute: "mv-storage-providers", + url: "https://plugins.mavo.io/plugin/firebase-firestore#authentication-with-firebase-using-google-facebook-twitter-or-github-accounts" + }, + "mv-firebase": { + attribute: "mv-storage-options", + url: "https://plugins.mavo.io/plugin/firebase-firestore#customization" + }, + "mv-firebase-storage": { + attribute: "mv-storage-bucketname", + url: "https://plugins.mavo.io/plugin/firebase-firestore#customization" + }, + }; + + Mavo.Plugins.register("firebase-firestore", { + dependencies: [ + "https://cdn.jsdelivr.net/gh/DmitrySharabin/mavo-firebase-firestore/mavo-firebase-firestore.css" + ], + + hooks: { + "init-start": function (mavo) { + // Add buttons for auth providers to the Mavo bar + // Show them only if the Firebase backend is used and any auth provider is specified + Object.keys(PROVIDERS).forEach(p => { + const id = `firebase-auth-${p}`; + + Mavo.UI.Bar.controls[id] = { + create (custom) { + return custom || $.create("button", { + type: "button", + className: `mv-${id}`, + textContent: mavo._(id), + }); + }, + + action () { + mavo.primaryBackend.provider = p; + mavo.primaryBackend.login(false); + }, + + permission: "login", + + condition () { + return Boolean(mavo.primaryBackend.project) && mavo.primaryBackend.authProviders?.includes?.(p); + } + }; + }); + + // Hide the Login button if either of auth providers is specified + $.extend(Mavo.UI.Bar.controls.login, { + condition () { + return Boolean(mavo.primaryBackend.project)? !mavo.primaryBackend.authProviders?.length : mavo.primaryBackend.permissions.login; + } + }); + } + } + }); + + const _ = Mavo.Backend.register( + class Firebase extends Mavo.Backend { + id = "Firebase" + + constructor (url, o) { + super(url, o); + + // Initialization code + this.permissions.on("read"); + + this.defaults = { + collection: "mavo-apps", + filename: o.mavo.id, + bucketName: o.bucketname || o.mavo.element.getAttribute("mv-firebase-storage") || o.mavo.id, + features: { + auth: false, + storage: false, + realtime: false, + "offline-persistence": false, + "all-can-write": false, + "all-can-edit": false + }, + authProviders: _.getAuthProviders(o.providers || o.mavo.element.getAttribute("mv-firebase-auth") || "", PROVIDERS), + provider: undefined + }; + + $.extend(this, this.defaults); + + // Warn an author about deprecated attributes + for (const attribute in DEPRECATED) { + if (o.mavo.element.hasAttribute(attribute)) { + const newAttribute = DEPRECATED[attribute].attribute; + const url = DEPRECATED[attribute].url; + + Mavo.warn(`@${attribute} is deprecated. Please use @${newAttribute} instead. For details, see ${url}.`); + } + } + + // Which backend features should we support? + const template = o.options || o.mavo.element.getAttribute("mv-firebase") || ""; + this.features = _.getOptions(template, this.defaults.features); + + // If either of the auth providers is specified, we must enable the auth feature + if (this.authProviders.length) { + this.features.auth = true; + } + + if (this.features.auth) { + this.permissions.on("login"); + + // If none of the auth providers is specified, by default Google is used + if (!this.authProviders.length) { + this.provider = "google"; + } + } + else { + this.permissions.on(["edit", "save"]); + } + + this.ready = + // First of all, we need to download the Firebase core file + $.load( + "https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js" + ).then(async () => { + // Then download the other parts if needed + await Promise.all([ + // Cloud Firestore + $.load( + "https://www.gstatic.com/firebasejs/8.2.0/firebase-firestore.js" + ), + + // Cloud Storage + $.include( + !this.features.storage, + "https://www.gstatic.com/firebasejs/8.2.0/firebase-storage.js" + ), + + // Authentication + $.include( + !this.features.auth, + "https://www.gstatic.com/firebasejs/8.2.0/firebase-auth.js" + ) + ]); + + // Get the config info from the attribute value + $.extend(this, _.parseSource(this.source, this.defaults)); + + // If an author provided backend metadata, use them + // since they have higher priority + this.project = o.project ?? this.project; + this.collection = o.collection ?? this.collection; + this.filename = o.filename ?? this.filename; + + // The app's Firebase configuration + const config = { + apiKey: this.key ?? o.mavo.element.getAttribute("mv-firebase-key"), + databaseURL: `https://${this.project}.firebaseio.com`, + projectId: this.project, + authDomain: `${this.project}.firebaseapp.com`, + storageBucket: `${this.project}.appspot.com` + }; + + // Initialize Cloud Firestore through Firebase + // We want all mavo apps with the same project ID share the same instance of Firebase app + // If there is no previously created Firebase app with the specified project ID, create one + if (!firebase.apps.length) { + this.app = firebase.initializeApp(config); + } + else { + this.app = firebase.apps.find(app => app.options.projectId === this.project) + || firebase.initializeApp(config, this.project); + } + + if (this.features["offline-persistence"]) { + // To allow offline persistence, we MUST enable it foremost and only once + // Offline persistence is supported only by Chrome, Safari, and Firefox web browsers + try { + this.app.firestore().enablePersistence({ synchronizeTabs: true }); + } + catch (error) { + if (error.code === "unimplemented") { + // The current browser does not support all of the + // features required to enable persistence + Mavo.warn(this.mavo._("firebase-offline-persistence-unimplemented")); + + this.mavo.error(`Firebase Offline Persistence: ${error.message}`); + } + } + } + + this.db = this.app.firestore().collection(this.collection); + + if (this.features.realtime) { + // Get realtime updates + this.unsubscribe = this.db.doc(this.filename).onSnapshot( + doc => this.updatesHandler(doc), + error => o.mavo.error(`Firebase Realtime: ${error.message}`) + ); + } + else if (this.unsubscribe) { + // Stop listening to changes + this.unsubscribe(); + } + + if (this.features.storage) { + // Get a reference to the storage service, which is used to create references in the storage bucket, + // and create a storage reference from the storage service + this.storageBucketRef = this.app.storage().ref(); + } + + if (this.features.auth) { + const defaultPermissions = ["login"]; + + // By default, if the authentication feature is on, only signed-in users can edit and save the app's data. + // We want to let authors granularly override the default behavior, + // and we could enable the corresponding permissions + if (this.features["all-can-write"]) { + defaultPermissions.push("save"); + } + + if (this.features["all-can-edit"]) { + defaultPermissions.push("edit"); + } + + // Set an authentication state observer and get user data + this.app.auth().onAuthStateChanged(user => { + if (user) { + // User is signed in + this.user = { + username: user.email, + name: user.displayName, + avatar: user.photoURL, + info: user // raw user object + }; + + // Make the plugin work both with stable and future versions of Mavo. + if (this instanceof EventTarget) { + $.fire(this, "mv-login"); + } + else { + // Mavo v0.2.4- + $.fire(o.mavo.element, "mv-login", { backend: this }); + } + + this.permissions.off("login").on(["edit", "save", "logout"]); + } + else { + // User is signed out + this.user = null; + + // Make the plugin work both with stable and future versions of Mavo. + if (this instanceof EventTarget) { + $.fire(this, "mv-logout"); + } + else { + // Mavo v0.2.4- + $.fire(o.mavo.element, "mv-logout", { backend: this }); + } + + this.permissions + .off(["edit", "add", "delete", "save", "logout"]) + .on(defaultPermissions); + } + }); + } + + return Promise.resolve(); + }); + } + + update (url, o) { + super.update(url, o); + + $.extend(this, _.parseSource(this.source, this.defaults)); + + // If an author provided backend metadata, use them + // since they have higher priority + this.project = o.project ?? this.project; + this.collection = o.collection ?? this.collection; + this.filename = o.filename ?? this.filename; + + if (this.app) { + this.db = this.app.firestore().collection(this.collection); + + if (this.unsubscribe) { + // Stop listening to changes + this.unsubscribe(); + + // Get realtime updates for a new document + this.unsubscribe = this.db.doc(this.filename).onSnapshot( + doc => this.updatesHandler(doc), + error => o.mavo.error(`Firebase Realtime: ${error.message}`) + ); + } + } + } + + async load () { + // Since we support offline persistence, we don't want end-users to think an app is hung when we are offline. + // So we hide the progress indicator after 300ms, and it seems that loading was performed (and it really was). + // I am not sure whether we would face this issue without making other parts of an app offline-ready, + // but in the sake of consistency and future use I add this code here + if (this.features["offline-persistence"] && !navigator.onLine) { + setTimeout(() => this.mavo.inProgress = false, 300); + } + + await this.ready; + + try { + const doc = await this.db.doc(this.filename).get(); + + return doc.data() || {}; + } + catch (error) { + Mavo.warn(this.mavo._("firebase-check-security-rules")); + this.mavo.error(`Firebase Load Data: ${error.message}`); + + return null; + } + } + + /** + * Low-level saving code + * @param {*} serialized Data serialized according to this.format + * @param {*} path Path to store data + * @param {*} o Arbitrary options + */ + put (serialized, path = this.path, o = {}) { + // Since we support offline persistence, we don't want end-users to think an app is hung when we are offline. + // So we hide the progress indicator after 300ms, and it seems that saving was performed (and it really was) + if (this.features["offline-persistence"] && !navigator.onLine) { + setTimeout(() => this.mavo.inProgress = false, 300); + } + + if (o.isFile) { + if (!this.storageBucketRef) { + Mavo.warn(this.mavo._("firebase-enable-storage")); + + return Promise.reject(Error(`Firebase Storage: ${this.mavo._("firebase-enable-storage")}`)); + } + + return this.storageBucketRef + .child(path) + .put(serialized) + .then(snapshot => snapshot.ref.getDownloadURL()); + } + + return this.db + .doc(this.filename) + .set(JSON.parse(serialized)) + .then(() => Promise.resolve()) + .catch(error => { + if (this.features.auth) { + Mavo.warn(this.mavo._("firebase-check-security-rules")); + } + else { + Mavo.warn(this.mavo._("firebase-enable-auth")); + Mavo.warn(this.mavo._("firebase-check-security-rules")); + } + + this.mavo.error(`Firebase Auth: ${error.message}`); + }); + } + + /** + * Upload code + * @param {*} file File object to be uploaded + * @param {*} path Relative path to store uploads (e.g. "images") + */ + async upload (file, path) { + path = `${this.bucketName}/${path}`; + + try { + const url = await this.put(file, path, {isFile: true}); + + return url; + } + catch (error) { + if (error.code) { + if (this.features.auth) { + Mavo.warn(this.mavo._("firebase-check-security-rules")); + } + else { + Mavo.warn(this.mavo._("firebase-enable-auth")); + Mavo.warn(this.mavo._("firebase-check-security-rules")); + } + } + + this.mavo.error(`${error.message}`); + + return null; + } + } + + // Takes care of authentication. If passive is true, only checks if + // the user is already logged in, but does not present any login UI + async login (passive) { + await this.ready; + + return new Promise((resolve, reject) => { + if (passive) { + resolve(this.user); + } + else { + // Apply the default browser preference + firebase.auth().useDeviceLanguage(); + + this.app + .auth() + .signInWithPopup(_.buildProvider(this.provider)) + .catch(error => { + this.mavo.error(`Firebase Auth: ${error.message}`); + reject(error); + }); + } + }); + } + + // Log current user out + logout () { + return this.app + .auth() + .signOut() + .catch(error => { + this.mavo.error(`Firebase Auth: ${error.message}`); + }); + } + + /** + * A handler for realtime updates of a document + * @param {Object} snapshot A document snapshot + */ + updatesHandler (snapshot) { + const source = snapshot.metadata.hasPendingWrites + ? "Local" + : "Server"; + + if (source === "Server") { + if (Mavo.prototype.push) { + $.fire(this, "mv-remotedatachange", { data: snapshot.data() }); + } + else { + // Backward compatibility for Mavo v0.2.4- + if (this.mavo.unsavedChanges) { + if (!confirm(this.mavo._("remote-data-conflict"))) { + return; + } + } + + // When an app author enables the autosave feature, + // we don't want data loss from race condition with autosave and realtime updates. + // We must save the state of the autosave feature for not to enable it by mistake + const autoSaveState = this.mavo.autoSave; + + this.mavo.autoSave = false; + this.mavo.render(snapshot.data()); + this.mavo.autoSave = autoSaveState; + } + } + } + + // Mandatory and very important! This determines when the backend is used + // value: The mv-storage/mv-source/mv-init/mv-uploads value + static test (value) { + return /^https:\/\/.*\.firebaseio\.com\/?/.test(value) // Backward compatibility + || /^firebase:\/\/.*/.test(value); + } + + // Parse the mv-storage/mv-source/mv-init/mv-uploads value, return project ID, collection name, filename + static parseSource (source, defaults = {}) { + const ret = {}; + + if (/^https:\/\/.*\.firebaseio\.com\/?/.test(source)) { + const url = new URL(source); + + ret.project = url.hostname.split(".").shift(); + source = url.pathname.slice(1); + } + else { + source = source.replace("firebase://", ""); + } + + if (source.indexOf("/") > -1) { + const parts = source.split("/"); + + ret.project = ret.project || parts.shift(); + + // If source without project ID has an odd number of parts, + // an app author specified only collection, so we should use the default filename. + // Otherwise, we have both: collection and filename + ret.filename = parts.length % 2 ? defaults.filename : parts.pop(); + ret.collection = parts.join("/"); + } + else { + ret.project = ret.project || source; + ret.collection = defaults.collection; + ret.filename = defaults.filename; + } + + return ret; + } + + /** + * Parse the list of options + * @param {String} template The value to parse or an empty string + * @param {Object} defaults Default set of values + */ + static getOptions (template, defaults) { + const ret = defaults; + + const all = Object.keys(defaults); + + if (template = template?.trim()) { + let ids = template.split(/\s+/); + + // Drop duplicates (last one wins) + ids = Mavo.Functions.unique(ids.reverse()).reverse(); + + all.forEach(id => + ids.includes(id) ? (ret[id] = true) : (ret[id] = false) + ); + + return ret; + } + + // No template, return default set + return ret; + } + + /** + * Parse the list of auth providers + * @param {String} template The value to parse or an empty string + * @param {Object} defaults Default set of auth providers + */ + static getAuthProviders (template, defaults) { + const all = Object.keys(defaults); + + if (template = template?.trim()) { + let ids = template.split(/\s+/); + + // Convert all auth providers names to lowercase and drop duplicates + ids = Mavo.Functions.unique(ids.map(id => id.toLowerCase())); + + // Drop not supported auth providers + ids = ids.filter(id => all.includes(id)); + + return ids; + } + + // No auth providers provided + return []; + } + + /** + * Build an instance of the specified provider object. Fallback to Google + * @param {String} provider An auth provider name + */ + static buildProvider (provider = "google") { + // Make provider name title-cased + provider = provider.charAt(0).toUpperCase() + provider.slice(1); + + return eval(`new firebase.auth.${provider}AuthProvider()`); + } + } + ); + + Mavo.Locale.register("en", { + "firebase-enable-auth": "You might need to enable authorization in your app. To do so, add mv-storage-options=\"auth\" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.", + "firebase-enable-storage": "It seems your app does not support uploads. To enable uploads, add mv-storage-options=\"storage\" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.", + "firebase-check-security-rules": "Please check the security rules for your app. They might be inappropriately set. For details, see https://plugins.mavo.io/plugin/firebase-firestore#security-rules-examples.", + "firebase-offline-persistence-unimplemented": "The current browser does not support all of the features required to enable offline persistence. This feature is supported only by Chrome, Safari, and Firefox web browsers.", + "firebase-auth-google": "Google", + "firebase-auth-facebook": "Facebook", + "firebase-auth-twitter": "Twitter", + "firebase-auth-github": "GitHub" + }); + + // We want to register this localization string for Mavo v0.2.4- only + if (!Mavo.prototype.push) { + Mavo.Locale.register("en", { + "remote-data-conflict": "There is new data but you have unsaved changes. Loading it will overwrite your changes. Load new data?" + }); + } +})(Bliss); diff --git a/dist/0.3.10/mavo-firebase-firestore.min.js b/dist/0.3.10/mavo-firebase-firestore.min.js new file mode 100644 index 0000000..75c6d1d --- /dev/null +++ b/dist/0.3.10/mavo-firebase-firestore.min.js @@ -0,0 +1 @@ +function _defineProperty(a,b,c){return b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}(function($){"use strict";const PROVIDERS={google:{},facebook:{},twitter:{},github:{}},DEPRECATED={"mv-firebase-key":{attribute:"mv-storage-key",url:"https://plugins.mavo.io/plugin/firebase-firestore#setup-mavo-application"},"mv-firebase-auth":{attribute:"mv-storage-providers",url:"https://plugins.mavo.io/plugin/firebase-firestore#authentication-with-firebase-using-google-facebook-twitter-or-github-accounts"},"mv-firebase":{attribute:"mv-storage-options",url:"https://plugins.mavo.io/plugin/firebase-firestore#customization"},"mv-firebase-storage":{attribute:"mv-storage-bucketname",url:"https://plugins.mavo.io/plugin/firebase-firestore#customization"}};Mavo.Plugins.register("firebase-firestore",{dependencies:["https://cdn.jsdelivr.net/gh/DmitrySharabin/mavo-firebase-firestore/mavo-firebase-firestore.css"],hooks:{"init-start":function(a){Object.keys(PROVIDERS).forEach(b=>{const c=`firebase-auth-${b}`;Mavo.UI.Bar.controls[c]={create(b){return b||$.create("button",{type:"button",className:`mv-${c}`,textContent:a._(c)})},action(){a.primaryBackend.provider=b,a.primaryBackend.login(!1)},permission:"login",condition(){return!!a.primaryBackend.project&&a.primaryBackend.authProviders?.includes?.(b)}}}),$.extend(Mavo.UI.Bar.controls.login,{condition(){return!a.primaryBackend.project?a.primaryBackend.permissions.login:!a.primaryBackend.authProviders?.length}})}}});const _=Mavo.Backend.register(class extends Mavo.Backend{constructor(a,b){for(const c in super(a,b),_defineProperty(this,"id","Firebase"),this.permissions.on("read"),this.defaults={collection:"mavo-apps",filename:b.mavo.id,bucketName:b.bucketname||b.mavo.element.getAttribute("mv-firebase-storage")||b.mavo.id,features:{auth:!1,storage:!1,realtime:!1,"offline-persistence":!1,"all-can-write":!1,"all-can-edit":!1},authProviders:_.getAuthProviders(b.providers||b.mavo.element.getAttribute("mv-firebase-auth")||"",PROVIDERS),provider:void 0},$.extend(this,this.defaults),DEPRECATED)if(b.mavo.element.hasAttribute(c)){const a=DEPRECATED[c].attribute,b=DEPRECATED[c].url;Mavo.warn(`@${c} is deprecated. Please use @${a} instead. For details, see ${b}.`)}const c=b.options||b.mavo.element.getAttribute("mv-firebase")||"";this.features=_.getOptions(c,this.defaults.features),this.authProviders.length&&(this.features.auth=!0),this.features.auth?(this.permissions.on("login"),!this.authProviders.length&&(this.provider="google")):this.permissions.on(["edit","save"]),this.ready=$.load("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js").then(async()=>{await Promise.all([$.load("https://www.gstatic.com/firebasejs/8.2.0/firebase-firestore.js"),$.include(!this.features.storage,"https://www.gstatic.com/firebasejs/8.2.0/firebase-storage.js"),$.include(!this.features.auth,"https://www.gstatic.com/firebasejs/8.2.0/firebase-auth.js")]),$.extend(this,_.parseSource(this.source,this.defaults)),this.project=b.project??this.project,this.collection=b.collection??this.collection,this.filename=b.filename??this.filename;const a={apiKey:this.key??b.mavo.element.getAttribute("mv-firebase-key"),databaseURL:`https://${this.project}.firebaseio.com`,projectId:this.project,authDomain:`${this.project}.firebaseapp.com`,storageBucket:`${this.project}.appspot.com`};if(this.app=firebase.apps.length?firebase.apps.find(a=>a.options.projectId===this.project)||firebase.initializeApp(a,this.project):firebase.initializeApp(a),this.features["offline-persistence"])try{this.app.firestore().enablePersistence({synchronizeTabs:!0})}catch(a){"unimplemented"===a.code&&(Mavo.warn(this.mavo._("firebase-offline-persistence-unimplemented")),this.mavo.error(`Firebase Offline Persistence: ${a.message}`))}if(this.db=this.app.firestore().collection(this.collection),this.features.realtime?this.unsubscribe=this.db.doc(this.filename).onSnapshot(a=>this.updatesHandler(a),a=>b.mavo.error(`Firebase Realtime: ${a.message}`)):this.unsubscribe&&this.unsubscribe(),this.features.storage&&(this.storageBucketRef=this.app.storage().ref()),this.features.auth){const a=["login"];this.features["all-can-write"]&&a.push("save"),this.features["all-can-edit"]&&a.push("edit"),this.app.auth().onAuthStateChanged(c=>{c?(this.user={username:c.email,name:c.displayName,avatar:c.photoURL,info:c},this instanceof EventTarget?$.fire(this,"mv-login"):$.fire(b.mavo.element,"mv-login",{backend:this}),this.permissions.off("login").on(["edit","save","logout"])):(this.user=null,this instanceof EventTarget?$.fire(this,"mv-logout"):$.fire(b.mavo.element,"mv-logout",{backend:this}),this.permissions.off(["edit","add","delete","save","logout"]).on(a))})}return Promise.resolve()})}update(a,b){super.update(a,b),$.extend(this,_.parseSource(this.source,this.defaults)),this.project=b.project??this.project,this.collection=b.collection??this.collection,this.filename=b.filename??this.filename,this.app&&(this.db=this.app.firestore().collection(this.collection),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=this.db.doc(this.filename).onSnapshot(a=>this.updatesHandler(a),a=>b.mavo.error(`Firebase Realtime: ${a.message}`))))}async load(){this.features["offline-persistence"]&&!navigator.onLine&&setTimeout(()=>this.mavo.inProgress=!1,300),await this.ready;try{const a=await this.db.doc(this.filename).get();return a.data()||{}}catch(a){return Mavo.warn(this.mavo._("firebase-check-security-rules")),this.mavo.error(`Firebase Load Data: ${a.message}`),null}}put(a,b=this.path,c={}){return this.features["offline-persistence"]&&!navigator.onLine&&setTimeout(()=>this.mavo.inProgress=!1,300),c.isFile?this.storageBucketRef?this.storageBucketRef.child(b).put(a).then(a=>a.ref.getDownloadURL()):(Mavo.warn(this.mavo._("firebase-enable-storage")),Promise.reject(Error(`Firebase Storage: ${this.mavo._("firebase-enable-storage")}`))):this.db.doc(this.filename).set(JSON.parse(a)).then(()=>Promise.resolve()).catch(a=>{this.features.auth?Mavo.warn(this.mavo._("firebase-check-security-rules")):(Mavo.warn(this.mavo._("firebase-enable-auth")),Mavo.warn(this.mavo._("firebase-check-security-rules"))),this.mavo.error(`Firebase Auth: ${a.message}`)})}async upload(a,b){b=`${this.bucketName}/${b}`;try{const c=await this.put(a,b,{isFile:!0});return c}catch(a){return a.code&&(this.features.auth?Mavo.warn(this.mavo._("firebase-check-security-rules")):(Mavo.warn(this.mavo._("firebase-enable-auth")),Mavo.warn(this.mavo._("firebase-check-security-rules")))),this.mavo.error(`${a.message}`),null}}async login(a){return await this.ready,new Promise((b,c)=>{a?b(this.user):(firebase.auth().useDeviceLanguage(),this.app.auth().signInWithPopup(_.buildProvider(this.provider)).catch(a=>{this.mavo.error(`Firebase Auth: ${a.message}`),c(a)}))})}logout(){return this.app.auth().signOut().catch(a=>{this.mavo.error(`Firebase Auth: ${a.message}`)})}updatesHandler(a){const b=a.metadata.hasPendingWrites?"Local":"Server";if("Server"==b)if(Mavo.prototype.push)$.fire(this,"mv-remotedatachange",{data:a.data()});else{if(this.mavo.unsavedChanges&&!confirm(this.mavo._("remote-data-conflict")))return;const b=this.mavo.autoSave;this.mavo.autoSave=!1,this.mavo.render(a.data()),this.mavo.autoSave=b}}static test(a){return /^https:\/\/.*\.firebaseio\.com\/?/.test(a)||/^firebase:\/\/.*/.test(a)}static parseSource(a,b={}){const c={};if(/^https:\/\/.*\.firebaseio\.com\/?/.test(a)){const b=new URL(a);c.project=b.hostname.split(".").shift(),a=b.pathname.slice(1)}else a=a.replace("firebase://","");if(-1b.includes(a)?c[a]=!0:c[a]=!1),c}return c}static getAuthProviders(a,b){const c=Object.keys(b);if(a=a?.trim()){let b=a.split(/\s+/);return b=Mavo.Functions.unique(b.map(a=>a.toLowerCase())),b=b.filter(a=>c.includes(a)),b}return[]}static buildProvider(provider="google"){return provider=provider.charAt(0).toUpperCase()+provider.slice(1),eval(`new firebase.auth.${provider}AuthProvider()`)}});Mavo.Locale.register("en",{"firebase-enable-auth":"You might need to enable authorization in your app. To do so, add mv-storage-options=\"auth\" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.","firebase-enable-storage":"It seems your app does not support uploads. To enable uploads, add mv-storage-options=\"storage\" to the Mavo root. Note: Instead of mv-storage, you can also use other backend types: mv-source, mv-init, and mv-uploads.","firebase-check-security-rules":"Please check the security rules for your app. They might be inappropriately set. For details, see https://plugins.mavo.io/plugin/firebase-firestore#security-rules-examples.","firebase-offline-persistence-unimplemented":"The current browser does not support all of the features required to enable offline persistence. This feature is supported only by Chrome, Safari, and Firefox web browsers.","firebase-auth-google":"Google","firebase-auth-facebook":"Facebook","firebase-auth-twitter":"Twitter","firebase-auth-github":"GitHub"}),Mavo.prototype.push||Mavo.Locale.register("en",{"remote-data-conflict":"There is new data but you have unsaved changes. Loading it will overwrite your changes. Load new data?"})})(Bliss); \ No newline at end of file diff --git a/mavo-firebase-firestore.js b/mavo-firebase-firestore.js index c6a0b02..bf08019 100644 --- a/mavo-firebase-firestore.js +++ b/mavo-firebase-firestore.js @@ -3,7 +3,7 @@ /** * Firebase backend plugin for Mavo * @author Dmitry Sharabin and contributors - * @version v0.3.9 + * @version v0.3.10 */ (function ($) { "use strict"; @@ -81,12 +81,12 @@ }); const _ = Mavo.Backend.register( - $.Class({ - extends: Mavo.Backend, - - id: "Firebase", + class Firebase extends Mavo.Backend { + id = "Firebase" constructor (url, o) { + super(url, o); + // Initialization code this.permissions.on("read"); @@ -215,7 +215,7 @@ if (this.features.realtime) { // Get realtime updates this.unsubscribe = this.db.doc(this.filename).onSnapshot( - doc => _.updatesHandler(doc, o.mavo), + doc => this.updatesHandler(doc), error => o.mavo.error(`Firebase Realtime: ${error.message}`) ); } @@ -255,7 +255,14 @@ info: user // raw user object }; - $.fire(o.mavo.element, "mv-login", { backend: this }); + // Make the plugin work both with stable and future versions of Mavo. + if (this instanceof EventTarget) { + $.fire(this, "mv-login"); + } + else { + // Mavo v0.2.4- + $.fire(o.mavo.element, "mv-login", { backend: this }); + } this.permissions.off("login").on(["edit", "save", "logout"]); } @@ -263,7 +270,14 @@ // User is signed out this.user = null; - $.fire(o.mavo.element, "mv-logout", { backend: this }); + // Make the plugin work both with stable and future versions of Mavo. + if (this instanceof EventTarget) { + $.fire(this, "mv-logout"); + } + else { + // Mavo v0.2.4- + $.fire(o.mavo.element, "mv-logout", { backend: this }); + } this.permissions .off(["edit", "add", "delete", "save", "logout"]) @@ -274,10 +288,10 @@ return Promise.resolve(); }); - }, + } update (url, o) { - this.super.update.call(this, url, o); + super.update(url, o); $.extend(this, _.parseSource(this.source, this.defaults)); @@ -296,12 +310,12 @@ // Get realtime updates for a new document this.unsubscribe = this.db.doc(this.filename).onSnapshot( - doc => _.updatesHandler(doc, o.mavo), + doc => this.updatesHandler(doc), error => o.mavo.error(`Firebase Realtime: ${error.message}`) ); } } - }, + } async load () { // Since we support offline persistence, we don't want end-users to think an app is hung when we are offline. @@ -325,7 +339,7 @@ return null; } - }, + } /** * Low-level saving code @@ -368,7 +382,7 @@ this.mavo.error(`Firebase Auth: ${error.message}`); }); - }, + } /** * Upload code @@ -398,7 +412,7 @@ return null; } - }, + } // Takes care of authentication. If passive is true, only checks if // the user is already logged in, but does not present any login UI @@ -422,7 +436,7 @@ }); } }); - }, + } // Log current user out logout () { @@ -432,135 +446,144 @@ .catch(error => { this.mavo.error(`Firebase Auth: ${error.message}`); }); - }, - - static: { - // Mandatory and very important! This determines when the backend is used - // value: The mv-storage/mv-source/mv-init/mv-uploads value - test (value) { - return /^https:\/\/.*\.firebaseio\.com\/?/.test(value) // Backward compatibility - || /^firebase:\/\/.*/.test(value); - }, - - // Parse the mv-storage/mv-source/mv-init/mv-uploads value, return project ID, collection name, filename - parseSource (source, defaults = {}) { - const ret = {}; - - if (/^https:\/\/.*\.firebaseio\.com\/?/.test(source)) { - const url = new URL(source); + } - ret.project = url.hostname.split(".").shift(); - source = url.pathname.slice(1); + /** + * A handler for realtime updates of a document + * @param {Object} snapshot A document snapshot + */ + updatesHandler (snapshot) { + const source = snapshot.metadata.hasPendingWrites + ? "Local" + : "Server"; + + if (source === "Server") { + if (Mavo.prototype.push) { + $.fire(this, "mv-remotedatachange", { data: snapshot.data() }); } else { - source = source.replace("firebase://", ""); + // Backward compatibility for Mavo v0.2.4- + if (this.mavo.unsavedChanges) { + if (!confirm(this.mavo._("remote-data-conflict"))) { + return; + } + } + + // When an app author enables the autosave feature, + // we don't want data loss from race condition with autosave and realtime updates. + // We must save the state of the autosave feature for not to enable it by mistake + const autoSaveState = this.mavo.autoSave; + + this.mavo.autoSave = false; + this.mavo.render(snapshot.data()); + this.mavo.autoSave = autoSaveState; } + } + } - if (source.indexOf("/") > -1) { - const parts = source.split("/"); + // Mandatory and very important! This determines when the backend is used + // value: The mv-storage/mv-source/mv-init/mv-uploads value + static test (value) { + return /^https:\/\/.*\.firebaseio\.com\/?/.test(value) // Backward compatibility + || /^firebase:\/\/.*/.test(value); + } - ret.project = ret.project || parts.shift(); + // Parse the mv-storage/mv-source/mv-init/mv-uploads value, return project ID, collection name, filename + static parseSource (source, defaults = {}) { + const ret = {}; - // If source without project ID has an odd number of parts, - // an app author specified only collection, so we should use the default filename. - // Otherwise, we have both: collection and filename - ret.filename = parts.length % 2 ? defaults.filename : parts.pop(); - ret.collection = parts.join("/"); - } - else { - ret.project = ret.project || source; - ret.collection = defaults.collection; - ret.filename = defaults.filename; - } + if (/^https:\/\/.*\.firebaseio\.com\/?/.test(source)) { + const url = new URL(source); - return ret; - }, + ret.project = url.hostname.split(".").shift(); + source = url.pathname.slice(1); + } + else { + source = source.replace("firebase://", ""); + } - /** - * Parse the list of options - * @param {String} template The value to parse or an empty string - * @param {Object} defaults Default set of values - */ - getOptions (template, defaults) { - const ret = defaults; + if (source.indexOf("/") > -1) { + const parts = source.split("/"); - const all = Object.keys(defaults); + ret.project = ret.project || parts.shift(); - if (template = template?.trim()) { - let ids = template.split(/\s+/); + // If source without project ID has an odd number of parts, + // an app author specified only collection, so we should use the default filename. + // Otherwise, we have both: collection and filename + ret.filename = parts.length % 2 ? defaults.filename : parts.pop(); + ret.collection = parts.join("/"); + } + else { + ret.project = ret.project || source; + ret.collection = defaults.collection; + ret.filename = defaults.filename; + } - // Drop duplicates (last one wins) - ids = Mavo.Functions.unique(ids.reverse()).reverse(); + return ret; + } - all.forEach(id => - ids.includes(id) ? (ret[id] = true) : (ret[id] = false) - ); + /** + * Parse the list of options + * @param {String} template The value to parse or an empty string + * @param {Object} defaults Default set of values + */ + static getOptions (template, defaults) { + const ret = defaults; - return ret; - } + const all = Object.keys(defaults); - // No template, return default set - return ret; - }, - - /** - * A handler for realtime updates of a document - * @param {Object} snapshot A document snapshot - * @param {Object} mavo Mavo instance - */ - updatesHandler (snapshot, mavo) { - const source = snapshot.metadata.hasPendingWrites - ? "Local" - : "Server"; - // TODO: There's the problem of what to do when local edits conflict with pulled data - if (source === "Server") { - // When an app author enables the autosave feature, - // we don't want data loss from race condition with autosave and realtime updates. - // We must save the state of the autosave feature for not to enable it by mistake - const autoSaveState = mavo.autoSave; + if (template = template?.trim()) { + let ids = template.split(/\s+/); - mavo.autoSave = false; - mavo.render(snapshot.data()); - mavo.autoSave = autoSaveState; - } - }, + // Drop duplicates (last one wins) + ids = Mavo.Functions.unique(ids.reverse()).reverse(); - /** - * Parse the list of auth providers - * @param {String} template The value to parse or an empty string - * @param {Object} defaults Default set of auth providers - */ - getAuthProviders (template, defaults) { - const all = Object.keys(defaults); + all.forEach(id => + ids.includes(id) ? (ret[id] = true) : (ret[id] = false) + ); - if (template = template?.trim()) { - let ids = template.split(/\s+/); + return ret; + } - // Convert all auth providers names to lowercase and drop duplicates - ids = Mavo.Functions.unique(ids.map(id => id.toLowerCase())); + // No template, return default set + return ret; + } - // Drop not supported auth providers - ids = ids.filter(id => all.includes(id)); + /** + * Parse the list of auth providers + * @param {String} template The value to parse or an empty string + * @param {Object} defaults Default set of auth providers + */ + static getAuthProviders (template, defaults) { + const all = Object.keys(defaults); - return ids; - } + if (template = template?.trim()) { + let ids = template.split(/\s+/); - // No auth providers provided - return []; - }, + // Convert all auth providers names to lowercase and drop duplicates + ids = Mavo.Functions.unique(ids.map(id => id.toLowerCase())); - /** - * Build an instance of the specified provider object. Fallback to Google - * @param {String} provider An auth provider name - */ - buildProvider (provider = "google") { - // Make provider name title-cased - provider = provider.charAt(0).toUpperCase() + provider.slice(1); + // Drop not supported auth providers + ids = ids.filter(id => all.includes(id)); - return eval(`new firebase.auth.${provider}AuthProvider()`); + return ids; } + + // No auth providers provided + return []; } - }) + + /** + * Build an instance of the specified provider object. Fallback to Google + * @param {String} provider An auth provider name + */ + static buildProvider (provider = "google") { + // Make provider name title-cased + provider = provider.charAt(0).toUpperCase() + provider.slice(1); + + return eval(`new firebase.auth.${provider}AuthProvider()`); + } + } ); Mavo.Locale.register("en", { @@ -573,4 +596,11 @@ "firebase-auth-twitter": "Twitter", "firebase-auth-github": "GitHub" }); + + // We want to register this localization string for Mavo v0.2.4- only + if (!Mavo.prototype.push) { + Mavo.Locale.register("en", { + "remote-data-conflict": "There is new data but you have unsaved changes. Loading it will overwrite your changes. Load new data?" + }); + } })(Bliss); diff --git a/package.json b/package.json index 92b7f7a..628bbcd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mavo-firebase-firestore", - "version": "0.3.9", + "version": "0.3.10", "description": "Firebase backend plugin for Mavo. Store and sync app data in milliseconds. Store and serve files at Google scale. Authenticate users simply and securely. All the Google Firebase powers are at your fingertips.", "repository": "https://github.com/DmitrySharabin/mavo-firebase-firestore.git", "bugs": { @@ -11,6 +11,7 @@ "browserslist": "> 0.19%, not IE <= 11, not samsung <= 4, not op_mini all, not chrome <= 55", "devDependencies": { "@babel/core": "^7.10.2", + "@babel/plugin-proposal-class-properties": "^7.14.5", "@babel/preset-env": "^7.10.2", "babel-eslint": "^10.1.0", "eslint": "^6.8.0",