@pomwik/afterdb-react 0.0.0-stage → 0.20.2

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.
Files changed (52) hide show
  1. package/CHANGES-FROM-UPSTREAM.md +59 -0
  2. package/LICENSE +177 -0
  3. package/NOTICE +9 -0
  4. package/README.md +10 -2
  5. package/dist/RealmContext.d.ts +153 -0
  6. package/dist/RealmContext.d.ts.map +1 -0
  7. package/dist/RealmProvider.d.ts +95 -0
  8. package/dist/RealmProvider.d.ts.map +1 -0
  9. package/dist/cachedCollection.d.ts +58 -0
  10. package/dist/cachedCollection.d.ts.map +1 -0
  11. package/dist/cachedObject.d.ts +48 -0
  12. package/dist/cachedObject.d.ts.map +1 -0
  13. package/dist/helpers.d.ts +22 -0
  14. package/dist/helpers.d.ts.map +1 -0
  15. package/dist/index.cjs +2818 -0
  16. package/dist/index.cjs.map +1 -0
  17. package/dist/index.d.ts +100 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +2809 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/tsconfig.types.tsbuildinfo +1 -0
  22. package/dist/types.d.ts +64 -0
  23. package/dist/types.d.ts.map +1 -0
  24. package/dist/useObject.d.ts +30 -0
  25. package/dist/useObject.d.ts.map +1 -0
  26. package/dist/useQuery.d.ts +31 -0
  27. package/dist/useQuery.d.ts.map +1 -0
  28. package/dist/useRealm.d.ts +12 -0
  29. package/dist/useRealm.d.ts.map +1 -0
  30. package/package.json +117 -4
  31. package/src/RealmContext.ts +196 -0
  32. package/src/RealmProvider.tsx +251 -0
  33. package/src/__tests__/RealmProvider.test.tsx +583 -0
  34. package/src/__tests__/createRealmTestContext.ts +68 -0
  35. package/src/__tests__/helpers.ts +35 -0
  36. package/src/__tests__/mocks.ts +154 -0
  37. package/src/__tests__/profileHook.tsx +76 -0
  38. package/src/__tests__/setup.ts +22 -0
  39. package/src/__tests__/tsconfig.json +14 -0
  40. package/src/__tests__/useObjectHook.test.tsx +158 -0
  41. package/src/__tests__/useObjectRender.test.tsx +630 -0
  42. package/src/__tests__/useQueryHook.test.tsx +209 -0
  43. package/src/__tests__/useQueryRender.test.tsx +463 -0
  44. package/src/cachedCollection.ts +210 -0
  45. package/src/cachedObject.ts +164 -0
  46. package/src/helpers.ts +60 -0
  47. package/src/index.tsx +130 -0
  48. package/src/runtime.d.ts +31 -0
  49. package/src/types.ts +92 -0
  50. package/src/useObject.tsx +227 -0
  51. package/src/useQuery.tsx +205 -0
  52. package/src/useRealm.tsx +41 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,2818 @@
