react-native-mosquito-transport 0.0.18 → 0.0.21

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 (30) hide show
  1. package/.jshintignore +4 -0
  2. package/.jshintrc +16 -0
  3. package/README.md +75 -1
  4. package/TODO +10 -1
  5. package/example/ios/MosquitodbExample.xcodeproj/project.pbxproj +6 -5
  6. package/example/ios/MosquitodbExample.xcworkspace/contents.xcworkspacedata +10 -0
  7. package/example/ios/MosquitodbExample.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +8 -0
  8. package/example/ios/MosquitodbExample.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +8 -0
  9. package/example/ios/MosquitodbExample.xcworkspace/xcuserdata/anthony.xcuserdatad/UserInterfaceState.xcuserstate +0 -0
  10. package/example/ios/MosquitodbExample.xcworkspace/xcuserdata/anthony.xcuserdatad/WorkspaceSettings.xcsettings +14 -0
  11. package/ios/Mosquitodb.swift +14 -1
  12. package/package.json +15 -14
  13. package/src/helpers/engine_api.js +39 -0
  14. package/src/helpers/peripherals.js +73 -127
  15. package/src/helpers/utils.js +48 -19
  16. package/src/helpers/values.js +8 -47
  17. package/src/helpers/variables.js +14 -6
  18. package/src/index.d.ts +103 -43
  19. package/src/index.js +198 -121
  20. package/src/products/auth/accessor.js +97 -36
  21. package/src/products/auth/index.js +151 -82
  22. package/src/products/database/accessor.js +720 -223
  23. package/src/products/database/bson.js +16 -0
  24. package/src/products/database/counter.js +16 -0
  25. package/src/products/database/index.js +303 -190
  26. package/src/products/database/types.js +1 -1
  27. package/src/products/database/validator.js +517 -254
  28. package/src/products/http_callable/index.js +111 -106
  29. package/src/products/storage/index.js +97 -88
  30. package/src/helpers/EngineApi.js +0 -33
@@ -3,14 +3,28 @@ import { ServerReachableListener, StoreReadyListener } from "./listeners";
3
3
  import { CACHE_PROTOCOL, CACHE_STORAGE_PATH, DEFAULT_CACHE_PASSWORD, LOCAL_STORAGE_PATH } from "./values";
4
4
  import { CacheStore, Scoped } from "./variables";
5
5
  import { decryptString, encryptString, niceTry, serializeE2E } from "./peripherals";
6
+ import { deserializeBSON, serializeToBase64 } from "../products/database/bson";
7
+ import { trySendPendingWrite } from "../products/database";
8
+ import { deserialize } from "entity-serializer";
6
9
 
7
- export const updateCacheStore = () => {
8
- const { cachePassword = DEFAULT_CACHE_PASSWORD, cacheProtocol = CACHE_PROTOCOL.ASYNC_STORAGE, io } = Scoped.ReleaseCacheData;
10
+ export const updateCacheStore = (timer = 300) => {
11
+ const { cachePassword = DEFAULT_CACHE_PASSWORD, cacheProtocol = CACHE_PROTOCOL.ASYNC_STORAGE, io, promoteCache } = Scoped.ReleaseCacheData;
9
12
 
10
13
  clearTimeout(Scoped.cacheStorageReducer);
11
14
  Scoped.cacheStorageReducer = setTimeout(() => {
15
+ const { AuthStore, EmulatedAuth, PendingAuthPurge, DatabaseStore, PendingWrites, ...restStore } = CacheStore;
16
+
12
17
  const txt = encryptString(
13
- JSON.stringify({ ...CacheStore }),
18
+ JSON.stringify({
19
+ AuthStore,
20
+ EmulatedAuth,
21
+ PendingAuthPurge,
22
+ ...promoteCache ? {
23
+ DatabaseStore: serializeToBase64(DatabaseStore),
24
+ PendingWrites: serializeToBase64(PendingWrites)
25
+ } : {},
26
+ ...promoteCache ? restStore : {}
27
+ }),
14
28
  cachePassword,
15
29
  cachePassword
16
30
  );
@@ -19,12 +33,14 @@ export const updateCacheStore = () => {
19
33
  io.output(txt);
20
34
  } else if (cacheProtocol === CACHE_PROTOCOL.ASYNC_STORAGE) {
21
35
  AsyncStorage.setItem(CACHE_STORAGE_PATH, txt);
36
+ } else if (cacheProtocol === CACHE_PROTOCOL.SQLITE) {
37
+ console.error('unsupported protocol "sqlite"');
22
38
  } else {
23
39
  const fs = require('react-native-fs');
24
40
  fs.writeFile(LOCAL_STORAGE_PATH(), txt, 'utf8');
25
41
  }
26
- }, 500);
27
- }
42
+ }, timer);
43
+ };
28
44
 
