@pomwik/afterdb-react 0.0.0-stage → 0.20.1

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