1
+ 'use strict';
2
+
3
+ var Realm = require('realm');
4
+ var React = require('react');
5
+
6
+ ////////////////////////////////////////////////////////////////////////////
7
+ //
8
+ // Copyright 2022 Realm Inc.
9
+ //
10
+ // Licensed under the Apache License, Version 2.0 (the "License");
11
+ // you may not use this file except in compliance with the License.
12
+ // You may obtain a copy of the License at
13
+ //
14
+ // http://www.apache.org/licenses/LICENSE-2.0
15
+ //
16
+ // Unless required by applicable law or agreed to in writing, software
17
+ // distributed under the License is distributed on an "AS IS" BASIS,
18
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ // See the License for the specific language governing permissions and
20
+ // limitations under the License.
21
+ //
22
+ ////////////////////////////////////////////////////////////////////////////
23
+ const numericRegEx = /^-?\d+$/;
24
+ function getCacheKey(id) {
25
+ return `${id}`;
26
+ }
27
+ /**
28
+ * Creates a proxy around a {@link Realm.Collection} that will create new {@link Realm.Object}
29
+ * references on any relevant change (update, insert, deletion) and return the same
30
+ * object reference if no changes have occurred since the last access.
31
+ *
32
+ * This makes the {@link Realm.Collection} behaves in an immutable way, as React expects, so
33
+ * that a {@link Realm.Object} can be wrapped in {@link React.memo} to prevent unnecessary
34
+ * rendering (see {@link useQuery} hook).
35
+ * @param args {@link CachedCollectionArgs} object arguments
36
+ * @returns Proxy object wrapping the collection
37
+ */
38
+ function createCachedCollection({ collection, realm, updateCallback, updatedRef, objectCache = new Map(), isDerived = false, keyPaths, }) {
39
+ const cachedCollectionHandler = {
40
+ get: function (target, key, receiver) {
41
+ // Pass functions through
42
+ const value = Reflect.get(target, key, receiver);
43
+ if (typeof value === "function") {
44
+ if (key === "sorted" || key === "filtered") {
45
+ return (...args) => {
46
+ const col = Reflect.apply(value, target, args);
47
+ const { collection: newCol } = createCachedCollection({
48
+ collection: col,
49
+ realm,
50
+ updateCallback,
51
+ updatedRef,
52
+ objectCache,
53
+ isDerived: true,
54
+ keyPaths,
55
+ });
56
+ return newCol;
57
+ };
58
+ }
59
+ return value;
60
+ }
61
+ // If the key is not numeric, pass it through
62
+ if (typeof key === "symbol" || !numericRegEx.test(key)) {
63
+ return value;
64
+ }
65
+ // If the key is numeric, check if we have a cached object for this key
66
+ const index = Number(key);
67
+ const object = target[index];
68
+ // If the collection is modeled in a way that objects can be null
69
+ // then we should return null instead of undefined to stay semantically
70
+ // correct
71
+ if (object === null) {
72
+ return null;
73
+ }
74
+ else if (typeof object === "undefined") {
75
+ // If there is no object at this index, return undefined
76
+ return undefined;
77
+ }
78
+ const objectId = object._objectKey();
79
+ const cacheKey = getCacheKey(objectId);
80
+ // If we do, return it...
81
+ if (objectCache.get(cacheKey)) {
82
+ return objectCache.get(cacheKey);
83
+ }
84
+ // If not then this index has either not been accessed before, or has been invalidated due
85
+ // to a modification. Fetch it from the collection and store it in the cache
86
+ objectCache.set(cacheKey, object);
87
+ return object;
88
+ },
89
+ };
90
+ const cachedCollectionResult = new Proxy(collection, cachedCollectionHandler);
91
+ const listenerCallback = (listenerCollection, changes) => {
92
+ if (changes.deletions.length > 0 || changes.insertions.length > 0 || changes.newModifications.length > 0) {
93
+ // TODO: There is currently no way to rebuild the cache key from the changes array for deleted object.
94
+ // Until it is possible, we clear the cache on deletions.
95
+ // Blocking issue: https://github.com/realm/realm-core/issues/5220
96
+ // Possible solutions:
97
+ // a. the listenerCollection is a frozen copy of the collection before the deletion,
98
+ // allowing accessing the _objectKey() using listenerCollection[index]._objectKey()
99
+ // b. the callback provides an array of changed objectIds
100
+ if (changes.deletions.length > 0) {
101
+ objectCache.clear();
102
+ }
103
+ // Item(s) were modified, just clear them from the cache so that we return new instances for them
104
+ changes.newModifications.forEach((index) => {
105
+ const objectId = listenerCollection[index]._objectKey();
106
+ if (objectId) {
107
+ const cacheKey = getCacheKey(objectId);
108
+ if (objectCache.has(cacheKey)) {
109
+ objectCache.delete(cacheKey);
110
+ }
111
+ }
112
+ });
113
+ updatedRef.current = true;
114
+ updateCallback();
115
+ }
116
+ };
117
+ let setImmediateId = undefined;
118
+ if (!isDerived) {
119
+ // If we are in a transaction, then push adding the listener to the event loop. This will allow the write transaction to finish.
120
+ // see https://github.com/realm/realm-js/issues/4375
121
+ if (realm.isInTransaction) {
122
+ setImmediateId = setImmediate(() => {
123
+ collection.addListener(listenerCallback, keyPaths);
124
+ });
125
+ }
126
+ else {
127
+ collection.addListener(listenerCallback, keyPaths);
128
+ }
129
+ }
130
+ const tearDown = () => {
131
+ if (!isDerived) {
132
+ if (setImmediateId) {
133
+ clearImmediate(setImmediateId);
134
+ setImmediateId = undefined;
135
+ }
136
+ collection.removeListener(listenerCallback);
137
+ objectCache.clear();
138
+ }
139
+ };
140
+ return { collection: cachedCollectionResult, tearDown };
141
+ }
142
+
143
+ ////////////////////////////////////////////////////////////////////////////
144
+ //
145
+ // Copyright 2022 Realm Inc.
146
+ //
147
+ // Licensed under the Apache License, Version 2.0 (the "License");
148
+ // you may not use this file except in compliance with the License.
149
+ // You may obtain a copy of the License at
150
+ //
151
+ // http://www.apache.org/licenses/LICENSE-2.0
152
+ //
153
+ // Unless required by applicable law or agreed to in writing, software
154
+ // distributed under the License is distributed on an "AS IS" BASIS,
155
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
156
+ // See the License for the specific language governing permissions and
157
+ // limitations under the License.
158
+ //
159
+ ////////////////////////////////////////////////////////////////////////////
160
+ /**
161
+ * Creates a proxy around a {@link Realm.Object} that will return a new reference
162
+ * on any relevant update to the object itself. It also wraps accesses to {@link Realm.List}
163
+ * attributes into a {@link cachedCollection}, so that any update, insert or deletion to the
164
+ * list will also return a new object reference.
165
+ *
166
+ * See {@link cachedCollection} and the `useObject` hook for description of how this
167
+ * helps prevent unnecessary rendering.
168
+ * @param args - {@link CachedObjectArgs} object arguments
169
+ * @returns Proxy object wrapping the {@link Realm.Object}
170
+ */
171
+ function createCachedObject({ object, realm, updateCallback, updatedRef, keyPaths, }) {
172
+ const listCaches = new Map();
173
+ const listTearDowns = [];
174
+ // If the object doesn't exist, just return it with an noop tearDown
175
+ //
176
+ if (object === null) {
177
+ return { object, tearDown: () => undefined };
178
+ }
179
+ // Create a cache for any Realm.List properties on the object
180
+ for (const key of object.keys()) {
181
+ //@ts-expect-error - TS doesn't know that the key is a valid property
182
+ const value = object[key];
183
+ if (value instanceof Realm.List && value.type === "object") {
184
+ const updatedRef = { current: true };
185
+ const { collection, tearDown } = createCachedCollection({ collection: value, realm, updateCallback, updatedRef });
186
+ listCaches.set(key, { collection, updatedRef });
187
+ listTearDowns.push(tearDown);
188
+ }
189
+ }
190
+ // This Proxy handler intercepts any accesses into properties of the cached object
191
+ // of type `Realm.List`, and returns a `cachedCollection` wrapping those properties
192
+ // to allow changes in the list to trigger re-renders
193
+ const cachedObjectHandler = {
194
+ get: function (target, key, receiver) {
195
+ const value = Reflect.get(target, key, receiver);
196
+ // If its a Realm.List we need to add a proxy cache around it
197
+ if (value instanceof Realm.List && value.type === "object") {
198
+ if (listCaches.has(key)) {
199
+ // Return a new proxy wrapping the cachedCollection so that its reference gets updated,
200
+ // otherwise the list component will not re-render. The cachedCollection then ensures that
201
+ // only the modified children of the list component actually re-render.
202
+ const { collection, updatedRef } = listCaches.get(key);
203
+ if (updatedRef.current) {
204
+ updatedRef.current = false;
205
+ const proxyCollection = new Proxy(collection, {});
206
+ listCaches.set(key, { collection: proxyCollection, updatedRef });
207
+ return proxyCollection;
208
+ }
209
+ return collection;
210
+ }
211
+ }
212
+ return value;
213
+ },
214
+ };
215
+ const cachedObjectResult = new Proxy(object, cachedObjectHandler);
216
+ const listenerCallback = (obj, changes) => {
217
+ updatedRef.current = true;
218
+ if (changes.deleted) {
219
+ updateCallback();
220
+ }
221
+ else if (changes.changedProperties.length > 0) {
222
+ // Don't force a second re-render if any of the changed properties is a Realm.List,
223
+ // as the List's cachedCollection will force a re-render itself
224
+ const anyListPropertyModified = changes.changedProperties.some((property) => {
225
+ return obj[property] instanceof Realm.List && obj[property].type === "object";
226
+ });
227
+ const shouldRerender = !anyListPropertyModified;
228
+ if (shouldRerender) {
229
+ updateCallback();
230
+ }
231
+ }
232
+ };
233
+ // We cannot add a listener to an invalid object
234
+ if (object.isValid()) {
235
+ // If we are in a transaction, then push adding the listener to the event loop. This will allow the write transaction to finish.
236
+ // see https://github.com/realm/realm-js/issues/4375
237
+ if (realm.isInTransaction) {
238
+ setImmediate(() => {
239
+ object.addListener(listenerCallback, keyPaths);
240
+ });
241
+ }
242
+ else {
243
+ object.addListener(listenerCallback, keyPaths);
244
+ }
245
+ }
246
+ const tearDown = () => {
247
+ object.removeListener(listenerCallback);
248
+ for (const listTearDown of listTearDowns) {
249
+ listTearDown();
250
+ }
251
+ };
252
+ return { object: cachedObjectResult, tearDown };
253
+ }
254
+
255
+ ////////////////////////////////////////////////////////////////////////////
256
+ //
257
+ // Copyright 2023 Realm Inc.
258
+ //
259
+ // Licensed under the Apache License, Version 2.0 (the "License");
260
+ // you may not use this file except in compliance with the License.
261
+ // You may obtain a copy of the License at
262
+ //
263
+ // http://www.apache.org/licenses/LICENSE-2.0
264
+ //
265
+ // Unless required by applicable law or agreed to in writing, software
266
+ // distributed under the License is distributed on an "AS IS" BASIS,
267
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
268
+ // See the License for the specific language governing permissions and
269
+ // limitations under the License.
270
+ //
271
+ ////////////////////////////////////////////////////////////////////////////
272
+ // Convenience function that returns the correct type for the objectForPrimaryKey function
273
+ // Since we don't have a combined declaration for this function, typescript needs to know
274
+ // which return to use based on the typeof the type argument
275
+ function getObjectForPrimaryKey(realm, type, primaryKey) {
276
+ return typeof type === "string"
277
+ ? realm.objectForPrimaryKey(type, primaryKey)
278
+ : realm.objectForPrimaryKey(type, primaryKey);
279
+ }
280
+ // Convenience function that returns the correct type for the objects function
281
+ // Since we don't have a combined declaration for this function, typescript needs to know
282
+ // which return to use based on the typeof the type argument
283
+ function getObjects(realm, type) {
284
+ return (typeof type === "string" ? realm.objects(type) : realm.objects(type));
285
+ }
286
+ function isClassModelConstructor(value) {
287
+ return Object.getPrototypeOf(value) === Realm.Object;
288
+ }
289
+
290
+ ////////////////////////////////////////////////////////////////////////////
291
+ //
292
+ // Copyright 2021 Realm Inc.
293
+ //
294
+ // Licensed under the Apache License, Version 2.0 (the "License");
295
+ // you may not use this file except in compliance with the License.
296
+ // You may obtain a copy of the License at
297
+ //
298
+ // http://www.apache.org/licenses/LICENSE-2.0
299
+ //
300
+ // Unless required by applicable law or agreed to in writing, software
301
+ // distributed under the License is distributed on an "AS IS" BASIS,
302
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
303
+ // See the License for the specific language governing permissions and
304
+ // limitations under the License.
305
+ //
306
+ ////////////////////////////////////////////////////////////////////////////
307
+ /**
308
+ * Generates the `useObject` hook from a given `useRealm` hook.
309
+ * @param useRealm - Hook that returns an open Realm instance
310
+ * @returns useObject - Hook that is used to gain access to a single Realm object from a primary key
311
+ */
312
+ function createUseObject(useRealm) {
313
+ function useObject(type, primaryKey, keyPaths) {
314
+ const realm = useRealm();
315
+ // Create a forceRerender function for the cachedObject to use as its updateCallback, so that
316
+ // the cachedObject can force the component using this hook to re-render when a change occurs.
317
+ const [, forceRerender] = React.useReducer((x) => x + 1, 0);
318
+ // Get the original object from the realm, so we can check if it exists
319
+ const originalObject = getObjectForPrimaryKey(realm, type, primaryKey);
320
+ // Store the primaryKey as a ref, since when it is an objectId or UUID, it will be a new instance on every render
321
+ const primaryKeyRef = React.useRef(primaryKey);
322
+ const collectionRef = React.useRef(getObjects(realm, type));
323
+ const objectRef = React.useRef(null);
324
+ const updatedRef = React.useRef(true);
325
+ // Initializing references with a function call or class constructor will
326
+ // cause the function or constructor to be called on ever render.
327
+ // Even though this value is thrown away on subsequent renders, `createCachedObject` will end up registering a listener.
328
+ // Therefore, we initialize the references with null, and only create the object if it is null
329
+ // Ref: https://github.com/facebook/react/issues/14490
330
+ const cachedObjectRef = React.useRef(null);
331
+ const memoizedKeyPaths = React.useMemo(() => (typeof keyPaths === "string" ? [keyPaths] : keyPaths),
332
+ /* eslint-disable-next-line react-hooks/exhaustive-deps -- Memoizing the keyPaths to avoid renders */
333
+ [JSON.stringify(keyPaths)]);
334
+ if (!cachedObjectRef.current) {
335
+ cachedObjectRef.current = createCachedObject({
336
+ object: originalObject ?? null,
337
+ realm,
338
+ updateCallback: forceRerender,
339
+ updatedRef,
340
+ keyPaths: memoizedKeyPaths,
341
+ });
342
+ }
343
+ // Create a ref, since the object returned from `objectForPrimaryKey` is always going to have a different reference
344
+ const originalObjectRef = React.useRef(originalObject);
345
+ // Wrap the cachedObject in useMemo, so we only replace it with a new instance if `primaryKey` or `type` change
346
+ const { object, tearDown } = React.useMemo(
347
+ // TODO: There will be an upcoming breaking change that makes objectForPrimaryKey return null
348
+ // When this is implemented, remove `?? null`
349
+ () => {
350
+ // This should never happen, but if it does, we want to return a null result
351
+ if (!cachedObjectRef.current) {
352
+ return { object: null, tearDown: () => undefined };
353
+ }
354
+ // Re-instantiate the cachedObject if the primaryKey has changed or the originalObject has gone from null to not null
355
+ if (!arePrimaryKeysIdentical(primaryKey, primaryKeyRef.current) ||
356
+ (!originalObjectRef.current && originalObject)) {
357
+ cachedObjectRef.current = createCachedObject({
358
+ object: originalObject ?? null,
359
+ realm,
360
+ updateCallback: forceRerender,
361
+ updatedRef,
362
+ keyPaths: memoizedKeyPaths,
363
+ });
364
+ originalObjectRef.current = originalObject;
365
+ // Primary key has updated, so update the reference
366
+ primaryKeyRef.current = primaryKey;
367
+ // Signal that the object reference needs to be updated
368
+ updatedRef.current = true;
369
+ }
370
+ return cachedObjectRef.current;
371
+ }, [realm, originalObject, primaryKey, memoizedKeyPaths]);
372
+ // Invoke the tearDown of the cachedObject when useObject is unmounted
373
+ React.useEffect(() => {
374
+ return tearDown;
375
+ }, [tearDown]);
376
+ // If the object doesn't exist, listen for insertions to the collection and force a rerender if the inserted object has the correct primary key
377
+ React.useEffect(() => {
378
+ const collection = collectionRef.current;
379
+ const collectionListener = (_, changes) => {
380
+ const primaryKeyProperty = collection?.[0]?.objectSchema()?.primaryKey;
381
+ for (const index of changes.insertions) {
382
+ const object = collection[index];
383
+ if (primaryKeyProperty) {
384
+ //@ts-expect-error - if the primaryKeyProperty exists, then it is indexable. However, we don't allow it when we don't actually know the type of the object
385
+ const insertedPrimaryKey = object[primaryKeyProperty];
386
+ if (arePrimaryKeysIdentical(insertedPrimaryKey, primaryKeyRef.current)) {
387
+ forceRerender();
388
+ collection.removeListener(collectionListener);
389
+ break;
390
+ }
391
+ }
392
+ }
393
+ };
394
+ if (!originalObjectRef.current) {
395
+ collection.addListener(collectionListener);
396
+ }
397
+ return () => {
398
+ // If the app is closing, the realm will be closed and the listener does not need to be removed if
399
+ if (!realm.isClosed && collection) {
400
+ collection.removeListener(collectionListener);
401
+ }
402
+ };
403
+ }, [realm, type, forceRerender]);
404
+ // If the object has been deleted or doesn't exist for the given primary key, just return null
405
+ if (!object?.isValid()) {
406
+ return null;
407
+ }
408
+ if (updatedRef.current) {
409
+ // Wrap object in a proxy to update the reference on rerender ( should only rerender when something has changed )
410
+ objectRef.current = new Proxy(object, {});
411
+ updatedRef.current = false;
412
+ }
413
+ // This will never be undefined, but the type system doesn't know that
414
+ return objectRef.current;
415
+ }
416
+ return function useObjectOverload(typeOrOptions, primaryKey, keyPaths) {
417
+ if (typeof typeOrOptions === "string" || isClassModelConstructor(typeOrOptions)) {
418
+ if (typeof primaryKey === "undefined") {
419
+ throw new Error("Expected a primary key");
420
+ }
421
+ /* eslint-disable-next-line react-hooks/rules-of-hooks -- We're calling `useQuery` once in any of the brances */
422
+ return useObject(typeOrOptions, primaryKey, keyPaths);
423
+ }
424
+ else {
425
+ const { type, primaryKey, keyPaths } = typeOrOptions;
426
+ /* eslint-disable-next-line react-hooks/rules-of-hooks -- We're calling `useQuery` once in any of the brances */
427
+ return useObject(type, primaryKey, keyPaths);
428
+ }
429
+ };
430
+ }
431
+ // This is a helper function that determines if two primary keys are equal. It will also handle the case where the primary key is an ObjectId or UUID
432
+ function arePrimaryKeysIdentical(a, b) {
433
+ if (typeof a !== typeof b) {
434
+ return false;
435
+ }
436
+ if (typeof a === "string" || typeof a === "number") {
437
+ return a === b;
438
+ }
439
+ if (a instanceof Realm.BSON.ObjectId && b instanceof Realm.BSON.ObjectId) {
440
+ return a.toHexString() === b.toHexString();
441
+ }
442
+ if (a instanceof Realm.BSON.UUID && b instanceof Realm.BSON.UUID) {
443
+ return a.toHexString() === b.toHexString();
444
+ }
445
+ return false;
446
+ }
447
+
448
+ ////////////////////////////////////////////////////////////////////////////
449
+ //
450
+ // Copyright 2021 Realm Inc.
451
+ //
452
+ // Licensed under the Apache License, Version 2.0 (the "License");
453
+ // you may not use this file except in compliance with the License.
454
+ // You may obtain a copy of the License at
455
+ //
456
+ // http://www.apache.org/licenses/LICENSE-2.0
457
+ //
458
+ // Unless required by applicable law or agreed to in writing, software
459
+ // distributed under the License is distributed on an "AS IS" BASIS,
460
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
461
+ // See the License for the specific language governing permissions and
462
+ // limitations under the License.
463
+ //
464
+ ////////////////////////////////////////////////////////////////////////////
465
+ /**
466
+ * Maps a value to itself
467
+ */
468
+ function identity(value) {
469
+ return value;
470
+ }
471
+ /**
472
+ * Generates the `useQuery` hook from a given `useRealm` hook.
473
+ * @param useRealm - Hook that returns an open Realm instance
474
+ * @returns useObject - Hook that is used to gain access to a {@link Realm.Collection}
475
+ */
476
+ function createUseQuery(useRealm) {
477
+ function useQuery({ type, query = identity, keyPaths }, deps = []) {
478
+ const realm = useRealm();
479
+ // We need to add the type to the deps, so that if the type changes, the query will be re-run.
480
+ // This will be saved in an array which will be spread into the provided deps.
481
+ const requiredDeps = [type];
482
+ // Create a forceRerender function for the cachedCollection to use as its updateCallback, so that
483
+ // the cachedCollection can force the component using this hook to re-render when a change occurs.
484
+ const [, forceRerender] = React.useReducer((x) => x + 1, 0);
485
+ const collectionRef = React.useRef(null);
486
+ const updatedRef = React.useRef(true);
487
+ const queryCallbackRef = React.useRef(null);
488
+ /* eslint-disable-next-line react-hooks/exhaustive-deps -- We want the user of this hook to be able pass in the `query` function inline (without the need to `useCallback` on it)
489
+ This means that the query function is unstable and will be a redefined on each render of the component where `useQuery` is used
490
+ Therefore we use the `deps` array to memoize the query function internally, and only use the returned `queryCallback` */
491
+ const queryCallback = React.useCallback(query, [...deps, ...requiredDeps]);
492
+ // If the query function changes, we need to update the cachedCollection
493
+ if (queryCallbackRef.current !== queryCallback) {
494
+ queryCallbackRef.current = queryCallback;
495
+ updatedRef.current = true;
496
+ }
497
+ const queryResult = React.useMemo(() => {
498
+ return queryCallback(getObjects(realm, type));
499
+ }, [type, realm, queryCallback]);
500
+ const memoizedKeyPaths = React.useMemo(() => (typeof keyPaths === "string" ? [keyPaths] : keyPaths),
501
+ /* eslint-disable-next-line react-hooks/exhaustive-deps -- Memoizing the keyPaths to avoid renders */
502
+ [JSON.stringify(keyPaths)]);
503
+ // Wrap the cachedObject in useMemo, so we only replace it with a new instance if `realm` or `queryResult` change
504
+ const { collection, tearDown } = React.useMemo(() => {
505
+ return createCachedCollection({
506
+ collection: queryResult,
507
+ realm,
508
+ updateCallback: forceRerender,
509
+ updatedRef,
510
+ keyPaths: memoizedKeyPaths,
511
+ });
512
+ }, [realm, queryResult, memoizedKeyPaths]);
513
+ // Invoke the tearDown of the cachedCollection when useQuery is unmounted
514
+ React.useEffect(() => {
515
+ return tearDown;
516
+ }, [tearDown]);
517
+ // This makes sure the collection has a different reference on a rerender
518
+ // Also we are ensuring the type returned is Realm.Results, as this is known in this context
519
+ if (updatedRef.current) {
520
+ updatedRef.current = false;
521
+ collectionRef.current = new Proxy(collection, {});
522
+ }
523
+ // This will never not be defined, but the type system doesn't know that
524
+ return collectionRef.current;
525
+ }
526
+ return function useQueryOverload(typeOrOptionsOrQuery, queryOrDeps = identity, depsOrPartialOptions = []) {
527
+ const args = { typeOrOptionsOrQuery, queryOrDeps, depsOrPartialOptions };
528
+ /* eslint-disable react-hooks/rules-of-hooks -- We're calling `useQuery` once in any of the brances */
529
+ if (isTypeFunctionDeps(args)) {
530
+ return useQuery({ type: args.typeOrOptionsOrQuery, query: args.queryOrDeps }, args.depsOrPartialOptions);
531
+ }
532
+ if (isOptionsDepsNone(args)) {
533
+ return useQuery(args.typeOrOptionsOrQuery, Array.isArray(args.queryOrDeps) ? args.queryOrDeps : []);
534
+ }
535
+ if (isFunctionDepsOptions(args)) {
536
+ return useQuery({ ...args.depsOrPartialOptions, query: args.typeOrOptionsOrQuery }, args.queryOrDeps);
537
+ }
538
+ /* eslint-enable react-hooks/rules-of-hooks */
539
+ throw new Error("Unexpected arguments passed to useQuery");
540
+ };
541
+ }
542
+ function isTypeFunctionDeps(args) {
543
+ const { typeOrOptionsOrQuery, queryOrDeps, depsOrPartialOptions } = args;
544
+ return ((typeof typeOrOptionsOrQuery === "string" || isClassModelConstructor(typeOrOptionsOrQuery)) &&
545
+ typeof queryOrDeps === "function" &&
546
+ Array.isArray(depsOrPartialOptions));
547
+ }
548
+ function isOptionsDepsNone(args) {
549
+ const { typeOrOptionsOrQuery, queryOrDeps } = args;
550
+ return (typeof typeOrOptionsOrQuery === "object" &&
551
+ typeOrOptionsOrQuery !== null &&
552
+ (Array.isArray(queryOrDeps) || queryOrDeps === identity));
553
+ }
554
+ function isFunctionDepsOptions(args) {
555
+ const { typeOrOptionsOrQuery, queryOrDeps, depsOrPartialOptions } = args;
556
+ return (typeof typeOrOptionsOrQuery === "function" &&
557
+ Array.isArray(queryOrDeps) &&
558
+ typeof depsOrPartialOptions === "object" &&
559
+ depsOrPartialOptions !== null);
560
+ }
561
+
562
+ ////////////////////////////////////////////////////////////////////////////
563
+ //
564
+ // Copyright 2021 Realm Inc.
565
+ //
566
+ // Licensed under the Apache License, Version 2.0 (the "License");
567
+ // you may not use this file except in compliance with the License.
568
+ // You may obtain a copy of the License at
569
+ //
570
+ // http://www.apache.org/licenses/LICENSE-2.0
571
+ //
572
+ // Unless required by applicable law or agreed to in writing, software
573
+ // distributed under the License is distributed on an "AS IS" BASIS,
574
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
575
+ // See the License for the specific language governing permissions and
576
+ // limitations under the License.
577
+ //
578
+ ////////////////////////////////////////////////////////////////////////////
579
+ /**
580
+ * Generates a `useRealm` hook given a RealmContext. This allows access to the {@link Realm}
581
+ * instance anywhere within the RealmProvider.
582
+ * @param RealmContext - The context containing the {@link Realm} instance
583
+ * @returns useRealm - Hook that is used to gain access to the {@link Realm} instance
584
+ */
585
+ const createUseRealm = (RealmContext) => {
586
+ return function useRealm() {
587
+ // This is the context setup by `createRealmContext`
588
+ const context = React.useContext(RealmContext);
589
+ if (context === null) {
590
+ throw new Error("Realm context not found. Did you call useRealm() within a <RealmProvider/>?");
591
+ }
592
+ return context;
593
+ };
594
+ };
595
+
596
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
597
+
598
+ function getDefaultExportFromCjs (x) {
599
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
600
+ }
601
+
602
+ var lodash_isequal = {exports: {}};
603
+
604
+ /**
605
+ * Lodash (Custom Build) <https://lodash.com/>
606
+ * Build: `lodash modularize exports="npm" -o ./`
607
+ * Copyright JS Foundation and other contributors <https://js.foundation/>
608
+ * Released under MIT license <https://lodash.com/license>
609
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
610
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
611
+ */
612
+ lodash_isequal.exports;
613
+
614
+ (function (module, exports) {
615
+ /** Used as the size to enable large array optimizations. */
616
+ var LARGE_ARRAY_SIZE = 200;
617
+
618
+ /** Used to stand-in for `undefined` hash values. */
619
+ var HASH_UNDEFINED = '__lodash_hash_undefined__';
620
+
621
+ /** Used to compose bitmasks for value comparisons. */
622
+ var COMPARE_PARTIAL_FLAG = 1,
623
+ COMPARE_UNORDERED_FLAG = 2;
624
+
625
+ /** Used as references for various `Number` constants. */
626
+ var MAX_SAFE_INTEGER = 9007199254740991;
627
+
628
+ /** `Object#toString` result references. */
629
+ var argsTag = '[object Arguments]',
630
+ arrayTag = '[object Array]',
631
+ asyncTag = '[object AsyncFunction]',
632
+ boolTag = '[object Boolean]',
633
+ dateTag = '[object Date]',
634
+ errorTag = '[object Error]',
635
+ funcTag = '[object Function]',
636
+ genTag = '[object GeneratorFunction]',
637
+ mapTag = '[object Map]',
638
+ numberTag = '[object Number]',
639
+ nullTag = '[object Null]',
640
+ objectTag = '[object Object]',
641
+ promiseTag = '[object Promise]',
642
+ proxyTag = '[object Proxy]',
643
+ regexpTag = '[object RegExp]',
644
+ setTag = '[object Set]',
645
+ stringTag = '[object String]',
646
+ symbolTag = '[object Symbol]',
647
+ undefinedTag = '[object Undefined]',
648
+ weakMapTag = '[object WeakMap]';
649
+
650
+ var arrayBufferTag = '[object ArrayBuffer]',
651
+ dataViewTag = '[object DataView]',
652
+ float32Tag = '[object Float32Array]',
653
+ float64Tag = '[object Float64Array]',
654
+ int8Tag = '[object Int8Array]',
655
+ int16Tag = '[object Int16Array]',
656
+ int32Tag = '[object Int32Array]',
657
+ uint8Tag = '[object Uint8Array]',
658
+ uint8ClampedTag = '[object Uint8ClampedArray]',
659
+ uint16Tag = '[object Uint16Array]',
660
+ uint32Tag = '[object Uint32Array]';
661
+
662
+ /**
663
+ * Used to match `RegExp`
664
+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
665
+ */
666
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
667
+
668
+ /** Used to detect host constructors (Safari). */
669
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
670
+
671
+ /** Used to detect unsigned integer values. */
672
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
673
+
674
+ /** Used to identify `toStringTag` values of typed arrays. */
675
+ var typedArrayTags = {};
676
+ typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
677
+ typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
678
+ typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
679
+ typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
680
+ typedArrayTags[uint32Tag] = true;
681
+ typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
682
+ typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
683
+ typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
684
+ typedArrayTags[errorTag] = typedArrayTags[funcTag] =
685
+ typedArrayTags[mapTag] = typedArrayTags[numberTag] =
686
+ typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
687
+ typedArrayTags[setTag] = typedArrayTags[stringTag] =
688
+ typedArrayTags[weakMapTag] = false;
689
+
690
+ /** Detect free variable `global` from Node.js. */
691
+ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
692
+
693
+ /** Detect free variable `self`. */
694
+ var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
695
+
696
+ /** Used as a reference to the global object. */
697
+ var root = freeGlobal || freeSelf || Function('return this')();
698
+
699
+ /** Detect free variable `exports`. */
700
+ var freeExports = exports && !exports.nodeType && exports;
701
+
702
+ /** Detect free variable `module`. */
703
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
704
+
705
+ /** Detect the popular CommonJS extension `module.exports`. */
706
+ var moduleExports = freeModule && freeModule.exports === freeExports;
707
+
708
+ /** Detect free variable `process` from Node.js. */
709
+ var freeProcess = moduleExports && freeGlobal.process;
710
+
711
+ /** Used to access faster Node.js helpers. */
712
+ var nodeUtil = (function() {
713
+ try {
714
+ return freeProcess && freeProcess.binding && freeProcess.binding('util');
715
+ } catch (e) {}
716
+ }());
717
+
718
+ /* Node.js helper references. */
719
+ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
720
+
721
+ /**
722
+ * A specialized version of `_.filter` for arrays without support for
723
+ * iteratee shorthands.
724
+ *
725
+ * @private
726
+ * @param {Array} [array] The array to iterate over.
727
+ * @param {Function} predicate The function invoked per iteration.
728
+ * @returns {Array} Returns the new filtered array.
729
+ */
730
+ function arrayFilter(array, predicate) {
731
+ var index = -1,
732
+ length = array == null ? 0 : array.length,
733
+ resIndex = 0,
734
+ result = [];
735
+
736
+ while (++index < length) {
737
+ var value = array[index];
738
+ if (predicate(value, index, array)) {
739
+ result[resIndex++] = value;
740
+ }
741
+ }
742
+ return result;
743
+ }
744
+
745
+ /**
746
+ * Appends the elements of `values` to `array`.
747
+ *
748
+ * @private
749
+ * @param {Array} array The array to modify.
750
+ * @param {Array} values The values to append.
751
+ * @returns {Array} Returns `array`.
752
+ */
753
+ function arrayPush(array, values) {
754
+ var index = -1,
755
+ length = values.length,
756
+ offset = array.length;
757
+
758
+ while (++index < length) {
759
+ array[offset + index] = values[index];
760
+ }
761
+ return array;
762
+ }
763
+
764
+ /**
765
+ * A specialized version of `_.some` for arrays without support for iteratee
766
+ * shorthands.
767
+ *
768
+ * @private
769
+ * @param {Array} [array] The array to iterate over.
770
+ * @param {Function} predicate The function invoked per iteration.
771
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
772
+ * else `false`.
773
+ */
774
+ function arraySome(array, predicate) {
775
+ var index = -1,
776
+ length = array == null ? 0 : array.length;
777
+
778
+ while (++index < length) {
779
+ if (predicate(array[index], index, array)) {
780
+ return true;
781
+ }
782
+ }
783
+ return false;
784
+ }
785
+
786
+ /**
787
+ * The base implementation of `_.times` without support for iteratee shorthands
788
+ * or max array length checks.
789
+ *
790
+ * @private
791
+ * @param {number} n The number of times to invoke `iteratee`.
792
+ * @param {Function} iteratee The function invoked per iteration.
793
+ * @returns {Array} Returns the array of results.
794
+ */
795
+ function baseTimes(n, iteratee) {
796
+ var index = -1,
797
+ result = Array(n);
798
+
799
+ while (++index < n) {
800
+ result[index] = iteratee(index);
801
+ }
802
+ return result;
803
+ }
804
+
805
+ /**
806
+ * The base implementation of `_.unary` without support for storing metadata.
807
+ *
808
+ * @private
809
+ * @param {Function} func The function to cap arguments for.
810
+ * @returns {Function} Returns the new capped function.
811
+ */
812
+ function baseUnary(func) {
813
+ return function(value) {
814
+ return func(value);
815
+ };
816
+ }
817
+
818
+ /**
819
+ * Checks if a `cache` value for `key` exists.
820
+ *
821
+ * @private
822
+ * @param {Object} cache The cache to query.
823
+ * @param {string} key The key of the entry to check.
824
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
825
+ */
826
+ function cacheHas(cache, key) {
827
+ return cache.has(key);
828
+ }
829
+
830
+ /**
831
+ * Gets the value at `key` of `object`.
832
+ *
833
+ * @private
834
+ * @param {Object} [object] The object to query.
835
+ * @param {string} key The key of the property to get.
836
+ * @returns {*} Returns the property value.
837
+ */
838
+ function getValue(object, key) {
839
+ return object == null ? undefined : object[key];
840
+ }
841
+
842
+ /**
843
+ * Converts `map` to its key-value pairs.
844
+ *
845
+ * @private
846
+ * @param {Object} map The map to convert.
847
+ * @returns {Array} Returns the key-value pairs.
848
+ */
849
+ function mapToArray(map) {
850
+ var index = -1,
851
+ result = Array(map.size);
852
+
853
+ map.forEach(function(value, key) {
854
+ result[++index] = [key, value];
855
+ });
856
+ return result;
857
+ }
858
+
859
+ /**
860
+ * Creates a unary function that invokes `func` with its argument transformed.
861
+ *
862
+ * @private
863
+ * @param {Function} func The function to wrap.
864
+ * @param {Function} transform The argument transform.
865
+ * @returns {Function} Returns the new function.
866
+ */
867
+ function overArg(func, transform) {
868
+ return function(arg) {
869
+ return func(transform(arg));
870
+ };
871
+ }
872
+
873
+ /**
874
+ * Converts `set` to an array of its values.
875
+ *
876
+ * @private
877
+ * @param {Object} set The set to convert.
878
+ * @returns {Array} Returns the values.
879
+ */
880
+ function setToArray(set) {
881
+ var index = -1,
882
+ result = Array(set.size);
883
+
884
+ set.forEach(function(value) {
885
+ result[++index] = value;
886
+ });
887
+ return result;
888
+ }
889
+
890
+ /** Used for built-in method references. */
891
+ var arrayProto = Array.prototype,
892
+ funcProto = Function.prototype,
893
+ objectProto = Object.prototype;
894
+
895
+ /** Used to detect overreaching core-js shims. */
896
+ var coreJsData = root['__core-js_shared__'];
897
+
898
+ /** Used to resolve the decompiled source of functions. */
899
+ var funcToString = funcProto.toString;
900
+
901
+ /** Used to check objects for own properties. */
902
+ var hasOwnProperty = objectProto.hasOwnProperty;
903
+
904
+ /** Used to detect methods masquerading as native. */
905
+ var maskSrcKey = (function() {
906
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
907
+ return uid ? ('Symbol(src)_1.' + uid) : '';
908
+ }());
909
+
910
+ /**
911
+ * Used to resolve the
912
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
913
+ * of values.
914
+ */
915
+ var nativeObjectToString = objectProto.toString;
916
+
917
+ /** Used to detect if a method is native. */
918
+ var reIsNative = RegExp('^' +
919
+ funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
920
+ .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
921
+ );
922
+
923
+ /** Built-in value references. */
924
+ var Buffer = moduleExports ? root.Buffer : undefined,
925
+ Symbol = root.Symbol,
926
+ Uint8Array = root.Uint8Array,
927
+ propertyIsEnumerable = objectProto.propertyIsEnumerable,
928
+ splice = arrayProto.splice,
929
+ symToStringTag = Symbol ? Symbol.toStringTag : undefined;
930
+
931
+ /* Built-in method references for those with the same name as other `lodash` methods. */
932
+ var nativeGetSymbols = Object.getOwnPropertySymbols,
933
+ nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
934
+ nativeKeys = overArg(Object.keys, Object);
935
+
936
+ /* Built-in method references that are verified to be native. */
937
+ var DataView = getNative(root, 'DataView'),
938
+ Map = getNative(root, 'Map'),
939
+ Promise = getNative(root, 'Promise'),
940
+ Set = getNative(root, 'Set'),
941
+ WeakMap = getNative(root, 'WeakMap'),
942
+ nativeCreate = getNative(Object, 'create');
943
+
944
+ /** Used to detect maps, sets, and weakmaps. */
945
+ var dataViewCtorString = toSource(DataView),
946
+ mapCtorString = toSource(Map),
947
+ promiseCtorString = toSource(Promise),
948
+ setCtorString = toSource(Set),
949
+ weakMapCtorString = toSource(WeakMap);
950
+
951
+ /** Used to convert symbols to primitives and strings. */
952
+ var symbolProto = Symbol ? Symbol.prototype : undefined,
953
+ symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
954
+
955
+ /**
956
+ * Creates a hash object.
957
+ *
958
+ * @private
959
+ * @constructor
960
+ * @param {Array} [entries] The key-value pairs to cache.
961
+ */
962
+ function Hash(entries) {
963
+ var index = -1,
964
+ length = entries == null ? 0 : entries.length;
965
+
966
+ this.clear();
967
+ while (++index < length) {
968
+ var entry = entries[index];
969
+ this.set(entry[0], entry[1]);
970
+ }
971
+ }
972
+
973
+ /**
974
+ * Removes all key-value entries from the hash.
975
+ *
976
+ * @private
977
+ * @name clear
978
+ * @memberOf Hash
979
+ */
980
+ function hashClear() {
981
+ this.__data__ = nativeCreate ? nativeCreate(null) : {};
982
+ this.size = 0;
983
+ }
984
+
985
+ /**
986
+ * Removes `key` and its value from the hash.
987
+ *
988
+ * @private
989
+ * @name delete
990
+ * @memberOf Hash
991
+ * @param {Object} hash The hash to modify.
992
+ * @param {string} key The key of the value to remove.
993
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
994
+ */
995
+ function hashDelete(key) {
996
+ var result = this.has(key) && delete this.__data__[key];
997
+ this.size -= result ? 1 : 0;
998
+ return result;
999
+ }
1000
+
1001
+ /**
1002
+ * Gets the hash value for `key`.
1003
+ *
1004
+ * @private
1005
+ * @name get
1006
+ * @memberOf Hash
1007
+ * @param {string} key The key of the value to get.
1008
+ * @returns {*} Returns the entry value.
1009
+ */
1010
+ function hashGet(key) {
1011
+ var data = this.__data__;
1012
+ if (nativeCreate) {
1013
+ var result = data[key];
1014
+ return result === HASH_UNDEFINED ? undefined : result;
1015
+ }
1016
+ return hasOwnProperty.call(data, key) ? data[key] : undefined;
1017
+ }
1018
+
1019
+ /**
1020
+ * Checks if a hash value for `key` exists.
1021
+ *
1022
+ * @private
1023
+ * @name has
1024
+ * @memberOf Hash
1025
+ * @param {string} key The key of the entry to check.
1026
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1027
+ */
1028
+ function hashHas(key) {
1029
+ var data = this.__data__;
1030
+ return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
1031
+ }
1032
+
1033
+ /**
1034
+ * Sets the hash `key` to `value`.
1035
+ *
1036
+ * @private
1037
+ * @name set
1038
+ * @memberOf Hash
1039
+ * @param {string} key The key of the value to set.
1040
+ * @param {*} value The value to set.
1041
+ * @returns {Object} Returns the hash instance.
1042
+ */
1043
+ function hashSet(key, value) {
1044
+ var data = this.__data__;
1045
+ this.size += this.has(key) ? 0 : 1;
1046
+ data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
1047
+ return this;
1048
+ }
1049
+
1050
+ // Add methods to `Hash`.
1051
+ Hash.prototype.clear = hashClear;
1052
+ Hash.prototype['delete'] = hashDelete;
1053
+ Hash.prototype.get = hashGet;
1054
+ Hash.prototype.has = hashHas;
1055
+ Hash.prototype.set = hashSet;
1056
+
1057
+ /**
1058
+ * Creates an list cache object.
1059
+ *
1060
+ * @private
1061
+ * @constructor
1062
+ * @param {Array} [entries] The key-value pairs to cache.
1063
+ */
1064
+ function ListCache(entries) {
1065
+ var index = -1,
1066
+ length = entries == null ? 0 : entries.length;
1067
+
1068
+ this.clear();
1069
+ while (++index < length) {
1070
+ var entry = entries[index];
1071
+ this.set(entry[0], entry[1]);
1072
+ }
1073
+ }
1074
+
1075
+ /**
1076
+ * Removes all key-value entries from the list cache.
1077
+ *
1078
+ * @private
1079
+ * @name clear
1080
+ * @memberOf ListCache
1081
+ */
1082
+ function listCacheClear() {
1083
+ this.__data__ = [];
1084
+ this.size = 0;
1085
+ }
1086
+
1087
+ /**
1088
+ * Removes `key` and its value from the list cache.
1089
+ *
1090
+ * @private
1091
+ * @name delete
1092
+ * @memberOf ListCache
1093
+ * @param {string} key The key of the value to remove.
1094
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1095
+ */
1096
+ function listCacheDelete(key) {
1097
+ var data = this.__data__,
1098
+ index = assocIndexOf(data, key);
1099
+
1100
+ if (index < 0) {
1101
+ return false;
1102
+ }
1103
+ var lastIndex = data.length - 1;
1104
+ if (index == lastIndex) {
1105
+ data.pop();
1106
+ } else {
1107
+ splice.call(data, index, 1);
1108
+ }
1109
+ --this.size;
1110
+ return true;
1111
+ }
1112
+
1113
+ /**
1114
+ * Gets the list cache value for `key`.
1115
+ *
1116
+ * @private
1117
+ * @name get
1118
+ * @memberOf ListCache
1119
+ * @param {string} key The key of the value to get.
1120
+ * @returns {*} Returns the entry value.
1121
+ */
1122
+ function listCacheGet(key) {
1123
+ var data = this.__data__,
1124
+ index = assocIndexOf(data, key);
1125
+
1126
+ return index < 0 ? undefined : data[index][1];
1127
+ }
1128
+
1129
+ /**
1130
+ * Checks if a list cache value for `key` exists.
1131
+ *
1132
+ * @private
1133
+ * @name has
1134
+ * @memberOf ListCache
1135
+ * @param {string} key The key of the entry to check.
1136
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1137
+ */
1138
+ function listCacheHas(key) {
1139
+ return assocIndexOf(this.__data__, key) > -1;
1140
+ }
1141
+
1142
+ /**
1143
+ * Sets the list cache `key` to `value`.
1144
+ *
1145
+ * @private
1146
+ * @name set
1147
+ * @memberOf ListCache
1148
+ * @param {string} key The key of the value to set.
1149
+ * @param {*} value The value to set.
1150
+ * @returns {Object} Returns the list cache instance.
1151
+ */
1152
+ function listCacheSet(key, value) {
1153
+ var data = this.__data__,
1154
+ index = assocIndexOf(data, key);
1155
+
1156
+ if (index < 0) {
1157
+ ++this.size;
1158
+ data.push([key, value]);
1159
+ } else {
1160
+ data[index][1] = value;
1161
+ }
1162
+ return this;
1163
+ }
1164
+
1165
+ // Add methods to `ListCache`.
1166
+ ListCache.prototype.clear = listCacheClear;
1167
+ ListCache.prototype['delete'] = listCacheDelete;
1168
+ ListCache.prototype.get = listCacheGet;
1169
+ ListCache.prototype.has = listCacheHas;
1170
+ ListCache.prototype.set = listCacheSet;
1171
+
1172
+ /**
1173
+ * Creates a map cache object to store key-value pairs.
1174
+ *
1175
+ * @private
1176
+ * @constructor
1177
+ * @param {Array} [entries] The key-value pairs to cache.
1178
+ */
1179
+ function MapCache(entries) {
1180
+ var index = -1,
1181
+ length = entries == null ? 0 : entries.length;
1182
+
1183
+ this.clear();
1184
+ while (++index < length) {
1185
+ var entry = entries[index];
1186
+ this.set(entry[0], entry[1]);
1187
+ }
1188
+ }
1189
+
1190
+ /**
1191
+ * Removes all key-value entries from the map.
1192
+ *
1193
+ * @private
1194
+ * @name clear
1195
+ * @memberOf MapCache
1196
+ */
1197
+ function mapCacheClear() {
1198
+ this.size = 0;
1199
+ this.__data__ = {
1200
+ 'hash': new Hash,
1201
+ 'map': new (Map || ListCache),
1202
+ 'string': new Hash
1203
+ };
1204
+ }
1205
+
1206
+ /**
1207
+ * Removes `key` and its value from the map.
1208
+ *
1209
+ * @private
1210
+ * @name delete
1211
+ * @memberOf MapCache
1212
+ * @param {string} key The key of the value to remove.
1213
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1214
+ */
1215
+ function mapCacheDelete(key) {
1216
+ var result = getMapData(this, key)['delete'](key);
1217
+ this.size -= result ? 1 : 0;
1218
+ return result;
1219
+ }
1220
+
1221
+ /**
1222
+ * Gets the map value for `key`.
1223
+ *
1224
+ * @private
1225
+ * @name get
1226
+ * @memberOf MapCache
1227
+ * @param {string} key The key of the value to get.
1228
+ * @returns {*} Returns the entry value.
1229
+ */
1230
+ function mapCacheGet(key) {
1231
+ return getMapData(this, key).get(key);
1232
+ }
1233
+
1234
+ /**
1235
+ * Checks if a map value for `key` exists.
1236
+ *
1237
+ * @private
1238
+ * @name has
1239
+ * @memberOf MapCache
1240
+ * @param {string} key The key of the entry to check.
1241
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1242
+ */
1243
+ function mapCacheHas(key) {
1244
+ return getMapData(this, key).has(key);
1245
+ }
1246
+
1247
+ /**
1248
+ * Sets the map `key` to `value`.
1249
+ *
1250
+ * @private
1251
+ * @name set
1252
+ * @memberOf MapCache
1253
+ * @param {string} key The key of the value to set.
1254
+ * @param {*} value The value to set.
1255
+ * @returns {Object} Returns the map cache instance.
1256
+ */
1257
+ function mapCacheSet(key, value) {
1258
+ var data = getMapData(this, key),
1259
+ size = data.size;
1260
+
1261
+ data.set(key, value);
1262
+ this.size += data.size == size ? 0 : 1;
1263
+ return this;
1264
+ }
1265
+
1266
+ // Add methods to `MapCache`.
1267
+ MapCache.prototype.clear = mapCacheClear;
1268
+ MapCache.prototype['delete'] = mapCacheDelete;
1269
+ MapCache.prototype.get = mapCacheGet;
1270
+ MapCache.prototype.has = mapCacheHas;
1271
+ MapCache.prototype.set = mapCacheSet;
1272
+
1273
+ /**
1274
+ *
1275
+ * Creates an array cache object to store unique values.
1276
+ *
1277
+ * @private
1278
+ * @constructor
1279
+ * @param {Array} [values] The values to cache.
1280
+ */
1281
+ function SetCache(values) {
1282
+ var index = -1,
1283
+ length = values == null ? 0 : values.length;
1284
+
1285
+ this.__data__ = new MapCache;
1286
+ while (++index < length) {
1287
+ this.add(values[index]);
1288
+ }
1289
+ }
1290
+
1291
+ /**
1292
+ * Adds `value` to the array cache.
1293
+ *
1294
+ * @private
1295
+ * @name add
1296
+ * @memberOf SetCache
1297
+ * @alias push
1298
+ * @param {*} value The value to cache.
1299
+ * @returns {Object} Returns the cache instance.
1300
+ */
1301
+ function setCacheAdd(value) {
1302
+ this.__data__.set(value, HASH_UNDEFINED);
1303
+ return this;
1304
+ }
1305
+
1306
+ /**
1307
+ * Checks if `value` is in the array cache.
1308
+ *
1309
+ * @private
1310
+ * @name has
1311
+ * @memberOf SetCache
1312
+ * @param {*} value The value to search for.
1313
+ * @returns {number} Returns `true` if `value` is found, else `false`.
1314
+ */
1315
+ function setCacheHas(value) {
1316
+ return this.__data__.has(value);
1317
+ }
1318
+
1319
+ // Add methods to `SetCache`.
1320
+ SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
1321
+ SetCache.prototype.has = setCacheHas;
1322
+
1323
+ /**
1324
+ * Creates a stack cache object to store key-value pairs.
1325
+ *
1326
+ * @private
1327
+ * @constructor
1328
+ * @param {Array} [entries] The key-value pairs to cache.
1329
+ */
1330
+ function Stack(entries) {
1331
+ var data = this.__data__ = new ListCache(entries);
1332
+ this.size = data.size;
1333
+ }
1334
+
1335
+ /**
1336
+ * Removes all key-value entries from the stack.
1337
+ *
1338
+ * @private
1339
+ * @name clear
1340
+ * @memberOf Stack
1341
+ */
1342
+ function stackClear() {
1343
+ this.__data__ = new ListCache;
1344
+ this.size = 0;
1345
+ }
1346
+
1347
+ /**
1348
+ * Removes `key` and its value from the stack.
1349
+ *
1350
+ * @private
1351
+ * @name delete
1352
+ * @memberOf Stack
1353
+ * @param {string} key The key of the value to remove.
1354
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1355
+ */
1356
+ function stackDelete(key) {
1357
+ var data = this.__data__,
1358
+ result = data['delete'](key);
1359
+
1360
+ this.size = data.size;
1361
+ return result;
1362
+ }
1363
+
1364
+ /**
1365
+ * Gets the stack value for `key`.
1366
+ *
1367
+ * @private
1368
+ * @name get
1369
+ * @memberOf Stack
1370
+ * @param {string} key The key of the value to get.
1371
+ * @returns {*} Returns the entry value.
1372
+ */
1373
+ function stackGet(key) {
1374
+ return this.__data__.get(key);
1375
+ }
1376
+
1377
+ /**
1378
+ * Checks if a stack value for `key` exists.
1379
+ *
1380
+ * @private
1381
+ * @name has
1382
+ * @memberOf Stack
1383
+ * @param {string} key The key of the entry to check.
1384
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1385
+ */
1386
+ function stackHas(key) {
1387
+ return this.__data__.has(key);
1388
+ }
1389
+
1390
+ /**
1391
+ * Sets the stack `key` to `value`.
1392
+ *
1393
+ * @private
1394
+ * @name set
1395
+ * @memberOf Stack
1396
+ * @param {string} key The key of the value to set.
1397
+ * @param {*} value The value to set.
1398
+ * @returns {Object} Returns the stack cache instance.
1399
+ */
1400
+ function stackSet(key, value) {
1401
+ var data = this.__data__;
1402
+ if (data instanceof ListCache) {
1403
+ var pairs = data.__data__;
1404
+ if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
1405
+ pairs.push([key, value]);
1406
+ this.size = ++data.size;
1407
+ return this;
1408
+ }
1409
+ data = this.__data__ = new MapCache(pairs);
1410
+ }
1411
+ data.set(key, value);
1412
+ this.size = data.size;
1413
+ return this;
1414
+ }
1415
+
1416
+ // Add methods to `Stack`.
1417
+ Stack.prototype.clear = stackClear;
1418
+ Stack.prototype['delete'] = stackDelete;
1419
+ Stack.prototype.get = stackGet;
1420
+ Stack.prototype.has = stackHas;
1421
+ Stack.prototype.set = stackSet;
1422
+
1423
+ /**
1424
+ * Creates an array of the enumerable property names of the array-like `value`.
1425
+ *
1426
+ * @private
1427
+ * @param {*} value The value to query.
1428
+ * @param {boolean} inherited Specify returning inherited property names.
1429
+ * @returns {Array} Returns the array of property names.
1430
+ */
1431
+ function arrayLikeKeys(value, inherited) {
1432
+ var isArr = isArray(value),
1433
+ isArg = !isArr && isArguments(value),
1434
+ isBuff = !isArr && !isArg && isBuffer(value),
1435
+ isType = !isArr && !isArg && !isBuff && isTypedArray(value),
1436
+ skipIndexes = isArr || isArg || isBuff || isType,
1437
+ result = skipIndexes ? baseTimes(value.length, String) : [],
1438
+ length = result.length;
1439
+
1440
+ for (var key in value) {
1441
+ if ((hasOwnProperty.call(value, key)) &&
1442
+ !(skipIndexes && (
1443
+ // Safari 9 has enumerable `arguments.length` in strict mode.
1444
+ key == 'length' ||
1445
+ // Node.js 0.10 has enumerable non-index properties on buffers.
1446
+ (isBuff && (key == 'offset' || key == 'parent')) ||
1447
+ // PhantomJS 2 has enumerable non-index properties on typed arrays.
1448
+ (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
1449
+ // Skip index properties.
1450
+ isIndex(key, length)
1451
+ ))) {
1452
+ result.push(key);
1453
+ }
1454
+ }
1455
+ return result;
1456
+ }
1457
+
1458
+ /**
1459
+ * Gets the index at which the `key` is found in `array` of key-value pairs.
1460
+ *
1461
+ * @private
1462
+ * @param {Array} array The array to inspect.
1463
+ * @param {*} key The key to search for.
1464
+ * @returns {number} Returns the index of the matched value, else `-1`.
1465
+ */
1466
+ function assocIndexOf(array, key) {
1467
+ var length = array.length;
1468
+ while (length--) {
1469
+ if (eq(array[length][0], key)) {
1470
+ return length;
1471
+ }
1472
+ }
1473
+ return -1;
1474
+ }
1475
+
1476
+ /**
1477
+ * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
1478
+ * `keysFunc` and `symbolsFunc` to get the enumerable property names and
1479
+ * symbols of `object`.
1480
+ *
1481
+ * @private
1482
+ * @param {Object} object The object to query.
1483
+ * @param {Function} keysFunc The function to get the keys of `object`.
1484
+ * @param {Function} symbolsFunc The function to get the symbols of `object`.
1485
+ * @returns {Array} Returns the array of property names and symbols.
1486
+ */
1487
+ function baseGetAllKeys(object, keysFunc, symbolsFunc) {
1488
+ var result = keysFunc(object);
1489
+ return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
1490
+ }
1491
+
1492
+ /**
1493
+ * The base implementation of `getTag` without fallbacks for buggy environments.
1494
+ *
1495
+ * @private
1496
+ * @param {*} value The value to query.
1497
+ * @returns {string} Returns the `toStringTag`.
1498
+ */
1499
+ function baseGetTag(value) {
1500
+ if (value == null) {
1501
+ return value === undefined ? undefinedTag : nullTag;
1502
+ }
1503
+ return (symToStringTag && symToStringTag in Object(value))
1504
+ ? getRawTag(value)
1505
+ : objectToString(value);
1506
+ }
1507
+
1508
+ /**
1509
+ * The base implementation of `_.isArguments`.
1510
+ *
1511
+ * @private
1512
+ * @param {*} value The value to check.
1513
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
1514
+ */
1515
+ function baseIsArguments(value) {
1516
+ return isObjectLike(value) && baseGetTag(value) == argsTag;
1517
+ }
1518
+
1519
+ /**
1520
+ * The base implementation of `_.isEqual` which supports partial comparisons
1521
+ * and tracks traversed objects.
1522
+ *
1523
+ * @private
1524
+ * @param {*} value The value to compare.
1525
+ * @param {*} other The other value to compare.
1526
+ * @param {boolean} bitmask The bitmask flags.
1527
+ * 1 - Unordered comparison
1528
+ * 2 - Partial comparison
1529
+ * @param {Function} [customizer] The function to customize comparisons.
1530
+ * @param {Object} [stack] Tracks traversed `value` and `other` objects.
1531
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
1532
+ */
1533
+ function baseIsEqual(value, other, bitmask, customizer, stack) {
1534
+ if (value === other) {
1535
+ return true;
1536
+ }
1537
+ if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
1538
+ return value !== value && other !== other;
1539
+ }
1540
+ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
1541
+ }
1542
+
1543
+ /**
1544
+ * A specialized version of `baseIsEqual` for arrays and objects which performs
1545
+ * deep comparisons and tracks traversed objects enabling objects with circular
1546
+ * references to be compared.
1547
+ *
1548
+ * @private
1549
+ * @param {Object} object The object to compare.
1550
+ * @param {Object} other The other object to compare.
1551
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
1552
+ * @param {Function} customizer The function to customize comparisons.
1553
+ * @param {Function} equalFunc The function to determine equivalents of values.
1554
+ * @param {Object} [stack] Tracks traversed `object` and `other` objects.
1555
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
1556
+ */
1557
+ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
1558
+ var objIsArr = isArray(object),
1559
+ othIsArr = isArray(other),
1560
+ objTag = objIsArr ? arrayTag : getTag(object),
1561
+ othTag = othIsArr ? arrayTag : getTag(other);
1562
+
1563
+ objTag = objTag == argsTag ? objectTag : objTag;
1564
+ othTag = othTag == argsTag ? objectTag : othTag;
1565
+
1566
+ var objIsObj = objTag == objectTag,
1567
+ othIsObj = othTag == objectTag,
1568
+ isSameTag = objTag == othTag;
1569
+
1570
+ if (isSameTag && isBuffer(object)) {
1571
+ if (!isBuffer(other)) {
1572
+ return false;
1573
+ }
1574
+ objIsArr = true;
1575
+ objIsObj = false;
1576
+ }
1577
+ if (isSameTag && !objIsObj) {
1578
+ stack || (stack = new Stack);
1579
+ return (objIsArr || isTypedArray(object))
1580
+ ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
1581
+ : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
1582
+ }
1583
+ if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
1584
+ var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
1585
+ othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
1586
+
1587
+ if (objIsWrapped || othIsWrapped) {
1588
+ var objUnwrapped = objIsWrapped ? object.value() : object,
1589
+ othUnwrapped = othIsWrapped ? other.value() : other;
1590
+
1591
+ stack || (stack = new Stack);
1592
+ return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
1593
+ }
1594
+ }
1595
+ if (!isSameTag) {
1596
+ return false;
1597
+ }
1598
+ stack || (stack = new Stack);
1599
+ return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
1600
+ }
1601
+
1602
+ /**
1603
+ * The base implementation of `_.isNative` without bad shim checks.
1604
+ *
1605
+ * @private
1606
+ * @param {*} value The value to check.
1607
+ * @returns {boolean} Returns `true` if `value` is a native function,
1608
+ * else `false`.
1609
+ */
1610
+ function baseIsNative(value) {
1611
+ if (!isObject(value) || isMasked(value)) {
1612
+ return false;
1613
+ }
1614
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
1615
+ return pattern.test(toSource(value));
1616
+ }
1617
+
1618
+ /**
1619
+ * The base implementation of `_.isTypedArray` without Node.js optimizations.
1620
+ *
1621
+ * @private
1622
+ * @param {*} value The value to check.
1623
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
1624
+ */
1625
+ function baseIsTypedArray(value) {
1626
+ return isObjectLike(value) &&
1627
+ isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
1628
+ }
1629
+
1630
+ /**
1631
+ * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
1632
+ *
1633
+ * @private
1634
+ * @param {Object} object The object to query.
1635
+ * @returns {Array} Returns the array of property names.
1636
+ */
1637
+ function baseKeys(object) {
1638
+ if (!isPrototype(object)) {
1639
+ return nativeKeys(object);
1640
+ }
1641
+ var result = [];
1642
+ for (var key in Object(object)) {
1643
+ if (hasOwnProperty.call(object, key) && key != 'constructor') {
1644
+ result.push(key);
1645
+ }
1646
+ }
1647
+ return result;
1648
+ }
1649
+
1650
+ /**
1651
+ * A specialized version of `baseIsEqualDeep` for arrays with support for
1652
+ * partial deep comparisons.
1653
+ *
1654
+ * @private
1655
+ * @param {Array} array The array to compare.
1656
+ * @param {Array} other The other array to compare.
1657
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
1658
+ * @param {Function} customizer The function to customize comparisons.
1659
+ * @param {Function} equalFunc The function to determine equivalents of values.
1660
+ * @param {Object} stack Tracks traversed `array` and `other` objects.
1661
+ * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
1662
+ */
1663
+ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
1664
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
1665
+ arrLength = array.length,
1666
+ othLength = other.length;
1667
+
1668
+ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
1669
+ return false;
1670
+ }
1671
+ // Assume cyclic values are equal.
1672
+ var stacked = stack.get(array);
1673
+ if (stacked && stack.get(other)) {
1674
+ return stacked == other;
1675
+ }
1676
+ var index = -1,
1677
+ result = true,
1678
+ seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
1679
+
1680
+ stack.set(array, other);
1681
+ stack.set(other, array);
1682
+
1683
+ // Ignore non-index properties.
1684
+ while (++index < arrLength) {
1685
+ var arrValue = array[index],
1686
+ othValue = other[index];
1687
+
1688
+ if (customizer) {
1689
+ var compared = isPartial
1690
+ ? customizer(othValue, arrValue, index, other, array, stack)
1691
+ : customizer(arrValue, othValue, index, array, other, stack);
1692
+ }
1693
+ if (compared !== undefined) {
1694
+ if (compared) {
1695
+ continue;
1696
+ }
1697
+ result = false;
1698
+ break;
1699
+ }
1700
+ // Recursively compare arrays (susceptible to call stack limits).
1701
+ if (seen) {
1702
+ if (!arraySome(other, function(othValue, othIndex) {
1703
+ if (!cacheHas(seen, othIndex) &&
1704
+ (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
1705
+ return seen.push(othIndex);
1706
+ }
1707
+ })) {
1708
+ result = false;
1709
+ break;
1710
+ }
1711
+ } else if (!(
1712
+ arrValue === othValue ||
1713
+ equalFunc(arrValue, othValue, bitmask, customizer, stack)
1714
+ )) {
1715
+ result = false;
1716
+ break;
1717
+ }
1718
+ }
1719
+ stack['delete'](array);
1720
+ stack['delete'](other);
1721
+ return result;
1722
+ }
1723
+
1724
+ /**
1725
+ * A specialized version of `baseIsEqualDeep` for comparing objects of
1726
+ * the same `toStringTag`.
1727
+ *
1728
+ * **Note:** This function only supports comparing values with tags of
1729
+ * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
1730
+ *
1731
+ * @private
1732
+ * @param {Object} object The object to compare.
1733
+ * @param {Object} other The other object to compare.
1734
+ * @param {string} tag The `toStringTag` of the objects to compare.
1735
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
1736
+ * @param {Function} customizer The function to customize comparisons.
1737
+ * @param {Function} equalFunc The function to determine equivalents of values.
1738
+ * @param {Object} stack Tracks traversed `object` and `other` objects.
1739
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
1740
+ */
1741
+ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
1742
+ switch (tag) {
1743
+ case dataViewTag:
1744
+ if ((object.byteLength != other.byteLength) ||
1745
+ (object.byteOffset != other.byteOffset)) {
1746
+ return false;
1747
+ }
1748
+ object = object.buffer;
1749
+ other = other.buffer;
1750
+
1751
+ case arrayBufferTag:
1752
+ if ((object.byteLength != other.byteLength) ||
1753
+ !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
1754
+ return false;
1755
+ }
1756
+ return true;
1757
+
1758
+ case boolTag:
1759
+ case dateTag:
1760
+ case numberTag:
1761
+ // Coerce booleans to `1` or `0` and dates to milliseconds.
1762
+ // Invalid dates are coerced to `NaN`.
1763
+ return eq(+object, +other);
1764
+
1765
+ case errorTag:
1766
+ return object.name == other.name && object.message == other.message;
1767
+
1768
+ case regexpTag:
1769
+ case stringTag:
1770
+ // Coerce regexes to strings and treat strings, primitives and objects,
1771
+ // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
1772
+ // for more details.
1773
+ return object == (other + '');
1774
+
1775
+ case mapTag:
1776
+ var convert = mapToArray;
1777
+
1778
+ case setTag:
1779
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
1780
+ convert || (convert = setToArray);
1781
+
1782
+ if (object.size != other.size && !isPartial) {
1783
+ return false;
1784
+ }
1785
+ // Assume cyclic values are equal.
1786
+ var stacked = stack.get(object);
1787
+ if (stacked) {
1788
+ return stacked == other;
1789
+ }
1790
+ bitmask |= COMPARE_UNORDERED_FLAG;
1791
+
1792
+ // Recursively compare objects (susceptible to call stack limits).
1793
+ stack.set(object, other);
1794
+ var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
1795
+ stack['delete'](object);
1796
+ return result;
1797
+
1798
+ case symbolTag:
1799
+ if (symbolValueOf) {
1800
+ return symbolValueOf.call(object) == symbolValueOf.call(other);
1801
+ }
1802
+ }
1803
+ return false;
1804
+ }
1805
+
1806
+ /**
1807
+ * A specialized version of `baseIsEqualDeep` for objects with support for
1808
+ * partial deep comparisons.
1809
+ *
1810
+ * @private
1811
+ * @param {Object} object The object to compare.
1812
+ * @param {Object} other The other object to compare.
1813
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
1814
+ * @param {Function} customizer The function to customize comparisons.
1815
+ * @param {Function} equalFunc The function to determine equivalents of values.
1816
+ * @param {Object} stack Tracks traversed `object` and `other` objects.
1817
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
1818
+ */
1819
+ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
1820
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
1821
+ objProps = getAllKeys(object),
1822
+ objLength = objProps.length,
1823
+ othProps = getAllKeys(other),
1824
+ othLength = othProps.length;
1825
+
1826
+ if (objLength != othLength && !isPartial) {
1827
+ return false;
1828
+ }
1829
+ var index = objLength;
1830
+ while (index--) {
1831
+ var key = objProps[index];
1832
+ if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
1833
+ return false;
1834
+ }
1835
+ }
1836
+ // Assume cyclic values are equal.
1837
+ var stacked = stack.get(object);
1838
+ if (stacked && stack.get(other)) {
1839
+ return stacked == other;
1840
+ }
1841
+ var result = true;
1842
+ stack.set(object, other);
1843
+ stack.set(other, object);
1844
+
1845
+ var skipCtor = isPartial;
1846
+ while (++index < objLength) {
1847
+ key = objProps[index];
1848
+ var objValue = object[key],
1849
+ othValue = other[key];
1850
+
1851
+ if (customizer) {
1852
+ var compared = isPartial
1853
+ ? customizer(othValue, objValue, key, other, object, stack)
1854
+ : customizer(objValue, othValue, key, object, other, stack);
1855
+ }
1856
+ // Recursively compare objects (susceptible to call stack limits).
1857
+ if (!(compared === undefined
1858
+ ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
1859
+ : compared
1860
+ )) {
1861
+ result = false;
1862
+ break;
1863
+ }
1864
+ skipCtor || (skipCtor = key == 'constructor');
1865
+ }
1866
+ if (result && !skipCtor) {
1867
+ var objCtor = object.constructor,
1868
+ othCtor = other.constructor;
1869
+
1870
+ // Non `Object` object instances with different constructors are not equal.
1871
+ if (objCtor != othCtor &&
1872
+ ('constructor' in object && 'constructor' in other) &&
1873
+ !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
1874
+ typeof othCtor == 'function' && othCtor instanceof othCtor)) {
1875
+ result = false;
1876
+ }
1877
+ }
1878
+ stack['delete'](object);
1879
+ stack['delete'](other);
1880
+ return result;
1881
+ }
1882
+
1883
+ /**
1884
+ * Creates an array of own enumerable property names and symbols of `object`.
1885
+ *
1886
+ * @private
1887
+ * @param {Object} object The object to query.
1888
+ * @returns {Array} Returns the array of property names and symbols.
1889
+ */
1890
+ function getAllKeys(object) {
1891
+ return baseGetAllKeys(object, keys, getSymbols);
1892
+ }
1893
+
1894
+ /**
1895
+ * Gets the data for `map`.
1896
+ *
1897
+ * @private
1898
+ * @param {Object} map The map to query.
1899
+ * @param {string} key The reference key.
1900
+ * @returns {*} Returns the map data.
1901
+ */
1902
+ function getMapData(map, key) {
1903
+ var data = map.__data__;
1904
+ return isKeyable(key)
1905
+ ? data[typeof key == 'string' ? 'string' : 'hash']
1906
+ : data.map;
1907
+ }
1908
+
1909
+ /**
1910
+ * Gets the native function at `key` of `object`.
1911
+ *
1912
+ * @private
1913
+ * @param {Object} object The object to query.
1914
+ * @param {string} key The key of the method to get.
1915
+ * @returns {*} Returns the function if it's native, else `undefined`.
1916
+ */
1917
+ function getNative(object, key) {
1918
+ var value = getValue(object, key);
1919
+ return baseIsNative(value) ? value : undefined;
1920
+ }
1921
+
1922
+ /**
1923
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
1924
+ *
1925
+ * @private
1926
+ * @param {*} value The value to query.
1927
+ * @returns {string} Returns the raw `toStringTag`.
1928
+ */
1929
+ function getRawTag(value) {
1930
+ var isOwn = hasOwnProperty.call(value, symToStringTag),
1931
+ tag = value[symToStringTag];
1932
+
1933
+ try {
1934
+ value[symToStringTag] = undefined;
1935
+ var unmasked = true;
1936
+ } catch (e) {}
1937
+
1938
+ var result = nativeObjectToString.call(value);
1939
+ if (unmasked) {
1940
+ if (isOwn) {
1941
+ value[symToStringTag] = tag;
1942
+ } else {
1943
+ delete value[symToStringTag];
1944
+ }
1945
+ }
1946
+ return result;
1947
+ }
1948
+
1949
+ /**
1950
+ * Creates an array of the own enumerable symbols of `object`.
1951
+ *
1952
+ * @private
1953
+ * @param {Object} object The object to query.
1954
+ * @returns {Array} Returns the array of symbols.
1955
+ */
1956
+ var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
1957
+ if (object == null) {
1958
+ return [];
1959
+ }
1960
+ object = Object(object);
1961
+ return arrayFilter(nativeGetSymbols(object), function(symbol) {
1962
+ return propertyIsEnumerable.call(object, symbol);
1963
+ });
1964
+ };
1965
+
1966
+ /**
1967
+ * Gets the `toStringTag` of `value`.
1968
+ *
1969
+ * @private
1970
+ * @param {*} value The value to query.
1971
+ * @returns {string} Returns the `toStringTag`.
1972
+ */
1973
+ var getTag = baseGetTag;
1974
+
1975
+ // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
1976
+ if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
1977
+ (Map && getTag(new Map) != mapTag) ||
1978
+ (Promise && getTag(Promise.resolve()) != promiseTag) ||
1979
+ (Set && getTag(new Set) != setTag) ||
1980
+ (WeakMap && getTag(new WeakMap) != weakMapTag)) {
1981
+ getTag = function(value) {
1982
+ var result = baseGetTag(value),
1983
+ Ctor = result == objectTag ? value.constructor : undefined,
1984
+ ctorString = Ctor ? toSource(Ctor) : '';
1985
+
1986
+ if (ctorString) {
1987
+ switch (ctorString) {
1988
+ case dataViewCtorString: return dataViewTag;
1989
+ case mapCtorString: return mapTag;
1990
+ case promiseCtorString: return promiseTag;
1991
+ case setCtorString: return setTag;
1992
+ case weakMapCtorString: return weakMapTag;
1993
+ }
1994
+ }
1995
+ return result;
1996
+ };
1997
+ }
1998
+
1999
+ /**
2000
+ * Checks if `value` is a valid array-like index.
2001
+ *
2002
+ * @private
2003
+ * @param {*} value The value to check.
2004
+ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
2005
+ * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
2006
+ */
2007
+ function isIndex(value, length) {
2008
+ length = length == null ? MAX_SAFE_INTEGER : length;
2009
+ return !!length &&
2010
+ (typeof value == 'number' || reIsUint.test(value)) &&
2011
+ (value > -1 && value % 1 == 0 && value < length);
2012
+ }
2013
+
2014
+ /**
2015
+ * Checks if `value` is suitable for use as unique object key.
2016
+ *
2017
+ * @private
2018
+ * @param {*} value The value to check.
2019
+ * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
2020
+ */
2021
+ function isKeyable(value) {
2022
+ var type = typeof value;
2023
+ return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
2024
+ ? (value !== '__proto__')
2025
+ : (value === null);
2026
+ }
2027
+
2028
+ /**
2029
+ * Checks if `func` has its source masked.
2030
+ *
2031
+ * @private
2032
+ * @param {Function} func The function to check.
2033
+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.
2034
+ */
2035
+ function isMasked(func) {
2036
+ return !!maskSrcKey && (maskSrcKey in func);
2037
+ }
2038
+
2039
+ /**
2040
+ * Checks if `value` is likely a prototype object.
2041
+ *
2042
+ * @private
2043
+ * @param {*} value The value to check.
2044
+ * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
2045
+ */
2046
+ function isPrototype(value) {
2047
+ var Ctor = value && value.constructor,
2048
+ proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
2049
+
2050
+ return value === proto;
2051
+ }
2052
+
2053
+ /**
2054
+ * Converts `value` to a string using `Object.prototype.toString`.
2055
+ *
2056
+ * @private
2057
+ * @param {*} value The value to convert.
2058
+ * @returns {string} Returns the converted string.
2059
+ */
2060
+ function objectToString(value) {
2061
+ return nativeObjectToString.call(value);
2062
+ }
2063
+
2064
+ /**
2065
+ * Converts `func` to its source code.
2066
+ *
2067
+ * @private
2068
+ * @param {Function} func The function to convert.
2069
+ * @returns {string} Returns the source code.
2070
+ */
2071
+ function toSource(func) {
2072
+ if (func != null) {
2073
+ try {
2074
+ return funcToString.call(func);
2075
+ } catch (e) {}
2076
+ try {
2077
+ return (func + '');
2078
+ } catch (e) {}
2079
+ }
2080
+ return '';
2081
+ }
2082
+
2083
+ /**
2084
+ * Performs a
2085
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
2086
+ * comparison between two values to determine if they are equivalent.
2087
+ *
2088
+ * @static
2089
+ * @memberOf _
2090
+ * @since 4.0.0
2091
+ * @category Lang
2092
+ * @param {*} value The value to compare.
2093
+ * @param {*} other The other value to compare.
2094
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
2095
+ * @example
2096
+ *
2097
+ * var object = { 'a': 1 };
2098
+ * var other = { 'a': 1 };
2099
+ *
2100
+ * _.eq(object, object);
2101
+ * // => true
2102
+ *
2103
+ * _.eq(object, other);
2104
+ * // => false
2105
+ *
2106
+ * _.eq('a', 'a');
2107
+ * // => true
2108
+ *
2109
+ * _.eq('a', Object('a'));
2110
+ * // => false
2111
+ *
2112
+ * _.eq(NaN, NaN);
2113
+ * // => true
2114
+ */
2115
+ function eq(value, other) {
2116
+ return value === other || (value !== value && other !== other);
2117
+ }
2118
+
2119
+ /**
2120
+ * Checks if `value` is likely an `arguments` object.
2121
+ *
2122
+ * @static
2123
+ * @memberOf _
2124
+ * @since 0.1.0
2125
+ * @category Lang
2126
+ * @param {*} value The value to check.
2127
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
2128
+ * else `false`.
2129
+ * @example
2130
+ *
2131
+ * _.isArguments(function() { return arguments; }());
2132
+ * // => true
2133
+ *
2134
+ * _.isArguments([1, 2, 3]);
2135
+ * // => false
2136
+ */
2137
+ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
2138
+ return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
2139
+ !propertyIsEnumerable.call(value, 'callee');
2140
+ };
2141
+
2142
+ /**
2143
+ * Checks if `value` is classified as an `Array` object.
2144
+ *
2145
+ * @static
2146
+ * @memberOf _
2147
+ * @since 0.1.0
2148
+ * @category Lang
2149
+ * @param {*} value The value to check.
2150
+ * @returns {boolean} Returns `true` if `value` is an array, else `false`.
2151
+ * @example
2152
+ *
2153
+ * _.isArray([1, 2, 3]);
2154
+ * // => true
2155
+ *
2156
+ * _.isArray(document.body.children);
2157
+ * // => false
2158
+ *
2159
+ * _.isArray('abc');
2160
+ * // => false
2161
+ *
2162
+ * _.isArray(_.noop);
2163
+ * // => false
2164
+ */
2165
+ var isArray = Array.isArray;
2166
+
2167
+ /**
2168
+ * Checks if `value` is array-like. A value is considered array-like if it's
2169
+ * not a function and has a `value.length` that's an integer greater than or
2170
+ * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
2171
+ *
2172
+ * @static
2173
+ * @memberOf _
2174
+ * @since 4.0.0
2175
+ * @category Lang
2176
+ * @param {*} value The value to check.
2177
+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
2178
+ * @example
2179
+ *
2180
+ * _.isArrayLike([1, 2, 3]);
2181
+ * // => true
2182
+ *
2183
+ * _.isArrayLike(document.body.children);
2184
+ * // => true
2185
+ *
2186
+ * _.isArrayLike('abc');
2187
+ * // => true
2188
+ *
2189
+ * _.isArrayLike(_.noop);
2190
+ * // => false
2191
+ */
2192
+ function isArrayLike(value) {
2193
+ return value != null && isLength(value.length) && !isFunction(value);
2194
+ }
2195
+
2196
+ /**
2197
+ * Checks if `value` is a buffer.
2198
+ *
2199
+ * @static
2200
+ * @memberOf _
2201
+ * @since 4.3.0
2202
+ * @category Lang
2203
+ * @param {*} value The value to check.
2204
+ * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
2205
+ * @example
2206
+ *
2207
+ * _.isBuffer(new Buffer(2));
2208
+ * // => true
2209
+ *
2210
+ * _.isBuffer(new Uint8Array(2));
2211
+ * // => false
2212
+ */
2213
+ var isBuffer = nativeIsBuffer || stubFalse;
2214
+
2215
+ /**
2216
+ * Performs a deep comparison between two values to determine if they are
2217
+ * equivalent.
2218
+ *
2219
+ * **Note:** This method supports comparing arrays, array buffers, booleans,
2220
+ * date objects, error objects, maps, numbers, `Object` objects, regexes,
2221
+ * sets, strings, symbols, and typed arrays. `Object` objects are compared
2222
+ * by their own, not inherited, enumerable properties. Functions and DOM
2223
+ * nodes are compared by strict equality, i.e. `===`.
2224
+ *
2225
+ * @static
2226
+ * @memberOf _
2227
+ * @since 0.1.0
2228
+ * @category Lang
2229
+ * @param {*} value The value to compare.
2230
+ * @param {*} other The other value to compare.
2231
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
2232
+ * @example
2233
+ *
2234
+ * var object = { 'a': 1 };
2235
+ * var other = { 'a': 1 };
2236
+ *
2237
+ * _.isEqual(object, other);
2238
+ * // => true
2239
+ *
2240
+ * object === other;
2241
+ * // => false
2242
+ */
2243
+ function isEqual(value, other) {
2244
+ return baseIsEqual(value, other);
2245
+ }
2246
+
2247
+ /**
2248
+ * Checks if `value` is classified as a `Function` object.
2249
+ *
2250
+ * @static
2251
+ * @memberOf _
2252
+ * @since 0.1.0
2253
+ * @category Lang
2254
+ * @param {*} value The value to check.
2255
+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.
2256
+ * @example
2257
+ *
2258
+ * _.isFunction(_);
2259
+ * // => true
2260
+ *
2261
+ * _.isFunction(/abc/);
2262
+ * // => false
2263
+ */
2264
+ function isFunction(value) {
2265
+ if (!isObject(value)) {
2266
+ return false;
2267
+ }
2268
+ // The use of `Object#toString` avoids issues with the `typeof` operator
2269
+ // in Safari 9 which returns 'object' for typed arrays and other constructors.
2270
+ var tag = baseGetTag(value);
2271
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
2272
+ }
2273
+
2274
+ /**
2275
+ * Checks if `value` is a valid array-like length.
2276
+ *
2277
+ * **Note:** This method is loosely based on
2278
+ * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
2279
+ *
2280
+ * @static
2281
+ * @memberOf _
2282
+ * @since 4.0.0
2283
+ * @category Lang
2284
+ * @param {*} value The value to check.
2285
+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
2286
+ * @example
2287
+ *
2288
+ * _.isLength(3);
2289
+ * // => true
2290
+ *
2291
+ * _.isLength(Number.MIN_VALUE);
2292
+ * // => false
2293
+ *
2294
+ * _.isLength(Infinity);
2295
+ * // => false
2296
+ *
2297
+ * _.isLength('3');
2298
+ * // => false
2299
+ */
2300
+ function isLength(value) {
2301
+ return typeof value == 'number' &&
2302
+ value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
2303
+ }
2304
+
2305
+ /**
2306
+ * Checks if `value` is the
2307
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
2308
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
2309
+ *
2310
+ * @static
2311
+ * @memberOf _
2312
+ * @since 0.1.0
2313
+ * @category Lang
2314
+ * @param {*} value The value to check.
2315
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
2316
+ * @example
2317
+ *
2318
+ * _.isObject({});
2319
+ * // => true
2320
+ *
2321
+ * _.isObject([1, 2, 3]);
2322
+ * // => true
2323
+ *
2324
+ * _.isObject(_.noop);
2325
+ * // => true
2326
+ *
2327
+ * _.isObject(null);
2328
+ * // => false
2329
+ */
2330
+ function isObject(value) {
2331
+ var type = typeof value;
2332
+ return value != null && (type == 'object' || type == 'function');
2333
+ }
2334
+
2335
+ /**
2336
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
2337
+ * and has a `typeof` result of "object".
2338
+ *
2339
+ * @static
2340
+ * @memberOf _
2341
+ * @since 4.0.0
2342
+ * @category Lang
2343
+ * @param {*} value The value to check.
2344
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
2345
+ * @example
2346
+ *
2347
+ * _.isObjectLike({});
2348
+ * // => true
2349
+ *
2350
+ * _.isObjectLike([1, 2, 3]);
2351
+ * // => true
2352
+ *
2353
+ * _.isObjectLike(_.noop);
2354
+ * // => false
2355
+ *
2356
+ * _.isObjectLike(null);
2357
+ * // => false
2358
+ */
2359
+ function isObjectLike(value) {
2360
+ return value != null && typeof value == 'object';
2361
+ }
2362
+
2363
+ /**
2364
+ * Checks if `value` is classified as a typed array.
2365
+ *
2366
+ * @static
2367
+ * @memberOf _
2368
+ * @since 3.0.0
2369
+ * @category Lang
2370
+ * @param {*} value The value to check.
2371
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
2372
+ * @example
2373
+ *
2374
+ * _.isTypedArray(new Uint8Array);
2375
+ * // => true
2376
+ *
2377
+ * _.isTypedArray([]);
2378
+ * // => false
2379
+ */
2380
+ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
2381
+
2382
+ /**
2383
+ * Creates an array of the own enumerable property names of `object`.
2384
+ *
2385
+ * **Note:** Non-object values are coerced to objects. See the
2386
+ * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
2387
+ * for more details.
2388
+ *
2389
+ * @static
2390
+ * @since 0.1.0
2391
+ * @memberOf _
2392
+ * @category Object
2393
+ * @param {Object} object The object to query.
2394
+ * @returns {Array} Returns the array of property names.
2395
+ * @example
2396
+ *
2397
+ * function Foo() {
2398
+ * this.a = 1;
2399
+ * this.b = 2;
2400
+ * }
2401
+ *
2402
+ * Foo.prototype.c = 3;
2403
+ *
2404
+ * _.keys(new Foo);
2405
+ * // => ['a', 'b'] (iteration order is not guaranteed)
2406
+ *
2407
+ * _.keys('hi');
2408
+ * // => ['0', '1']
2409
+ */
2410
+ function keys(object) {
2411
+ return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
2412
+ }
2413
+
2414
+ /**
2415
+ * This method returns a new empty array.
2416
+ *
2417
+ * @static
2418
+ * @memberOf _
2419
+ * @since 4.13.0
2420
+ * @category Util
2421
+ * @returns {Array} Returns the new empty array.
2422
+ * @example
2423
+ *
2424
+ * var arrays = _.times(2, _.stubArray);
2425
+ *
2426
+ * console.log(arrays);
2427
+ * // => [[], []]
2428
+ *
2429
+ * console.log(arrays[0] === arrays[1]);
2430
+ * // => false
2431
+ */
2432
+ function stubArray() {
2433
+ return [];
2434
+ }
2435
+
2436
+ /**
2437
+ * This method returns `false`.
2438
+ *
2439
+ * @static
2440
+ * @memberOf _
2441
+ * @since 4.13.0
2442
+ * @category Util
2443
+ * @returns {boolean} Returns `false`.
2444
+ * @example
2445
+ *
2446
+ * _.times(2, _.stubFalse);
2447
+ * // => [false, false]
2448
+ */
2449
+ function stubFalse() {
2450
+ return false;
2451
+ }
2452
+
2453
+ module.exports = isEqual;
2454
+ } (lodash_isequal, lodash_isequal.exports));
2455
+
2456
+ var lodash_isequalExports = lodash_isequal.exports;
2457
+ var isEqual = /*@__PURE__*/getDefaultExportFromCjs(lodash_isequalExports);
2458
+
2459
+ ////////////////////////////////////////////////////////////////////////////
2460
+ //
2461
+ // Copyright 2021 Realm Inc.
2462
+ //
2463
+ // Licensed under the Apache License, Version 2.0 (the "License");
2464
+ // you may not use this file except in compliance with the License.
2465
+ // You may obtain a copy of the License at
2466
+ //
2467
+ // http://www.apache.org/licenses/LICENSE-2.0
2468
+ //
2469
+ // Unless required by applicable law or agreed to in writing, software
2470
+ // distributed under the License is distributed on an "AS IS" BASIS,
2471
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2472
+ // See the License for the specific language governing permissions and
2473
+ // limitations under the License.
2474
+ //
2475
+ ////////////////////////////////////////////////////////////////////////////
2476
+ function createRealmProviderFromRealm(realm, RealmContext) {
2477
+ return ({ children }) => {
2478
+ return React.createElement(RealmContext.Provider, { value: realm, children: children });
2479
+ };
2480
+ }
2481
+ /**
2482
+ * Generates a `RealmProvider` given a {@link Realm.Configuration} and {@link React.Context}.
2483
+ * @param realmConfig - The configuration of the Realm to be instantiated
2484
+ * @param RealmContext - The context that will contain the Realm instance
2485
+ * @returns a RealmProvider component that provides context to all context hooks
2486
+ */
2487
+ function createRealmProviderFromConfig(realmConfig, RealmContext) {
2488
+ return ({ children, fallback: Fallback, closeOnUnmount = true, realmRef, ...restProps }) => {
2489
+ const [realm, setRealm] = React.useState(() => realmConfig.sync === undefined && restProps.sync === undefined
2490
+ ? new Realm(mergeRealmConfiguration(realmConfig, restProps))
2491
+ : null);
2492
+ // We increment `configVersion` when a config override passed as a prop
2493
+ // changes, which triggers a `useEffect` to re-open the Realm with the
2494
+ // new config
2495
+ const [configVersion, setConfigVersion] = React.useState(0);
2496
+ // We put realm in a ref to avoid have an endless loop of updates when the realm is updated
2497
+ const currentRealm = React.useRef(realm);
2498
+ // This will merge the configuration provided by createRealmContext and any configuration properties
2499
+ // set directly on the RealmProvider component. Any settings on the component will override the original configuration.
2500
+ const configuration = React.useRef(mergeRealmConfiguration(realmConfig, restProps));
2501
+ // Merge and set the configuration again and increment the version if any
2502
+ // of the RealmProvider properties change.
2503
+ React.useEffect(() => {
2504
+ const combinedConfig = mergeRealmConfiguration(realmConfig, restProps);
2505
+ if (!areConfigurationsIdentical(configuration.current, combinedConfig)) {
2506
+ configuration.current = combinedConfig;
2507
+ // Only rerender if realm has already been configured
2508
+ if (currentRealm.current != null) {
2509
+ setConfigVersion((x) => x + 1);
2510
+ }
2511
+ }
2512
+ }, [restProps]);
2513
+ React.useEffect(() => {
2514
+ currentRealm.current = realm;
2515
+ if (realmRef) {
2516
+ realmRef.current = realm;
2517
+ }
2518
+ }, [realm]);
2519
+ React.useEffect(() => {
2520
+ const realmRef = currentRealm.current;
2521
+ // Check if we currently have an open Realm. If we do not (i.e. it is the first
2522
+ // render, or the Realm has been closed due to a config change), then we
2523
+ // need to open a new Realm.
2524
+ const shouldInitRealm = realmRef === null;
2525
+ const initRealm = async () => {
2526
+ const openRealm = await Realm.open(configuration.current);
2527
+ setRealm(openRealm);
2528
+ };
2529
+ if (shouldInitRealm) {
2530
+ initRealm().catch(console.error);
2531
+ }
2532
+ return () => {
2533
+ if (realm) {
2534
+ if (closeOnUnmount) {
2535
+ realm.close();
2536
+ }
2537
+ setRealm(null);
2538
+ }
2539
+ };
2540
+ }, [configVersion, realm, setRealm, closeOnUnmount]);
2541
+ if (!realm) {
2542
+ if (typeof Fallback === "function") {
2543
+ return React.createElement(Fallback, null);
2544
+ }
2545
+ return React.createElement(React.Fragment, null, Fallback);
2546
+ }
2547
+ return React.createElement(RealmContext.Provider, { value: realm, children: children });
2548
+ };
2549
+ }
2550
+ /**
2551
+ * Generates a `RealmProvider` which is either based on a configuration
2552
+ * or based on a realm, depending on its props.
2553
+ * @param RealmContext - The context that will contain the Realm instance
2554
+ * @returns a RealmProvider component that provides context to all context hooks
2555
+ */
2556
+ function createDynamicRealmProvider(RealmContext) {
2557
+ const RealmProviderFromConfig = createRealmProviderFromConfig({}, RealmContext);
2558
+ return ({ realm, children, ...config }) => {
2559
+ if (realm) {
2560
+ if (Object.keys(config).length > 0) {
2561
+ throw new Error("Cannot use configuration props when using an existing Realm instance.");
2562
+ }
2563
+ return React.createElement(RealmContext.Provider, { value: realm, children: children });
2564
+ }
2565
+ else {
2566
+ return React.createElement(RealmProviderFromConfig, { ...config, children: children });
2567
+ }
2568
+ };
2569
+ }
2570
+ /**
2571
+ * Generates the appropriate `RealmProvider` based on whether there is a config, realm, or neither given.
2572
+ * @param realmOrConfig - A Realm instance, a configuration, or undefined (including default provider).
2573
+ * @param RealmContext - The context that will contain the Realm instance
2574
+ * @returns a RealmProvider component that provides context to all context hooks
2575
+ */
2576
+ function createRealmProvider(realmOrConfig, RealmContext) {
2577
+ if (!realmOrConfig) {
2578
+ return createDynamicRealmProvider(RealmContext);
2579
+ }
2580
+ else if (realmOrConfig instanceof Realm) {
2581
+ return createRealmProviderFromRealm(realmOrConfig, RealmContext);
2582
+ }
2583
+ else {
2584
+ return createRealmProviderFromConfig(realmOrConfig, RealmContext);
2585
+ }
2586
+ }
2587
+ /**
2588
+ * Merge two configurations, creating a configuration using `configA` as the default,
2589
+ * merged with `configB`, with properties in `configB` overriding `configA`.
2590
+ * @param configA - The default config object
2591
+ * @param configB - Config overrides object
2592
+ * @returns Merged config object
2593
+ */
2594
+ function mergeRealmConfiguration(configA, configB) {
2595
+ return {
2596
+ ...configA,
2597
+ ...configB,
2598
+ };
2599
+ }
2600
+ /**
2601
+ * Utility function that does a deep comparison (key: value) of object a with object b
2602
+ * @param a - Object to compare
2603
+ * @param b - Object to compare
2604
+ * @returns True if the objects are identical
2605
+ */
2606
+ function areConfigurationsIdentical(a, b) {
2607
+ return isEqual(a, b);
2608
+ }
2609
+
2610
+ ////////////////////////////////////////////////////////////////////////////
2611
+ //
2612
+ // Copyright 2024 Realm Inc.
2613
+ //
2614
+ // Licensed under the Apache License, Version 2.0 (the "License");
2615
+ // you may not use this file except in compliance with the License.
2616
+ // You may obtain a copy of the License at
2617
+ //
2618
+ // http://www.apache.org/licenses/LICENSE-2.0
2619
+ //
2620
+ // Unless required by applicable law or agreed to in writing, software
2621
+ // distributed under the License is distributed on an "AS IS" BASIS,
2622
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2623
+ // See the License for the specific language governing permissions and
2624
+ // limitations under the License.
2625
+ //
2626
+ ////////////////////////////////////////////////////////////////////////////
2627
+ function createRealmContext(realmOrConfig) {
2628
+ const RealmContext = React.createContext(realmOrConfig instanceof Realm ? realmOrConfig : null);
2629
+ const RealmProvider = createRealmProvider(realmOrConfig, RealmContext);
2630
+ const useRealm = createUseRealm(RealmContext);
2631
+ const useQuery = createUseQuery(useRealm);
2632
+ const useObject = createUseObject(useRealm);
2633
+ return {
2634
+ RealmProvider,
2635
+ useRealm,
2636
+ useQuery,
2637
+ useObject,
2638
+ };
2639
+ }
2640
+
2641
+ ////////////////////////////////////////////////////////////////////////////
2642
+ //
2643
+ // Copyright 2023 Realm Inc.
2644
+ //
2645
+ // Licensed under the Apache License, Version 2.0 (the "License");
2646
+ // you may not use this file except in compliance with the License.
2647
+ // You may obtain a copy of the License at
2648
+ //
2649
+ // http://www.apache.org/licenses/LICENSE-2.0
2650
+ //
2651
+ // Unless required by applicable law or agreed to in writing, software
2652
+ // distributed under the License is distributed on an "AS IS" BASIS,
2653
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2654
+ // See the License for the specific language governing permissions and
2655
+ // limitations under the License.
2656
+ //
2657
+ ////////////////////////////////////////////////////////////////////////////
2658
+ exports.AuthOperationName = void 0;
2659
+ (function (AuthOperationName) {
2660
+ AuthOperationName["LogIn"] = "logIn";
2661
+ AuthOperationName["LogInWithAnonymous"] = "logInWithAnonymous";
2662
+ AuthOperationName["LogInWithApiKey"] = "logInWithApiKey";
2663
+ AuthOperationName["LogInWithEmailPassword"] = "logInWithEmailPassword";
2664
+ AuthOperationName["LogInWithJWT"] = "logInWithJWT";
2665
+ AuthOperationName["LogInWithGoogle"] = "logInWithGoogle";
2666
+ AuthOperationName["LogInWithApple"] = "logInWithApple";
2667
+ AuthOperationName["LogInWithFacebook"] = "logInWithFacebook";
2668
+ AuthOperationName["LogInWithFunction"] = "logInWithFunction";
2669
+ AuthOperationName["LogOut"] = "logOut";
2670
+ AuthOperationName["Register"] = "register";
2671
+ AuthOperationName["Confirm"] = "confirm";
2672
+ AuthOperationName["ResendConfirmationEmail"] = "resendConfirmationEmail";
2673
+ AuthOperationName["RetryCustomConfirmation"] = "retryCustomConfirmation";
2674
+ AuthOperationName["SendResetPasswordEmail"] = "sendResetPasswordEmail";
2675
+ AuthOperationName["ResetPassword"] = "resetPassword";
2676
+ AuthOperationName["CallResetPasswordFunction"] = "callResetPasswordFunction";
2677
+ })(exports.AuthOperationName || (exports.AuthOperationName = {}));
2678
+ /**
2679
+ * The `AuthError` is set based on the operation name and the error message.
2680
+ */
2681
+ class AuthError extends Error {
2682
+ constructor(operation, message) {
2683
+ super(message);
2684
+ this.name = "AuthError";
2685
+ this.operation = operation;
2686
+ }
2687
+ }
2688
+ /**
2689
+ * The possible states an {@link OperationResult} can be in.
2690
+ */
2691
+ exports.OperationState = void 0;
2692
+ (function (OperationState) {
2693
+ OperationState["NotStarted"] = "not-started";
2694
+ OperationState["Pending"] = "pending";
2695
+ OperationState["Success"] = "success";
2696
+ OperationState["Error"] = "error";
2697
+ })(exports.OperationState || (exports.OperationState = {}));
2698
+
2699
+ ////////////////////////////////////////////////////////////////////////////
2700
+ //
2701
+ // Copyright 2021 Realm Inc.
2702
+ //
2703
+ // Licensed under the Apache License, Version 2.0 (the "License");
2704
+ // you may not use this file except in compliance with the License.
2705
+ // You may obtain a copy of the License at
2706
+ //
2707
+ // http://www.apache.org/licenses/LICENSE-2.0
2708
+ //
2709
+ // Unless required by applicable law or agreed to in writing, software
2710
+ // distributed under the License is distributed on an "AS IS" BASIS,
2711
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2712
+ // See the License for the specific language governing permissions and
2713
+ // limitations under the License.
2714
+ //
2715
+ ////////////////////////////////////////////////////////////////////////////
2716
+ const defaultContext = createRealmContext();
2717
+ /**
2718
+ * The Provider component that is required to wrap any component using
2719
+ * the Realm hooks.
2720
+ * @example
2721
+ * ```
2722
+ * const AppRoot = () => {
2723
+ * const syncConfig = {
2724
+ * flexible: true,
2725
+ * user: currentUser
2726
+ * };
2727
+ *
2728
+ * return (
2729
+ * <RealmProvider schema={[Task, User]} path={"data.realm"} sync={syncConfig}>
2730
+ * <App/>
2731
+ * </RealmProvider>
2732
+ * )
2733
+ * }
2734
+ * ```
2735
+ * @example
2736
+ * const syncConfig = {
2737
+ * flexible: true,
2738
+ * user: currentUser
2739
+ * };
2740
+ * const realm = new Realm(schema:[Task, User], path:"data.realm", sync: syncConfig);
2741
+ * ...
2742
+ * const AppRoot = () => {
2743
+ * return (
2744
+ * <RealmProvider>
2745
+ * <App/>
2746
+ * </RealmProvider>
2747
+ * )
2748
+ * }
2749
+ * @param props - The {@link Realm.Configuration} or {@link Realm} for this Provider, passed as props.
2750
+ */
2751
+ const RealmProvider = defaultContext.RealmProvider;
2752
+ /**
2753
+ * Returns the instance of the {@link Realm} opened by the `RealmProvider`.
2754
+ * @example
2755
+ * ```
2756
+ * const realm = useRealm();
2757
+ * ```
2758
+ * @returns a realm instance
2759
+ */
2760
+ const useRealm = defaultContext.useRealm;
2761
+ /**
2762
+ * Returns a {@link Realm.Collection} of {@link Realm.Object}s from a given type.
2763
+ * The hook will update on any changes to any object in the collection.
2764
+ *
2765
+ * The result of this can be consumed directly by the `data` argument of any React Native
2766
+ * VirtualizedList or FlatList. If the component used for the list's `renderItem` prop is {@link React.Memo}ized,
2767
+ * then only the modified object will re-render.
2768
+ * @example
2769
+ * ```tsx
2770
+ * // Return all collection items
2771
+ * const collection = useQuery({ type: Object });
2772
+ *
2773
+ * // Return all collection items sorted by name and filtered by category
2774
+ * const filteredAndSorted = useQuery({
2775
+ * type: Object,
2776
+ * query: (collection) => collection.filtered('category == $0',category).sorted('name'),
2777
+ * }, [category]);
2778
+ *
2779
+ * // Return all collection items sorted by name and filtered by category, triggering re-renders only if "name" changes
2780
+ * const filteredAndSorted = useQuery({
2781
+ * type: Object,
2782
+ * query: (collection) => collection.filtered('category == $0',category).sorted('name'),
2783
+ * keyPaths: ["name"]
2784
+ * }, [category]);
2785
+ * ```
2786
+ * @param options
2787
+ * @param options.type - The object type, depicted by a string or a class extending Realm.Object
2788
+ * @param options.query - A function that takes a {@link Realm.Collection} and returns a {@link Realm.Collection} of the same type. This allows for filtering and sorting of the collection, before it is returned.
2789
+ * @param options.keyPaths - Indicates a lower bound on the changes relevant for the hook. This is a lower bound, since if multiple hooks add listeners (each with their own `keyPaths`) the union of these key-paths will determine the changes that are considered relevant for all listeners registered on the collection. In other words: A listener might fire and cause a re-render more than the key-paths specify, if other listeners with different key-paths are present.
2790
+ * @param deps - An array of dependencies that will be passed to {@link React.useMemo}
2791
+ * @returns a collection of realm objects or an empty array
2792
+ */
2793
+ const useQuery = defaultContext.useQuery;
2794
+ /**
2795
+ * Returns a {@link Realm.Object} from a given type and value of primary key.
2796
+ * The hook will update on any changes to the properties on the returned object
2797
+ * and return null if it either doesn't exists or has been deleted.
2798
+ * @example
2799
+ * ```
2800
+ * const object = useObject(ObjectClass, objectId);
2801
+ * ```
2802
+ * @param type - The object type, depicted by a string or a class extending {@link Realm.Object}
2803
+ * @param primaryKey - The primary key of the desired object which will be retrieved using {@link Realm.objectForPrimaryKey}
2804
+ * @param keyPaths - Indicates a lower bound on the changes relevant for the hook. This is a lower bound, since if multiple hooks add listeners (each with their own `keyPaths`) the union of these key-paths will determine the changes that are considered relevant for all listeners registered on the object. In other words: A listener might fire and cause a re-render more than the key-paths specify, if other listeners with different key-paths are present.
2805
+ * @returns either the desired {@link Realm.Object} or `null` in the case of it being deleted or not existing.
2806
+ */
2807
+ const useObject = defaultContext.useObject;
2808
+
2809
+ exports.Realm = Realm;
2810
+ exports.AuthError = AuthError;
2811
+ exports.RealmProvider = RealmProvider;
2812
+ exports.createRealmContext = createRealmContext;
2813
+ exports.createUseObject = createUseObject;
2814
+ exports.createUseQuery = createUseQuery;
2815
+ exports.useObject = useObject;
2816
+ exports.useQuery = useQuery;
2817
+ exports.useRealm = useRealm;
2818
+ //# sourceMappingURL=index.cjs.map