29
45
  export const releaseCacheStore = async (builder) => {
30
46
  const { cachePassword = DEFAULT_CACHE_PASSWORD, cacheProtocol = CACHE_PROTOCOL.ASYNC_STORAGE, io } = builder;
@@ -41,17 +57,26 @@ export const releaseCacheStore = async (builder) => {
41
57
  }
42
58
 
43
59
  const j = JSON.parse(decryptString(txt || '', cachePassword, cachePassword) || '{}');
60
+ const projectList = new Set([]);
44
61
 
45
62
  Object.entries(j).forEach(([k, v]) => {
46
- CacheStore[k] = v;
63
+ if (['DatabaseStore', 'PendingWrites'].includes(k)) {
64
+ CacheStore[k] = deserializeBSON(v);
65
+ } else CacheStore[k] = v;
66
+ projectList.add(k);
47
67
  });
48
68
  Object.entries(CacheStore.AuthStore).forEach(([key, value]) => {
49
69
  Scoped.AuthJWTToken[key] = value?.token;
50
70
  });
71
+ projectList.forEach(projectUrl => {
72
+ if (Scoped.IS_CONNECTED[projectUrl])
73
+ trySendPendingWrite(projectUrl);
74
+ });
51
75
  Scoped.IsStoreReady = true;
52
76
  StoreReadyListener.dispatch('_', 'ready');
53
- // TODO: commit pending write
54
- }
77
+ };
78
+
79
+ export const getPrefferTime = () => Date.now() + (Scoped.serverTimeOffset || 0);
55
80
 
