firetruss-worker 2.6.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,603 +1,533 @@
1
1
  (function (global, factory) {
2
2
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
- typeof null === 'function' && null.amd ? null(factory) :
3
+ typeof define === 'function' && define.amd ? define(factory) :
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Fireworker = factory());
5
- }(this, (function () { 'use strict';
5
+ })(this, (function () { 'use strict';
6
6
 
7
7
  /* globals firebase */
8
8
 
9
- var fireworkers = [];
10
- var apps = {};
9
+ const fireworkers = [];
10
+ const apps = {};
11
11
  // This version is filled in by the build, don't reformat the line.
12
- var VERSION = '2.6.0';
12
+ const VERSION = '3.0.0';
13
13
 
14
14
 
15
- var LocalStorage = function LocalStorage() {
16
- this._items = [];
17
- this._pendingItems = [];
18
- this._initialized = false;
19
- this._flushPending = this.flushPending.bind(this);
20
- };
21
-
22
- var prototypeAccessors = { length: { configurable: true } };
23
-
24
- LocalStorage.prototype.init = function init (items) {
25
- if (!this._initialized) {
26
- this._items = items;
27
- this._initialized = true;
15
+ class LocalStorage {
16
+ constructor() {
17
+ this._items = [];
18
+ this._pendingItems = [];
19
+ this._initialized = false;
20
+ this._flushPending = this.flushPending.bind(this);
28
21
  }
29
- };
30
-
31
- LocalStorage.prototype._update = function _update (item) {
32
- if (!this._pendingItems.length) { Promise.resolve().then(this._flushPending); }
33
- this._pendingItems.push(item);
34
- };
35
22
 
36
- LocalStorage.prototype.flushPending = function flushPending () {
37
- if (!this._pendingItems.length) { return; }
38
- if (!fireworkers.length) {
39
- setTimeout(this._flushPending, 200);
40
- return;
23
+ init(items) {
24
+ if (!this._initialized) {
25
+ this._items = items;
26
+ this._initialized = true;
27
+ }
41
28
  }
42
- fireworkers[0]._send({msg: 'updateLocalStorage', items: this._pendingItems});
43
- this._pendingItems = [];
44
- };
45
29
 
46
- prototypeAccessors.length.get = function () {return this._items.length;};
30
+ _update(item) {
31
+ if (!this._pendingItems.length) Promise.resolve().then(this._flushPending);
32
+ this._pendingItems.push(item);
33
+ }
47
34
 
48
- LocalStorage.prototype.key = function key (n) {
49
- return this._items[n].key;
50
- };
35
+ flushPending() {
36
+ if (!this._pendingItems.length) return;
37
+ if (!fireworkers.length) {
38
+ setTimeout(this._flushPending, 200);
39
+ return;
40
+ }
41
+ fireworkers[0]._send({msg: 'updateLocalStorage', items: this._pendingItems});
42
+ this._pendingItems = [];
43
+ }
51
44
 
52
- LocalStorage.prototype.getItem = function getItem (key) {
53
- for (var i = 0, list = this._items; i < list.length; i += 1) {
54
- var item = list[i];
45
+ get length() {return this._items.length;}
55
46
 
56
- if (item.key === key) { return item.value; }
47
+ key(n) {
48
+ return this._items[n].key;
57
49
  }
58
- return null;
59
- };
60
50
 
61
- LocalStorage.prototype.setItem = function setItem (key, value) {
62
- var targetItem;
63
- for (var i = 0, list = this._items; i < list.length; i += 1) {
64
- var item = list[i];
51
+ getItem(key) {
52
+ for (const item of this._items) {
53
+ if (item.key === key) return item.value;
54
+ }
55
+ return null;
56
+ }
65
57
 
58
+ setItem(key, value) {
59
+ let targetItem;
60
+ for (const item of this._items) {
66
61
  if (item.key === key) {
67
- targetItem = item;
68
- item.value = value;
69
- break;
62
+ targetItem = item;
63
+ item.value = value;
64
+ break;
65
+ }
70
66
  }
67
+ if (!targetItem) {
68
+ targetItem = {key, value};
69
+ this._items.push(targetItem);
70
+ }
71
+ this._update(targetItem);
71
72
  }
72
- if (!targetItem) {
73
- targetItem = {key: key, value: value};
74
- this._items.push(targetItem);
75
- }
76
- this._update(targetItem);
77
- };
78
73
 
79
- LocalStorage.prototype.removeItem = function removeItem (key) {
80
- for (var i = 0; i < this._items.length; i++) {
81
- if (this._items[i].key === key) {
82
- this._items.splice(i, 1);
83
- this._update({key: key, value: null});
84
- break;
74
+ removeItem(key) {
75
+ for (let i = 0; i < this._items.length; i++) {
76
+ if (this._items[i].key === key) {
77
+ this._items.splice(i, 1);
78
+ this._update({key, value: null});
79
+ break;
80
+ }
85
81
  }
86
82
  }
87
- };
88
83
 
89
- LocalStorage.prototype.clear = function clear () {
90
- for (var item in this._items) {
91
- this._update({key: item.key, value: null});
84
+ clear() {
85
+ for (const item in this._items) {
86
+ this._update({key: item.key, value: null});
87
+ }
88
+ this._items = [];
92
89
  }
93
- this._items = [];
94
- };
95
-
96
- Object.defineProperties( LocalStorage.prototype, prototypeAccessors );
90
+ }
97
91
 
98
92
  self.localStorage = new LocalStorage();
99
93
 
100
94
 
101
- var Branch = function Branch() {
102
- this._root = null;
103
- };
104
-
105
- Branch.prototype.set = function set (value) {
106
- this._root = value;
107
- };
95
+ class Branch {
96
+ constructor() {
97
+ this._root = null;
98
+ }
108
99
 
109
- Branch.prototype.diff = function diff (value, pathPrefix) {
110
- var updates = {};
111
- var segments = pathPrefix === '/' ? [''] : pathPrefix.split('/');
112
- if (this._diffRecursively(this._root, value, segments, updates)) {
100
+ set(value) {
113
101
  this._root = value;
114
- updates[pathPrefix] = value;
115
- }
116
- return updates;
117
- };
118
-
119
- Branch.prototype._diffRecursively = function _diffRecursively (oldValue, newValue, segments, updates) {
120
- if (oldValue === undefined) { oldValue = null; }
121
- if (newValue === undefined) { newValue = null; }
122
- if (oldValue === null) { return newValue !== null; }
123
- if (oldValue instanceof Object && newValue instanceof Object) {
124
- var replace = true;
125
- var keysToReplace = [];
126
- for (var childKey in newValue) {
127
- if (!newValue.hasOwnProperty(childKey)) { continue; }
128
- var replaceChild = this._diffRecursively(
129
- oldValue[childKey], newValue[childKey], segments.concat(childKey), updates);
130
- if (replaceChild) {
131
- keysToReplace.push(childKey);
132
- } else {
133
- replace = false;
102
+ }
103
+
104
+ diff(value, pathPrefix) {
105
+ const updates = {};
106
+ const segments = pathPrefix === '/' ? [''] : pathPrefix.split('/');
107
+ if (this._diffRecursively(this._root, value, segments, updates)) {
108
+ this._root = value;
109
+ updates[pathPrefix] = value;
110
+ }
111
+ return updates;
112
+ }
113
+
114
+ _diffRecursively(oldValue, newValue, segments, updates) {
115
+ if (oldValue === undefined) oldValue = null;
116
+ if (newValue === undefined) newValue = null;
117
+ if (oldValue === null) return newValue !== null;
118
+ if (oldValue instanceof Object && newValue instanceof Object) {
119
+ let replace = true;
120
+ const keysToReplace = [];
121
+ for (const childKey in newValue) {
122
+ if (!newValue.hasOwnProperty(childKey)) continue;
123
+ const replaceChild = this._diffRecursively(
124
+ oldValue[childKey], newValue[childKey], segments.concat(childKey), updates);
125
+ if (replaceChild) {
126
+ keysToReplace.push(childKey);
127
+ } else {
128
+ replace = false;
129
+ }
134
130
  }
131
+ if (replace) return true;
132
+ for (const childKey in oldValue) {
133
+ if (!oldValue.hasOwnProperty(childKey) || newValue.hasOwnProperty(childKey)) continue;
134
+ updates[segments.concat(childKey).join('/')] = null;
135
+ delete oldValue[childKey];
136
+ }
137
+ for (const childKey of keysToReplace) {
138
+ updates[segments.concat(childKey).join('/')] = newValue[childKey];
139
+ oldValue[childKey] = newValue[childKey];
140
+ }
141
+ } else {
142
+ return newValue !== oldValue;
135
143
  }
136
- if (replace) { return true; }
137
- for (var childKey$1 in oldValue) {
138
- if (!oldValue.hasOwnProperty(childKey$1) || newValue.hasOwnProperty(childKey$1)) { continue; }
139
- updates[segments.concat(childKey$1).join('/')] = null;
140
- delete oldValue[childKey$1];
144
+ }
145
+ }
146
+
147
+
148
+ class Fireworker {
149
+ constructor(port) {
150
+ this._port = port;
151
+ this._lastWriteSerial = 0;
152
+ this._app = undefined;
153
+ this._cachedAuth = undefined;
154
+ this._cachedDatabase = undefined;
155
+ this._lastJsonUser = undefined;
156
+ this._configError = Fireworker._staticConfigError;
157
+ this._callbacks = {};
158
+ this._messages = [];
159
+ this._flushMessageQueue = this._flushMessageQueue.bind(this);
160
+ port.onmessage = this._receive.bind(this);
161
+ }
162
+
163
+ get _auth() {
164
+ if (this._cachedAuth) return this._cachedAuth;
165
+ if (!this._app) throw new Error('Must provide Firebase configuration data first');
166
+ return this._cachedAuth = this._app.auth();
167
+ }
168
+
169
+ get _database() {
170
+ if (this._cachedDatabase) return this._cachedDatabase;
171
+ if (!this._app) throw new Error('Must provide Firebase configuration data first');
172
+ if (Fireworker._databaseWrapperCallback) {
173
+ this._cachedDatabase = Fireworker._databaseWrapperCallback(this._app.database());
174
+ } else {
175
+ this._cachedDatabase = this._app.database();
141
176
  }
142
- for (var i = 0, list = keysToReplace; i < list.length; i += 1) {
143
- var childKey$2 = list[i];
177
+ return this._cachedDatabase;
178
+ }
179
+
180
+ init({storage, config}) {
181
+ if (storage) self.localStorage.init(storage);
182
+ if (config) {
183
+ try {
184
+ this._app = apps[config.databaseURL];
185
+ if (!this._app) {
186
+ this._app = apps[config.databaseURL] = firebase.initializeApp(config, config.databaseURL);
187
+ // If the API key looks invalid then assume that we're running against Cinderbase rather
188
+ // than Firebase and override the configuration appropriately.
189
+ if (config.apiKey && config.apiKey.length < 20) {
190
+ this._app.database().INTERNAL.forceWebSockets();
191
+ this._app.auth().useEmulator(config.databaseURL, {disableWarnings: true});
192
+ }
193
+ }
194
+ this._app.database();
195
+ this._app.auth();
196
+ this._configError = Fireworker._staticConfigError;
197
+ } catch (e) {
198
+ this._configError = e;
199
+ throw e;
200
+ }
201
+ } else if (this._configError) {
202
+ throw this._configError;
203
+ }
204
+ return {
205
+ exposedFunctionNames: Object.keys(Fireworker._exposed),
206
+ version: VERSION,
207
+ firebaseSdkVersion: firebase.SDK_VERSION
208
+ };
209
+ }
144
210
 
145
- updates[segments.concat(childKey$2).join('/')] = newValue[childKey$2];
146
- oldValue[childKey$2] = newValue[childKey$2];
211
+ destroy() {
212
+ for (const key in this._callbacks) {
213
+ const callback = this._callbacks[key];
214
+ if (callback.cancel) callback.cancel();
147
215
  }
148
- } else {
149
- return newValue !== oldValue;
150
- }
151
- };
152
-
153
-
154
- var Fireworker = function Fireworker(port) {
155
- this._port = port;
156
- this._lastWriteSerial = 0;
157
- this._app = undefined;
158
- this._cachedAuth = undefined;
159
- this._cachedDatabase = undefined;
160
- this._lastJsonUser = undefined;
161
- this._configError = Fireworker._staticConfigError;
162
- this._callbacks = {};
163
- this._messages = [];
164
- this._flushMessageQueue = this._flushMessageQueue.bind(this);
165
- port.onmessage = this._receive.bind(this);
166
- };
167
-
168
- var prototypeAccessors$1 = { _auth: { configurable: true },_database: { configurable: true } };
169
-
170
- prototypeAccessors$1._auth.get = function () {
171
- if (this._cachedAuth) { return this._cachedAuth; }
172
- if (!this._app) { throw new Error('Must provide Firebase configuration data first'); }
173
- return this._cachedAuth = this._app.auth();
174
- };
175
-
176
- prototypeAccessors$1._database.get = function () {
177
- if (this._cachedDatabase) { return this._cachedDatabase; }
178
- if (!this._app) { throw new Error('Must provide Firebase configuration data first'); }
179
- if (Fireworker._databaseWrapperCallback) {
180
- this._cachedDatabase = Fireworker._databaseWrapperCallback(this._app.database());
181
- } else {
182
- this._cachedDatabase = this._app.database();
216
+ this._callbacks = {};
217
+ this._port.onmessage = null;
218
+ this._messages = [];
219
+ const k = fireworkers.indexOf(this);
220
+ if (k >= 0) fireworkers[k] = null;
183
221
  }
184
- return this._cachedDatabase;
185
- };
186
222
 
187
- Fireworker.prototype.init = function init (ref) {
188
- var storage = ref.storage;
189
- var config = ref.config;
223
+ enableFirebaseLogging({value}) {
224
+ firebase.database.enableLogging(value);
225
+ }
226
+
227
+ ping() {
228
+ // Noop, placeholder for legacy Firetruss clients.
229
+ }
230
+
231
+ bounceConnection() {
232
+ this._database.goOffline();
233
+ this._database.goOnline();
234
+ }
235
+
236
+ _receive(event) {
237
+ Fireworker._firstMessageReceived = true;
238
+ for (const message of event.data) this._receiveMessage(message);
239
+ }
190
240
 
191
- if (storage) { self.localStorage.init(storage); }
192
- if (config) {
241
+ _receiveMessage(message) {
242
+ let promise;
193
243
  try {
194
- this._app = apps[config.databaseURL];
195
- if (!this._app) {
196
- this._app = apps[config.databaseURL] = firebase.initializeApp(config, config.databaseURL);
197
- // If the API key looks invalid then assume that we're running against Cinderbase rather
198
- // than Firebase and override the configuration appropriately.
199
- if (config.apiKey && config.apiKey.length < 20) {
200
- this._app.database().INTERNAL.forceWebSockets();
201
- this._app.auth().useEmulator(config.databaseURL, {disableWarnings: true});
202
- }
244
+ const fn = this[message.msg];
245
+ if (typeof fn !== 'function') throw new Error('Unknown message: ' + message.msg);
246
+ if (message.writeSerial) {
247
+ this._lastWriteSerial = Math.max(this._lastWriteSerial, message.writeSerial);
203
248
  }
204
- this._app.database();
205
- this._app.auth();
206
- this._configError = Fireworker._staticConfigError;
249
+ promise = Promise.resolve(fn.call(this, message));
207
250
  } catch (e) {
208
- this._configError = e;
209
- throw e;
251
+ e.immediateFailure = true;
252
+ promise = Promise.reject(e);
210
253
  }
211
- } else if (this._configError) {
212
- throw this._configError;
213
- }
214
- return {
215
- exposedFunctionNames: Object.keys(Fireworker._exposed),
216
- version: VERSION,
217
- firebaseSdkVersion: firebase.SDK_VERSION
218
- };
219
- };
220
-
221
- Fireworker.prototype.destroy = function destroy () {
222
- for (var key in this._callbacks) {
223
- var callback = this._callbacks[key];
224
- if (callback.cancel) { callback.cancel(); }
225
- }
226
- this._callbacks = {};
227
- this._port.onmessage = null;
228
- this._messages = [];
229
- var k = fireworkers.indexOf(this);
230
- if (k >= 0) { fireworkers[k] = null; }
231
- };
232
-
233
- Fireworker.prototype.enableFirebaseLogging = function enableFirebaseLogging (ref) {
234
- var value = ref.value;
235
-
236
- firebase.database.enableLogging(value);
237
- };
238
-
239
- Fireworker.prototype.ping = function ping () {
240
- // Noop, placeholder for legacy Firetruss clients.
241
- };
242
-
243
- Fireworker.prototype.bounceConnection = function bounceConnection () {
244
- this._database.goOffline();
245
- this._database.goOnline();
246
- };
247
-
248
- Fireworker.prototype._receive = function _receive (event) {
249
- Fireworker._firstMessageReceived = true;
250
- for (var i = 0, list = event.data; i < list.length; i += 1) {
251
- var message = list[i];
252
-
253
- this._receiveMessage(message);
254
+ if (!message.oneWay) {
255
+ promise.then(result => {
256
+ this._send({msg: 'resolve', id: message.id, result});
257
+ }, error => {
258
+ this._send({msg: 'reject', id: message.id, error: errorToJson(error)});
259
+ });
254
260
  }
255
- };
261
+ }
262
+
263
+ _send(message) {
264
+ if (!this._messages.length) Promise.resolve().then(this._flushMessageQueue);
265
+ this._messages.push(message);
266
+ }
256
267
 
257
- Fireworker.prototype._receiveMessage = function _receiveMessage (message) {
258
- var this$1 = this;
268
+ _flushMessageQueue() {
269
+ this._port.postMessage(this._messages);
270
+ this._messages = [];
271
+ }
259
272
 
260
- var promise;
261
- try {
262
- var fn = this[message.msg];
263
- if (typeof fn !== 'function') { throw new Error('Unknown message: ' + message.msg); }
264
- if (message.writeSerial) {
265
- this._lastWriteSerial = Math.max(this._lastWriteSerial, message.writeSerial);
273
+ call({name, args}) {
274
+ try {
275
+ return Promise.resolve(Fireworker._exposed[name].apply(null, args));
276
+ } catch (e) {
277
+ return Promise.reject(e);
266
278
  }
267
- promise = Promise.resolve(fn.call(this, message));
268
- } catch (e) {
269
- e.immediateFailure = true;
270
- promise = Promise.reject(e);
271
- }
272
- if (!message.oneWay) {
273
- promise.then(function (result) {
274
- this$1._send({msg: 'resolve', id: message.id, result: result});
275
- }, function (error) {
276
- this$1._send({msg: 'reject', id: message.id, error: errorToJson(error)});
277
- });
278
279
  }
279
- };
280
280
 
281
- Fireworker.prototype._send = function _send (message) {
282
- if (!this._messages.length) { Promise.resolve().then(this._flushMessageQueue); }
283
- this._messages.push(message);
284
- };
281
+ authWithCustomToken({url, authToken}) {
282
+ return this._auth.signInWithCustomToken(authToken)
283
+ .then(result => userToJson(result.user));
284
+ }
285
285
 
286
- Fireworker.prototype._flushMessageQueue = function _flushMessageQueue () {
287
- this._port.postMessage(this._messages);
288
- this._messages = [];
289
- };
286
+ authAnonymously({url}) {
287
+ return this._auth.signInAnonymously()
288
+ .then(result => userToJson(result.user));
289
+ }
290
290
 
291
- Fireworker.prototype.call = function call (ref) {
292
- var name = ref.name;
293
- var args = ref.args;
291
+ unauth({url}) {
292
+ return this._auth.signOut().catch(e => {
293
+ // We can ignore the error if the user is signed out anyway, but make sure to notify all
294
+ // authCallbacks otherwise we end up in a bogus state!
295
+ if (this._auth.currentUser === null) {
296
+ for (const callbackId in this._callbacks) {
297
+ if (!this._callbacks.hasOwnProperty(callbackId)) continue;
298
+ const callback = this._callbacks[callbackId];
299
+ if (callback.auth) callback(null);
300
+ }
301
+ } else {
302
+ return Promise.reject(e);
303
+ }
304
+ });
305
+ }
294
306
 
295
- try {
296
- return Promise.resolve(Fireworker._exposed[name].apply(null, args));
297
- } catch (e) {
298
- return Promise.reject(e);
307
+ onAuth({url, callbackId}) {
308
+ const authCallback = this._callbacks[callbackId] = this._onAuthCallback.bind(this, callbackId);
309
+ authCallback.auth = true;
310
+ authCallback.cancel = this._auth.onIdTokenChanged(authCallback);
299
311
  }
300
- };
301
312
 
302
- Fireworker.prototype.authWithCustomToken = function authWithCustomToken (ref) {
303
- var url = ref.url;
304
- var authToken = ref.authToken;
313
+ _onAuthCallback(callbackId, user) {
314
+ userToJson(user).then(jsonUser => {
315
+ if (areEqualValues(this._lastJsonUser, jsonUser)) return;
316
+ this._lastJsonUser = jsonUser;
317
+ this._send({msg: 'callback', id: callbackId, args: [jsonUser]});
318
+ });
319
+ }
305
320
 
306
- return this._auth.signInWithCustomToken(authToken)
307
- .then(function (result) { return userToJson(result.user); });
308
- };
321
+ set({url, value}) {
322
+ return this._createRef(url).set(value);
323
+ }
309
324
 
310
- Fireworker.prototype.authAnonymously = function authAnonymously (ref) {
311
- var url = ref.url;
325
+ update({url, value}) {
326
+ return this._createRef(url).update(value);
327
+ }
312
328
 
313
- return this._auth.signInAnonymously()
314
- .then(function (result) { return userToJson(result.user); });
315
- };
329
+ once({url}) {
330
+ return this._createRef(url).once('value').then(snapshot => this._snapshotToJson(snapshot));
331
+ }
316
332
 
317
- Fireworker.prototype.unauth = function unauth (ref) {
318
- var this$1 = this;
319
- var url = ref.url;
333
+ on({listenerKey, url, spec, eventType, callbackId, options}) {
334
+ options = options || {};
335
+ if (options.sync) options.branch = new Branch();
336
+ options.cancel = this.off.bind(this, {listenerKey, url, spec, eventType, callbackId});
337
+ const snapshotCallback = this._callbacks[callbackId] =
338
+ this._onSnapshotCallback.bind(this, callbackId, options);
339
+ snapshotCallback.listenerKey = listenerKey;
340
+ snapshotCallback.eventType = eventType;
341
+ snapshotCallback.cancel = options.cancel;
342
+ const cancelCallback = this._onCancelCallback.bind(this, callbackId);
343
+ this._createRef(url, spec).on(eventType, snapshotCallback, cancelCallback);
344
+ }
320
345
 
321
- return this._auth.signOut().catch(function (e) {
322
- // We can ignore the error if the user is signed out anyway, but make sure to notify all
323
- // authCallbacks otherwise we end up in a bogus state!
324
- if (this$1._auth.currentUser === null) {
325
- for (var callbackId in this$1._callbacks) {
326
- if (!this$1._callbacks.hasOwnProperty(callbackId)) { continue; }
327
- var callback = this$1._callbacks[callbackId];
328
- if (callback.auth) { callback(null); }
329
- }
346
+ off({listenerKey, url, spec, eventType, callbackId}) {
347
+ let snapshotCallback;
348
+ if (callbackId) {
349
+ // Callback IDs will not be reused across on() calls, so it's safe to just delete it.
350
+ snapshotCallback = this._callbacks[callbackId];
351
+ delete this._callbacks[callbackId];
330
352
  } else {
331
- return Promise.reject(e);
353
+ for (const key of Object.keys(this._callbacks)) {
354
+ if (!this._callbacks.hasOwnProperty(key)) continue;
355
+ const callback = this._callbacks[key];
356
+ if (callback.listenerKey === listenerKey &&
357
+ (!eventType || callback.eventType === eventType)) {
358
+ delete this._callbacks[key];
359
+ }
360
+ }
332
361
  }
333
- });
334
- };
335
-
336
- Fireworker.prototype.onAuth = function onAuth (ref) {
337
- var url = ref.url;
338
- var callbackId = ref.callbackId;
339
-
340
- var authCallback = this._callbacks[callbackId] = this._onAuthCallback.bind(this, callbackId);
341
- authCallback.auth = true;
342
- authCallback.cancel = this._auth.onIdTokenChanged(authCallback);
343
- };
344
-
345
- Fireworker.prototype._onAuthCallback = function _onAuthCallback (callbackId, user) {
346
- var this$1 = this;
347
-
348
- userToJson(user).then(function (jsonUser) {
349
- if (areEqualValues(this$1._lastJsonUser, jsonUser)) { return; }
350
- this$1._lastJsonUser = jsonUser;
351
- this$1._send({msg: 'callback', id: callbackId, args: [jsonUser]});
352
- });
353
- };
354
-
355
- Fireworker.prototype.set = function set (ref) {
356
- var url = ref.url;
357
- var value = ref.value;
358
-
359
- return this._createRef(url).set(value);
360
- };
361
-
362
- Fireworker.prototype.update = function update (ref) {
363
- var url = ref.url;
364
- var value = ref.value;
365
-
366
- return this._createRef(url).update(value);
367
- };
368
-
369
- Fireworker.prototype.once = function once (ref) {
370
- var this$1 = this;
371
- var url = ref.url;
372
-
373
- return this._createRef(url).once('value').then(function (snapshot) { return this$1._snapshotToJson(snapshot); });
374
- };
375
-
376
- Fireworker.prototype.on = function on (ref) {
377
- var listenerKey = ref.listenerKey;
378
- var url = ref.url;
379
- var spec = ref.spec;
380
- var eventType = ref.eventType;
381
- var callbackId = ref.callbackId;
382
- var options = ref.options;
383
-
384
- options = options || {};
385
- if (options.sync) { options.branch = new Branch(); }
386
- options.cancel = this.off.bind(this, {listenerKey: listenerKey, url: url, spec: spec, eventType: eventType, callbackId: callbackId});
387
- var snapshotCallback = this._callbacks[callbackId] =
388
- this._onSnapshotCallback.bind(this, callbackId, options);
389
- snapshotCallback.listenerKey = listenerKey;
390
- snapshotCallback.eventType = eventType;
391
- snapshotCallback.cancel = options.cancel;
392
- var cancelCallback = this._onCancelCallback.bind(this, callbackId);
393
- this._createRef(url, spec).on(eventType, snapshotCallback, cancelCallback);
394
- };
395
-
396
- Fireworker.prototype.off = function off (ref) {
397
- var listenerKey = ref.listenerKey;
398
- var url = ref.url;
399
- var spec = ref.spec;
400
- var eventType = ref.eventType;
401
- var callbackId = ref.callbackId;
402
-
403
- var snapshotCallback;
404
- if (callbackId) {
405
- // Callback IDs will not be reused across on() calls, so it's safe to just delete it.
406
- snapshotCallback = this._callbacks[callbackId];
407
- delete this._callbacks[callbackId];
408
- } else {
409
- for (var i = 0, list = Object.keys(this._callbacks); i < list.length; i += 1) {
410
- var key = list[i];
411
-
412
- if (!this._callbacks.hasOwnProperty(key)) { continue; }
413
- var callback = this._callbacks[key];
414
- if (callback.listenerKey === listenerKey &&
415
- (!eventType || callback.eventType === eventType)) {
416
- delete this._callbacks[key];
362
+ this._createRef(url, spec).off(eventType, snapshotCallback);
363
+ }
364
+
365
+ _onSnapshotCallback(callbackId, options, snapshot) {
366
+ if (options.sync && options.rest) {
367
+ const path = decodeURIComponent(
368
+ snapshot.ref.toString().replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
369
+ let value;
370
+ try {
371
+ value = normalizeFirebaseValue(snapshot.val());
372
+ } catch (e) {
373
+ options.cancel();
374
+ this._onCancelCallback(callbackId, e);
375
+ return;
376
+ }
377
+ const updates = options.branch.diff(value, path);
378
+ for (const childPath in updates) {
379
+ if (!updates.hasOwnProperty(childPath)) continue;
380
+ this._send({
381
+ msg: 'callback', id: callbackId,
382
+ args: [null, {
383
+ path: childPath, value: updates[childPath], writeSerial: this._lastWriteSerial
384
+ }]
385
+ });
386
+ }
387
+ } else {
388
+ try {
389
+ const snapshotJson = this._snapshotToJson(snapshot);
390
+ if (options.sync) options.branch.set(snapshotJson.value);
391
+ this._send({msg: 'callback', id: callbackId, args: [null, snapshotJson]});
392
+ options.rest = true;
393
+ } catch (e) {
394
+ options.cancel();
395
+ this._onCancelCallback(callbackId, e);
417
396
  }
418
397
  }
419
398
  }
420
- this._createRef(url, spec).off(eventType, snapshotCallback);
421
- };
422
399
 
423
- Fireworker.prototype._onSnapshotCallback = function _onSnapshotCallback (callbackId, options, snapshot) {
424
- if (options.sync && options.rest) {
425
- var path = decodeURIComponent(
426
- snapshot.ref.toString().replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
427
- var value;
428
- try {
429
- value = normalizeFirebaseValue(snapshot.val());
430
- } catch (e) {
431
- options.cancel();
432
- this._onCancelCallback(callbackId, e);
433
- return;
434
- }
435
- var updates = options.branch.diff(value, path);
436
- for (var childPath in updates) {
437
- if (!updates.hasOwnProperty(childPath)) { continue; }
438
- this._send({
439
- msg: 'callback', id: callbackId,
440
- args: [null, {
441
- path: childPath, value: updates[childPath], writeSerial: this._lastWriteSerial
442
- }]
443
- });
444
- }
445
- } else {
446
- try {
447
- var snapshotJson = this._snapshotToJson(snapshot);
448
- if (options.sync) { options.branch.set(snapshotJson.value); }
449
- this._send({msg: 'callback', id: callbackId, args: [null, snapshotJson]});
450
- options.rest = true;
451
- } catch (e$1) {
452
- options.cancel();
453
- this._onCancelCallback(callbackId, e$1);
454
- }
455
- }
456
- };
457
-
458
- Fireworker.prototype._onCancelCallback = function _onCancelCallback (callbackId, error) {
459
- delete this._callbacks[callbackId];
460
- this._send({msg: 'callback', id: callbackId, args: [errorToJson(error)]});
461
- };
462
-
463
- Fireworker.prototype.transaction = function transaction (ref$1) {
464
- var this$1 = this;
465
- var url = ref$1.url;
466
- var oldValue = ref$1.oldValue;
467
- var relativeUpdates = ref$1.relativeUpdates;
468
-
469
- var transactionPath = decodeURIComponent(url.replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
470
- var ref = this._createRef(url);
471
- var branch = new Branch();
472
- var stale, committedValue;
473
-
474
- return ref.transaction(function (value) {
475
- committedValue = undefined;
476
- value = normalizeFirebaseValue(value);
477
- stale = !areEqualNormalFirebaseValues(value, oldValue);
478
- if (stale) { value = oldValue; }
479
- if (relativeUpdates) {
480
- for (var relativePath in relativeUpdates) {
481
- if (!relativeUpdates.hasOwnProperty(relativePath)) { continue; }
482
- if (relativePath) {
483
- var segments = relativePath.split('/');
484
- if (value === undefined || value === null) { value = {}; }
485
- var object = value;
486
- for (var i = 0; i < segments.length - 1; i++) {
487
- var key = segments[i];
488
- var child = object[key];
489
- if (child === undefined || child === null) { child = object[key] = {}; }
490
- object = child;
400
+ _onCancelCallback(callbackId, error) {
401
+ delete this._callbacks[callbackId];
402
+ this._send({msg: 'callback', id: callbackId, args: [errorToJson(error)]});
403
+ }
404
+
405
+ transaction({url, oldValue, relativeUpdates}) {
406
+ const transactionPath = decodeURIComponent(url.replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
407
+ const ref = this._createRef(url);
408
+ const branch = new Branch();
409
+ let stale, committedValue;
410
+
411
+ return ref.transaction(value => {
412
+ committedValue = undefined;
413
+ value = normalizeFirebaseValue(value);
414
+ stale = !areEqualNormalFirebaseValues(value, oldValue);
415
+ if (stale) value = oldValue;
416
+ if (relativeUpdates) {
417
+ for (const relativePath in relativeUpdates) {
418
+ if (!relativeUpdates.hasOwnProperty(relativePath)) continue;
419
+ if (relativePath) {
420
+ const segments = relativePath.split('/');
421
+ if (value === undefined || value === null) value = {};
422
+ let object = value;
423
+ for (let i = 0; i < segments.length - 1; i++) {
424
+ const key = segments[i];
425
+ let child = object[key];
426
+ if (child === undefined || child === null) child = object[key] = {};
427
+ object = child;
428
+ }
429
+ object[segments[segments.length - 1]] = relativeUpdates[relativePath];
430
+ } else {
431
+ value = relativeUpdates[relativePath];
491
432
  }
492
- object[segments[segments.length - 1]] = relativeUpdates[relativePath];
493
- } else {
494
- value = relativeUpdates[relativePath];
495
433
  }
496
434
  }
497
- }
498
- branch.set(value);
499
- if (!stale) {
500
- committedValue = value;
501
- return value;
502
- }
503
- }).then(function (result) {
504
- var snapshots = [];
505
- var updates = branch.diff(normalizeFirebaseValue(result.snapshot.val()), transactionPath);
506
- for (var path in updates) {
507
- if (!updates.hasOwnProperty(path)) { continue; }
508
- snapshots.push({
509
- path: path, value: updates[path], writeSerial: result.writeSerial || this$1._lastWriteSerial
510
- });
511
- }
512
- return {committed: !stale, snapshots: snapshots};
513
- }, function (error) {
514
- if (error.message === 'set' || error.message === 'disconnect') {
515
- return ref.once('value').then(function (snapshot) {
516
- return {committed: false, snapshots: [snapshot], writeSerial: this$1._lastWriteSerial};
517
- });
518
- }
519
- error.committedValue = committedValue;
520
- return Promise.reject(error);
521
- });
522
- };
523
-
524
- Fireworker.prototype._snapshotToJson = function _snapshotToJson (snapshot) {
525
- var path =
526
- decodeURIComponent(snapshot.ref.toString().replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
527
- return {
528
- path: path, value: normalizeFirebaseValue(snapshot.val()), writeSerial: this._lastWriteSerial
529
- };
530
- };
531
-
532
- Fireworker.prototype.onDisconnect = function onDisconnect (ref) {
533
- var url = ref.url;
534
- var method = ref.method;
535
- var value = ref.value;
536
-
537
- var onDisconnect = this._createRef(url).onDisconnect();
538
- return onDisconnect[method](value);
539
- };
540
-
541
- Fireworker.prototype._createRef = function _createRef (url, spec) {
542
- if (!this._app) { throw new Error('Must provide Firebase configuration data first'); }
543
- try {
544
- var ref = this._database.refFromURL(url);
545
- if (spec) {
546
- switch (spec.by) {
547
- case '$key': ref = ref.orderByKey(); break;
548
- case '$value': ref = ref.orderByValue(); break;
549
- default: ref = ref.orderByChild(spec.by); break;
435
+ branch.set(value);
436
+ if (!stale) {
437
+ committedValue = value;
438
+ return value;
550
439
  }
551
- if (spec.at !== undefined) { ref = ref.equalTo(spec.at); }
552
- else if (spec.from !== undefined) { ref = ref.startAt(spec.from); }
553
- else if (spec.to !== undefined) { ref = ref.endAt(spec.to); }
554
- if (spec.first !== undefined) { ref = ref.limitToFirst(spec.first); }
555
- else if (spec.last !== undefined) { ref = ref.limitToLast(spec.last); }
556
- }
557
- return ref;
558
- } catch (e) {
559
- e.extra = {url: url, spec: spec};
560
- throw e;
440
+ }).then(result => {
441
+ const snapshots = [];
442
+ const updates = branch.diff(normalizeFirebaseValue(result.snapshot.val()), transactionPath);
443
+ for (const path in updates) {
444
+ if (!updates.hasOwnProperty(path)) continue;
445
+ snapshots.push({
446
+ path, value: updates[path], writeSerial: result.writeSerial || this._lastWriteSerial
447
+ });
448
+ }
449
+ return {committed: !stale, snapshots};
450
+ }, error => {
451
+ if (error.message === 'set' || error.message === 'disconnect') {
452
+ return ref.once('value').then(snapshot => {
453
+ return {committed: false, snapshots: [snapshot], writeSerial: this._lastWriteSerial};
454
+ });
455
+ }
456
+ error.committedValue = committedValue;
457
+ return Promise.reject(error);
458
+ });
561
459
  }
562
- };
563
460
 
564
- Fireworker.expose = function expose (fn, name) {
565
- name = name || fn.name;
566
- if (!name) {
567
- Fireworker._signalStaticConfigError(
568
- new Error(("Cannot expose a function with no name: " + fn)));
569
- }
570
- if (Fireworker._exposed.hasOwnProperty(name)) {
571
- Fireworker._signalStaticConfigError(new Error(("Function " + name + "() already exposed")));
572
- }
573
- if (Fireworker._firstMessageReceived) {
574
- Fireworker._signalStaticConfigError(new Error('Too late to expose function, worker in use'));
461
+ _snapshotToJson(snapshot) {
462
+ const path =
463
+ decodeURIComponent(snapshot.ref.toString().replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
464
+ return {
465
+ path, value: normalizeFirebaseValue(snapshot.val()), writeSerial: this._lastWriteSerial
466
+ };
575
467
  }
576
- Fireworker._exposed[name] = fn;
577
- };
578
468
 
579
- Fireworker.setDatabaseWrapperCallback = function setDatabaseWrapperCallback (fn) {
580
- if (Fireworker._databaseWrapperCallback) {
581
- Fireworker._signalStaticConfigError(new Error('Database wrapper callback already set'));
469
+ onDisconnect({url, method, value}) {
470
+ const onDisconnect = this._createRef(url).onDisconnect();
471
+ return onDisconnect[method](value);
582
472
  }
583
- if (Fireworker._firstMessageReceived) {
584
- Fireworker._signalStaticConfigError(
585
- new Error('Too late to set database wrapper callback, worker in use'));
473
+
474
+ _createRef(url, spec) {
475
+ if (!this._app) throw new Error('Must provide Firebase configuration data first');
476
+ try {
477
+ let ref = this._database.refFromURL(url);
478
+ if (spec) {
479
+ switch (spec.by) {
480
+ case '$key': ref = ref.orderByKey(); break;
481
+ case '$value': ref = ref.orderByValue(); break;
482
+ default: ref = ref.orderByChild(spec.by); break;
483
+ }
484
+ if (spec.at !== undefined) ref = ref.equalTo(spec.at);
485
+ else if (spec.from !== undefined) ref = ref.startAt(spec.from);
486
+ else if (spec.to !== undefined) ref = ref.endAt(spec.to);
487
+ if (spec.first !== undefined) ref = ref.limitToFirst(spec.first);
488
+ else if (spec.last !== undefined) ref = ref.limitToLast(spec.last);
489
+ }
490
+ return ref;
491
+ } catch (e) {
492
+ e.extra = {url, spec};
493
+ throw e;
494
+ }
586
495
  }
587
- Fireworker._databaseWrapperCallback = fn;
588
- };
589
496
 
590
- Fireworker._signalStaticConfigError = function _signalStaticConfigError (error) {
591
- if (!Fireworker._staticConfigError) { Fireworker._staticConfigError = error; }
592
- for (var i = 0, list = fireworkers; i < list.length; i += 1) {
593
- var fireworker = list[i];
497
+ static expose(fn, name) {
498
+ name = name || fn.name;
499
+ if (!name) {
500
+ Fireworker._signalStaticConfigError(
501
+ new Error(`Cannot expose a function with no name: ${fn}`));
502
+ }
503
+ if (Fireworker._exposed.hasOwnProperty(name)) {
504
+ Fireworker._signalStaticConfigError(new Error(`Function ${name}() already exposed`));
505
+ }
506
+ if (Fireworker._firstMessageReceived) {
507
+ Fireworker._signalStaticConfigError(new Error('Too late to expose function, worker in use'));
508
+ }
509
+ Fireworker._exposed[name] = fn;
510
+ }
594
511
 
595
- if (fireworker && !fireworker._configError) { fireworker._configError = error; }
512
+ static setDatabaseWrapperCallback(fn) {
513
+ if (Fireworker._databaseWrapperCallback) {
514
+ Fireworker._signalStaticConfigError(new Error('Database wrapper callback already set'));
515
+ }
516
+ if (Fireworker._firstMessageReceived) {
517
+ Fireworker._signalStaticConfigError(
518
+ new Error('Too late to set database wrapper callback, worker in use'));
519
+ }
520
+ Fireworker._databaseWrapperCallback = fn;
596
521
  }
597
- throw error;
598
- };
599
522
 
600
- Object.defineProperties( Fireworker.prototype, prototypeAccessors$1 );
523
+ static _signalStaticConfigError(error) {
524
+ if (!Fireworker._staticConfigError) Fireworker._staticConfigError = error;
525
+ for (const fireworker of fireworkers) {
526
+ if (fireworker && !fireworker._configError) fireworker._configError = error;
527
+ }
528
+ throw error;
529
+ }
530
+ }
601
531
 
602
532
  Fireworker._exposed = {};
603
533
  Fireworker._firstMessageReceived = false;
@@ -605,11 +535,9 @@
605
535
  Fireworker._staticConfigError = undefined;
606
536
 
607
537
  function errorToJson(error) {
608
- var json = {name: error.name, message: error.message};
609
- var propertyNames = Object.getOwnPropertyNames(error);
610
- for (var i = 0, list = propertyNames; i < list.length; i += 1) {
611
- var propertyName = list[i];
612
-
538
+ const json = {name: error.name, message: error.message};
539
+ const propertyNames = Object.getOwnPropertyNames(error);
540
+ for (const propertyName of propertyNames) {
613
541
  json[propertyName] = error[propertyName];
614
542
  }
615
543
  return json;
@@ -617,27 +545,27 @@
617
545
 
618
546
  function normalizeFirebaseValue(value) {
619
547
  if (Array.isArray(value)) {
620
- var normalValue = {};
621
- for (var i = 0; i < value.length; i++) {
622
- var item = value[i];
623
- if (item === undefined || item === null) { continue; }
548
+ const normalValue = {};
549
+ for (let i = 0; i < value.length; i++) {
550
+ const item = value[i];
551
+ if (item === undefined || item === null) continue;
624
552
  normalValue[i] = normalizeFirebaseValue(item);
625
553
  }
626
554
  return normalValue;
627
555
  }
628
556
  if (value instanceof Object) {
629
- for (var key in value) {
630
- if (value.hasOwnProperty(key)) { value[key] = normalizeFirebaseValue(value[key]); }
557
+ for (const key in value) {
558
+ if (value.hasOwnProperty(key)) value[key] = normalizeFirebaseValue(value[key]);
631
559
  }
632
560
  }
633
561
  return value;
634
562
  }
635
563
 
636
564
  function userToJson(user) {
637
- if (!user) { return Promise.resolve(user); }
638
- var json = user.toJSON();
565
+ if (!user) return Promise.resolve(user);
566
+ const json = user.toJSON();
639
567
  delete json.stsTokenManager;
640
- return user.getIdTokenResult().then(function (result) {
568
+ return user.getIdTokenResult().then(result => {
641
569
  delete result.claims.exp;
642
570
  delete result.claims.iat;
643
571
  json.claims = result.claims;
@@ -647,37 +575,37 @@
647
575
 
648
576
 
649
577
  function areEqualNormalFirebaseValues(a, b) {
650
- if (a === b) { return true; }
651
- if ((a === null || a === undefined) && (b === null || b === undefined)) { return true; }
652
- if (a === null || b === null) { return false; }
653
- if (!(typeof a === 'object' && typeof b === 'object')) { return false; }
654
- for (var key in a) {
655
- if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { return false; }
656
- if (!areEqualNormalFirebaseValues(a[key], b[key])) { return false; }
578
+ if (a === b) return true;
579
+ if ((a === null || a === undefined) && (b === null || b === undefined)) return true;
580
+ if (a === null || b === null) return false;
581
+ if (!(typeof a === 'object' && typeof b === 'object')) return false;
582
+ for (const key in a) {
583
+ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return false;
584
+ if (!areEqualNormalFirebaseValues(a[key], b[key])) return false;
657
585
  }
658
- for (var key$1 in b) {
659
- if (!a.hasOwnProperty(key$1) || !b.hasOwnProperty(key$1)) { return false; }
586
+ for (const key in b) {
587
+ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return false;
660
588
  }
661
589
  return true;
662
590
  }
663
591
 
664
592
  function areEqualValues(a, b) {
665
- if (a === b) { return true; }
666
- if (a === null && b === null || a === undefined && b === undefined) { return true; }
667
- if (a === null || b === null || a === undefined || b === undefined) { return false; }
668
- if (!(typeof a === 'object' && typeof b === 'object')) { return false; }
669
- for (var key in a) {
670
- if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { return false; }
671
- if (!areEqualValues(a[key], b[key])) { return false; }
593
+ if (a === b) return true;
594
+ if (a === null && b === null || a === undefined && b === undefined) return true;
595
+ if (a === null || b === null || a === undefined || b === undefined) return false;
596
+ if (!(typeof a === 'object' && typeof b === 'object')) return false;
597
+ for (const key in a) {
598
+ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return false;
599
+ if (!areEqualValues(a[key], b[key])) return false;
672
600
  }
673
- for (var key$1 in b) {
674
- if (!a.hasOwnProperty(key$1) || !b.hasOwnProperty(key$1)) { return false; }
601
+ for (const key in b) {
602
+ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return false;
675
603
  }
676
604
  if (Array.isArray(a) || Array.isArray(b)) {
677
- if (!Array.isArray(a) || !Array.isArray(b)) { return false; }
678
- if (a.length !== b.length) { return false; }
679
- for (var i = 0; i < a.length; i++) {
680
- if (!areEqualValues(a[i], b[i])) { return false; }
605
+ if (!Array.isArray(a) || !Array.isArray(b)) return false;
606
+ if (a.length !== b.length) return false;
607
+ for (let i = 0; i < a.length; i++) {
608
+ if (!areEqualValues(a[i], b[i])) return false;
681
609
  }
682
610
  }
683
611
  return true;
@@ -699,6 +627,6 @@
699
627
 
700
628
  return Fireworker;
701
629
 
702
- })));
630
+ }));
703
631
 
704
632
  //# sourceMappingURL=worker.umd.js.map