56
81
  export const awaitStore = () => new Promise(resolve => {
57
82
  if (Scoped.IsStoreReady) {
@@ -92,26 +117,30 @@ export const getReachableServer = (projectUrl) => new Promise(resolve => {
92
117
  }, true);
93
118
  });
94
119
 
95
- export const buildFetchInterface = ({ body, accessKey, authToken, method, uglify, serverE2E_PublicKey }) => {
120
+ export const buildFetchInterface = async ({ body, accessKey, authToken, method, uglify, serverE2E_PublicKey, extraHeaders }) => {
96
121
  if (!uglify) body = JSON.stringify({ ...body });
97
- const [plate, keyPair] = uglify ? serializeE2E(body, authToken, serverE2E_PublicKey) : [undefined, []];
122
+ const [plate, keyPair] = uglify ? await serializeE2E(body, authToken, serverE2E_PublicKey) : [undefined, []];
98
123
 
99
124
  return [{
100
125
  body: uglify ? plate : body,
101
126
  cache: 'no-cache',
102
127
  headers: {
103
- 'Content-type': uglify ? 'text/plain' : 'application/json',
128
+ 'Content-type': uglify ? 'request/buffer' : 'application/json',
104
129
  'Authorization': accessKey,
105
- ...((authToken && !uglify) ? { 'Mosquito-Token': authToken } : {})
130
+ ...(authToken && !uglify) ? { 'Mosquito-Token': authToken } : {},
131
+ ...extraHeaders
106
132
  },
107
133
  method: method || 'POST'
108
134
  }, keyPair];
109
135
  };
110
136
 
111
- export const simplifyError = (error, message) => ({
112
- simpleError: { error, message }
113
- });
114
-
115
- export const validateRequestMethod = (method) => {
116
- // TODO:
117
- }
137
+ export const buildFetchResult = async (fetchRef, ugly) => {
138
+ if (ugly) {
139
+ const [data, simpleError] = deserialize(await fetchRef.arrayBuffer());
140
+ if (simpleError) throw simpleError;
141
+ return data;
142
+ }
143
+ const json = await fetchRef.json();
144
+ if (json.simpleError) throw json;
145
+ return json;
146
+ };
@@ -6,10 +6,7 @@ export const CACHE_STORAGE_PATH = encodeBinary('MOSQUITO_TRANSPORT_FREEZER'),
6
6
  LOCAL_STORAGE_PATH = () => {
7
7
  const fs = require('react-native-fs');
8
8
  return `${Platform.OS === 'android' ? fs.ExternalCachesDirectoryPath : fs.CachesDirectoryPath}/${encodeBinary('MOSQUITO_TRANSPORT_STORAGE')}`;
9
- },
10
- DEFAULT_DB_NAME = 'DEFAULT_DB',
11
- DEFAULT_DB_URL = 'mongodb://127.0.0.1:27017',
12
- DEFAULT_ENCRYPT_IV = '****';
9
+ };
13
10
 
14
11
  export const CACHE_PROTOCOL = {
15
12
  ASYNC_STORAGE: 'async-storage',
@@ -23,7 +20,8 @@ export const RETRIEVAL = {
23
20
  STICKY_RELOAD: 'sticky-reload',
24
21
  DEFAULT: 'default',
25
22
  CACHE_NO_AWAIT: 'cache-no-await',
26
- NO_CACHE_NO_AWAIT: 'no-cache-no-await'
23
+ NO_CACHE_NO_AWAIT: 'no-cache-no-await',
24
+ NO_CACHE_AWAIT: 'no-cache-await'
27
25
  };
28
26
 
29
27
  export const DELIVERY = {
@@ -35,48 +33,11 @@ export const DELIVERY = {
35
33
  CACHE_NO_AWAIT: 'cache-no-await'
36
34
  };
37
35
 
38
- export const WRITE_OPS = {
39
- $SET: '$set',
40
- $PUSH: '$push',
41
- $PULL: '$pull',
42
- $UNSET: '$unset',
43
- $INC: '$inc',
44
- $MAX: '$max',
45
- $MIN: '$min',
46
- $MUL: '$mul',
47
- $RENAME: '$rename',
48
- $SET_ON_INSERT: '$setOnInsert'
49
- };
50
- export const WRITE_OPS_LIST = Object.values(WRITE_OPS);
51
-
52
- export const READ_OPS = {
53
- $IN: '$in',
54
- $ALL: '$all',
55
- $NIN: '$nin',
56
- $GT: '$gt',
57
- $GTE: '$gte',
58
- $LT: '$lt',
59
- $LTE: '$lte',
60
- $TEXT: '$text',
61
- // $EQ: '$eq',
62
- // $REGEX: '$regex',
63
- // $EXISTS: '$exists',
64
- $NEAR: '$near',
65
- $TYPE: '$type',
66
- $SIZE: '$size',
67
- // $NE: '$ne'
68
- };
69
- export const READ_OPS_LIST = Object.values(READ_OPS);
70
-
71
- export const Regexs = {
72
- LINK: () => /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig
73
- };
74
-
75
36
  export const AUTH_PROVIDER_ID = {
76
- GOOGLE: 'google.com',
77
- FACEBOOK: 'facebook.com',
37
+ GOOGLE: 'google',
38
+ FACEBOOK: 'facebook',
78
39
  PASSWORD: 'password',
79
- TWITTER: 'x.com',
80
- GITHUB: 'github.com',
81
- APPLE: 'apple.com'
40
+ TWITTER: 'x',
41
+ GITHUB: 'github',
42
+ APPLE: 'apple'
82
43
  };
@@ -1,4 +1,6 @@
1
+
1
2
  export const Scoped = {
3
+ serverTimeOffset: undefined,
2
4
  PendingIte: 0,
3
5
  AnyProcessIte: 0,
4
6
  IS_CONNECTED: {},
@@ -19,16 +21,22 @@ export const Scoped = {
19
21
  PendingDbReadCollective: {
20
22
  pendingProcess: {},
21
23
  pendingResolution: {}
22
- }
23
- }
24
+ },
25
+ ActiveDatabaseListeners: {},
26
+ OutgoingWrites: {},
27
+ /**
28
+ * @type {Promise<any> | undefined}
29
+ */
30
+ dispatchingWritesPromise: undefined
31
+ };
24
32
 
25
33
  export const CacheStore = {
26
34
  DatabaseStore: {},
27
- DatabaseRecords: {},
28
35
  DatabaseCountResult: {},
36
+ DatabaseStats: {},
29
37
  AuthStore: {},
38
+ PendingAuthPurge: {},
39
+ EmulatedAuth: {},
30
40
  PendingWrites: {},
31
41
  FetchedStore: {}
32
- }
33
-
34
- export const CacheConstant = { ...CacheStore };
42
+ };
package/src/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  interface RNMTConfig {
2
2
  dbName?: string;
3
3
  dbUrl?: string;
4
- heapMemory?: number;
5
4
  projectUrl: string;
6
5
  disableCache?: boolean;
7
6
  accessKey: string;
7
+ /**
8
+ * maximum numbers of attempts to retry sending a request
9
+ */
8
10
  maxRetries?: number;
9
11
  /**
10
12
  * setting this to true will encrypt all outgoing and incoming request. This enables end-to-end encryption using [Tweetnacl](https://github.com/dchest/tweetnacl-js) and to prevent request interception by browser extensions, network intermediaries or other hijacking tools
@@ -14,6 +16,18 @@ interface RNMTConfig {
14
16
  * this is the base64 public key for end-to-end encryption on the server
15
17
  */
16
18
  serverE2E_PublicKey?: string;
19
+ /**
20
+ * extra headers that will be appended to all outgoing request in this instance
21
+ */
22
+ extraHeaders?: {
23
+ [key: string]: string
24
+ };
25
+ /**
26
+ * true to deserialize BSON values to their Node.js closest equivalent types
27
+ *
28
+ * @default true
29
+ */
30
+ castBSON?: boolean;
17
31
  }
18
32
 
19
33
  interface GetDatabase {
@@ -23,7 +37,7 @@ interface GetDatabase {
23
37
  interface mtimestamp { $timestamp: 'now' }
24
38
 
25
39
  export const TIMESTAMP: mtimestamp;
26
- export function DOCUMENT_EXTRACTION(path: string): { $dynamicValue: number };
40
+ export function DOCUMENT_EXTRACTION(path: string): { $dynamicValue: string };
27
41
 
28
42
  type longitude = number;
29
43
  type latitude = number;
@@ -34,7 +48,7 @@ export function GEO_JSON(latitude: latitude, longitude: longitude): {
34
48
  };
35
49
 
36
50
  export function FIND_GEO_JSON(coordinates: [latitude, longitude], offSetMeters: number, centerMeters?: number): {
37
- $near: {
51
+ $nearSphere: {
38
52
  $geometry: {
39
53
  type: "Point",
40
54
  coordinates: [longitude, latitude]
@@ -46,13 +60,20 @@ export function FIND_GEO_JSON(coordinates: [latitude, longitude], offSetMeters:
46
60
 
47
61
  export const AUTH_PROVIDER_ID: auth_provider_id;
48
62
 
63
+ /**
64
+ * useful for avoiding encrypting data and extra overhead
65
+ */
66
+ export class DoNotEncrypt {
67
+ value: any;
68
+ }
69
+
49
70
  interface auth_provider_id {
50
- GOOGLE: 'google.com';
51
- FACEBOOK: 'facebook.com';
71
+ GOOGLE: 'google';
72
+ FACEBOOK: 'facebook';
52
73
  PASSWORD: 'password';
53
- TWITTER: 'x.com';
54
- GITHUB: 'github.com';
55
- APPLE: 'apple.com';
74
+ TWITTER: 'x';
75
+ GITHUB: 'github';
76
+ APPLE: 'apple';
56
77
  }
57
78
 
58
79
  type auth_provider_id_values = auth_provider_id['GOOGLE'] |
@@ -76,7 +97,7 @@ interface ReleaseCacheOption_IO {
76
97
  * emits mosquito-transport internal data
77
98
  */
78
99
  output: (data: string) => void;
79
- }
100
+ };
80
101
  }
81
102
 
82
103
  interface ReleaseCacheOption {
@@ -90,6 +111,17 @@ interface ReleaseCacheOption {
90
111
  * - reat-native-fs: uses [reat-native-fs](https://github.com/itinance/react-native-fs) for storing data, make sure you have this package installed before setting this as the value
91
112
  */
92
113
  cacheProtocol?: 'async-storage' | 'reat-native-fs';
114
+ /**
115
+ * the maximum database size
116
+ */
117
+ heapMemory?: number;
118
+ /**
119
+ * true to cache database and {@link RNMT.fetchHttp} data.
120
+ * the value only applies to in-memory storage protocol such as `io`, `async-storage` and `reat-native-fs`
121
+ *
122
+ * @default false
123
+ */
124
+ promoteCache?: boolean;
93
125
  }
94
126
 
95
127
  interface RNMTSocket {
@@ -97,7 +129,7 @@ interface RNMTSocket {
97
129
  emitWithAck: (...args: any) => Promise<any>;
98
130
  });
99
131
  emit: (...args: any) => void;
100
- emitWithAck: () => Promise<any>;
132
+ emitWithAck: (...args: any) => Promise<any>;
101
133
  on: (route: string, callback?: () => any) => void;
102
134
  once: (route: string, callback?: () => any) => void;
103
135
  destroy: () => void;
@@ -116,7 +148,7 @@ interface BatchWriteConfig extends WriteConfig {
116
148
 
117
149
  export default class RNMT {
118
150
  constructor(config: RNMTConfig);
119
- static releaseCache(option?: ReleaseCacheOption | ReleaseCacheOption_IO): void;
151
+ static initializeCache(option?: ReleaseCacheOption | ReleaseCacheOption_IO): void;
120
152
  getDatabase(dbName?: string, dbUrl?: string): GetDatabase;
121
153
  collection(path: string): RNMTCollection;
122
154
  auth(): RNMTAuth;
@@ -244,7 +276,7 @@ interface WriteConfig {
244
276
  delivery?: Delievery;
245
277
  }
246
278
 
247
- type Retrieval = 'sticky' | 'sticky-no-await' | 'sticky-reload' | 'default' | 'cache-no-await' | 'no-cache-no-await';
279
+ type Retrieval = 'sticky' | 'sticky-no-await' | 'sticky-reload' | 'default' | 'cache-no-await' | 'no-cache-no-await' | 'no-cache-await';
248
280
 
249
281
  interface GetConfig {
250
282
  excludeFields?: string | string[];
@@ -253,17 +285,19 @@ interface GetConfig {
253
285
  /**
254
286
  * This property determines how requested data is being access and handled
255
287
  *
256
- * - default: we try getting fresh data from server if server is reachable, else we check if local data exists and return it, if no local data exist we await for client->server connectivity, then try getting the data, return it and cache it for future need. ⚠️ This respect disableCache value
288
+ * - default: will try getting fresh data from server if server is reachable, else we check if local data exists and return it, if no local data exist we await for client->server connectivity, then try getting the data, return it and cache it for future need. ⚠️ This respect disableCache value
257
289
  *
258
290
  * - sticky: if local data exists for the specified query, such data is returned and no-ops afterwards. If no local data is found, we await for client->server connectivity and try to get fresh data from serve, return the data and cache it for future need. ⚠️ This does not respect disableCache value
259
291
  *
260
- * - sticky-no-await: if local data exists for the specified query, such data is returned and no-ops afterwards. If no local data is found, we try to get fresh data from serve, we throw an error if server is not reachable else if server returns requested data, we return such data and cache it for future need. ⚠️ This does not respect disableCache value
292
+ * - sticky-no-await: if local data exists for the specified query, such data is returned and no-ops afterwards. If no local data is found, will try to get fresh data from serve, we throw an error if server is not reachable else if server returns requested data, we return such data and cache it for future need. ⚠️ This does not respect disableCache value
261
293
  *
262
- * - sticky-reload: if local data exists for the specified query, such data is returned, then we try getting fresh data from the server and caching it for future need. If no local data is found, we await for client->server connectivity and try to get fresh data from serve, return the data and cache it for future need
294
+ * - sticky-reload: if local data exists for the specified query, such data is returned, then will try getting fresh data from the server and caching it for future need. If no local data is found, we await for client->server connectivity and try to get fresh data from serve, return the data and cache it for future need
263
295
  *
264
- * - cache-no-await: we try getting fresh data from server if server is reachable, else we check if local data exists and return it, if no local data exist we throw an error
296
+ * - cache-no-await: will try getting fresh data from server if server is reachable, else we check if local data exists and return it, if no local data exist we throw an error
265
297
  *
266
- * - no-cache-no-await: we try getting fresh data from server if server is reachable, else we throw an error
298
+ * - no-cache-no-await: will try getting fresh data from server if server is reachable, else we throw an error
299
+ *
300
+ * - no-cache-await: will try getting fresh data from server when server is reachable and the result won't be cache
267
301
  *
268
302
  * To learn and see more examples on this, Please visit https://brainbehindx.com/mosquito-transport/docs/reading_data/retrieval
269
303
  */
@@ -278,33 +312,31 @@ interface GetConfig {
278
312
  */
279
313
  episode?: 0 | 1;
280
314
  /**
281
- * send authentication token along with this request
315
+ * disable sending authentication token along with this request
282
316
  *
283
317
  * @default - false
284
318
  */
285
319
  disableAuth?: boolean;
286
320
  /**
287
- * this reduces duplicate query calls with the same operation resultant to a single request call.
321
+ * this reduces redundant network calls for the same query operation to a single request call.
288
322
  *
289
- * - Example:
323
+ * @example
290
324
  *
291
325
  * ```js
292
326
  *
293
327
  * const mserver = new RNMT({ projectUrl: 'http..', accessKey: '..'});
294
- * const minimizedUser = ['james', 'john', 'james', 'john'];
295
- * const unminimizedUser = ['anthony', 'albert', 'anthony', 'albert'];
296
328
  *
297
- * // operation will be reduced to two request: james and john
329
+ * // operation will be reduced to only one request
298
330
  *
299
- * minimizedUser.forEach(e=> {
300
- * mserver.collection('user').findOne({ _id: e }).get();
301
- * });
331
+ * for (let i = 0; i < 1000; i++) {
332
+ * mserver.collection('user').findOne({ company: 'brainbehindx' }).get({ disableMinimizer: false });
333
+ * }
302
334
  *
303
- * // operation will not be reduced and therefore four request will be sent: anthony, albert, anthony, albert
335
+ * // operation will not be reduced and therefore 1000 network calls will be made
304
336
  *
305
- * unminimizedUser.forEach(e=> {
306
- * mserver.collection('user').findOne({ _id: e }).get();
307
- * });
337
+ * for (let i = 0; i < 1000; i++) {
338
+ * mserver.collection('user').findOne({ company: 'brainbehindx' }).get({ disableMinimizer: true });
339
+ * }
308
340
  * ```
309
341
  * defaults to false
310
342
  *
@@ -318,8 +350,13 @@ interface GetConfigExtraction {
318
350
  sort: string;
319
351
  direction?: 'desc' | 'asc' | 1 | -1
320
352
  collection: string;
321
- find?: DocumentFind;
322
- findOne?: DocumentFind
353
+ find?: DocumentFind | DynamicValueExtraction<{ $dynamicValue: string }>;
354
+ findOne?: DocumentFind | DynamicValueExtraction<{ $dynamicValue: string }>;
355
+ returnOnly: string | string[]
356
+ }
357
+
358
+ interface DynamicValueExtraction<T> {
359
+ [key: string]: T
323
360
  }
324
361
 
325
362
  interface DocumentFind {
@@ -356,15 +393,16 @@ interface RNMTAuth {
356
393
  twitterSignin: () => Promise<SignupResult>;
357
394
  githubSignin: () => Promise<SignupResult>;
358
395
  listenVerifiedStatus: (callback?: (verified?: boolean) => void, onError?: (error?: ErrorResponse) => void) => () => void;
359
- listenAuthToken: (callback: (token: string) => void) => () => void;
360
- getAuthToken: () => Promise<string>;
361
- getRefreshToken: () => Promise<string>;
362
- getRefreshTokenData: () => Promise<RefreshTokenData>;
363
- parseToken: () => string;
364
- listenAuth: (callback: (auth: TokenEventData) => void) => () => void;
396
+ listenAuthToken: (callback: (token: string | null) => void) => () => void;
397
+ getAuthToken: () => Promise<string | null>;
398
+ getRefreshToken: () => Promise<string | undefined>;
399
+ getRefreshTokenData: () => Promise<RefreshTokenData | undefined>;
400
+ parseToken: (token: string) => AuthData | RefreshTokenData;
401
+ listenAuth: (callback: (auth: TokenEventData | null) => void) => () => void;
365
402
  getAuth: () => Promise<TokenEventData>;
366
403
  signOut: () => Promise<void>;
367
404
  forceRefreshToken: () => Promise<string>;
405
+ emulate: (projectUrl?: string) => Promise<void>;
368
406
  }
369
407
 
370
408
  interface SigninResult {
@@ -403,10 +441,14 @@ interface RefreshTokenData {
403
441
  uid: string;
404
442
  tokenID: string;
405
443
  isRefreshToken: true;
444
+ exp: number;
445
+ aud: string;
446
+ iss: string;
447
+ sub: string;
406
448
  }
407
449
 
408
450
  interface TokenEventData extends AuthData {
409
- tokenManager: TokenManager | null;
451
+ tokenManager: TokenManager;
410
452
  }
411
453
 
412
454
  interface TokenManager {
@@ -414,9 +456,27 @@ interface TokenManager {
414
456
  accessToken: string;
415
457
  }
416
458
 
459
+ interface UploadOptions {
460
+ /**
461
+ * optionally create hash for this upload to save disk space
462
+ */
463
+ createHash?: boolean;
464
+ /**
465
+ * wait for a reachable server before initiating the upload task
466
+ */
467
+ awaitServer?: boolean;
468
+ }
469
+
470
+ interface DownloadOptions {
471
+ /**
472
+ * wait for a reachable server before initiating the download task
473
+ */
474
+ awaitServer?: boolean;
475
+ }
476
+
417
477
  interface RNMTStorage {
418
- downloadFile: (link: string, onComplete?: (error?: ErrorResponse, filepath?: string) => void, destination?: string, onProgress?: (stats: DownloadProgressStats) => void) => () => void;
419
- uploadFile: (file: string, destination: string, onComplete?: (error?: ErrorResponse, downloadUrl?: string) => void, onProgress?: (stats: UploadProgressStats) => void) => () => void;
478
+ downloadFile: (link: string, onComplete?: (error?: ErrorResponse, filepath?: string) => void, destination?: string, onProgress?: (stats: DownloadProgressStats) => void, options?: DownloadOptions) => () => void;
479
+ uploadFile: (file: string, destination: string, onComplete?: (error?: ErrorResponse, downloadUrl?: string) => void, onProgress?: (stats: UploadProgressStats) => void, options?: UploadOptions) => () => void;
420
480
  deleteFile: (path: string) => Promise<void>;
421
481
  deleteFolder: (folder: string) => Promise<void>;
422
482
  }
@@ -440,13 +500,13 @@ interface ErrorResponse {
440
500
  }
441
501
 
442
502
  /** @public */
443
- export declare type Sort = string | Exclude<SortDirection, {
503
+ declare type Sort = string | Exclude<SortDirection, {
444
504
  $meta: string;
445
505
  }> | string[] | {
446
506
  [key: string]: SortDirection;
447
507
  } | Map<string, SortDirection> | [string, SortDirection][] | [string, SortDirection];
448
508
 
449
509
  /** @public */
450
- export declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | {
510
+ declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | {
451
511
  $meta: string;
452
512
  };