@rpcbase/client 0.385.0 → 0.387.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import { createContext, useContext, useId, useMemo, useState, useRef, useEffect } from "react";
2
2
  import { jsx } from "react/jsx-runtime";
3
+ import { c } from "react/compiler-runtime";
3
4
  const STATIC_RPCBASE_RTS_HYDRATION_DATA_KEY = "__staticRpcbaseRtsHydrationData";
4
5
  const RtsSsrRuntimeContext = createContext(null);
5
6
  const hydrationDataStore = /* @__PURE__ */ new Map();
@@ -19,8 +20,12 @@ const normalizePageInfo$2 = (value) => {
19
20
  return {
20
21
  hasNextPage: raw.hasNextPage,
21
22
  hasPrevPage: raw.hasPrevPage,
22
- ...nextCursor ? { nextCursor } : {},
23
- ...prevCursor ? { prevCursor } : {}
23
+ ...nextCursor ? {
24
+ nextCursor
25
+ } : {},
26
+ ...prevCursor ? {
27
+ prevCursor
28
+ } : {}
24
29
  };
25
30
  };
26
31
  const parseHydrationData = (value) => {
@@ -41,7 +46,9 @@ const parseHydrationData = (value) => {
41
46
  modelName,
42
47
  queryKey,
43
48
  data: query.data,
44
- ...pageInfo ? { pageInfo } : {}
49
+ ...pageInfo ? {
50
+ pageInfo
51
+ } : {}
45
52
  });
46
53
  }
47
54
  return {
@@ -80,11 +87,22 @@ const clearHydratedRtsQueryData = () => {
80
87
  hydrationDataStore.clear();
81
88
  hydrationPageInfoStore.clear();
82
89
  };
83
- const RtsSsrRuntimeProvider = ({
84
- value,
85
- children
86
- }) => {
87
- return /* @__PURE__ */ jsx(RtsSsrRuntimeContext.Provider, { value, children });
90
+ const RtsSsrRuntimeProvider = (t0) => {
91
+ const $ = c(3);
92
+ const {
93
+ value,
94
+ children
95
+ } = t0;
96
+ let t1;
97
+ if ($[0] !== children || $[1] !== value) {
98
+ t1 = /* @__PURE__ */ jsx(RtsSsrRuntimeContext.Provider, { value, children });
99
+ $[0] = children;
100
+ $[1] = value;
101
+ $[2] = t1;
102
+ } else {
103
+ t1 = $[2];
104
+ }
105
+ return t1;
88
106
  };
89
107
  const useRtsSsrRuntime = () => {
90
108
  return useContext(RtsSsrRuntimeContext);
@@ -106,17 +124,29 @@ const ensureBrowser$1 = () => {
106
124
  throw new Error("RTS PouchDB store can only be used in the browser");
107
125
  }
108
126
  };
109
- const computeBasePrefix = ({ tenantId, appName }) => {
127
+ const computeBasePrefix = ({
128
+ tenantId,
129
+ appName
130
+ }) => {
110
131
  let prefix = "rb/";
111
132
  if (appName) prefix += `${appName}/`;
112
133
  prefix += `${tenantId}/`;
113
134
  return prefix;
114
135
  };
115
136
  const getDbNamesKey = (prefix) => `rb:rts:pouchDbs:${prefix}`;
116
- const getPrefixOverrideKey = ({ tenantId, appName }) => `rb:rts:pouchPrefix:${appName ?? ""}:${tenantId}`;
117
- const readPrefixOverride = ({ tenantId, appName }) => {
137
+ const getPrefixOverrideKey = ({
138
+ tenantId,
139
+ appName
140
+ }) => `rb:rts:pouchPrefix:${appName ?? ""}:${tenantId}`;
141
+ const readPrefixOverride = ({
142
+ tenantId,
143
+ appName
144
+ }) => {
118
145
  try {
119
- const value = window.localStorage.getItem(getPrefixOverrideKey({ tenantId, appName }));
146
+ const value = window.localStorage.getItem(getPrefixOverrideKey({
147
+ tenantId,
148
+ appName
149
+ }));
120
150
  if (!value) return null;
121
151
  if (!value.endsWith("/")) return `${value}/`;
122
152
  return value;
@@ -129,8 +159,14 @@ const getPrefix = () => {
129
159
  throw new Error("RTS PouchDB store is not configured");
130
160
  }
131
161
  if (storeConfig.prefix) return storeConfig.prefix;
132
- const basePrefix = computeBasePrefix({ tenantId: storeConfig.tenantId, appName: storeConfig.appName });
133
- const override = readPrefixOverride({ tenantId: storeConfig.tenantId, appName: storeConfig.appName });
162
+ const basePrefix = computeBasePrefix({
163
+ tenantId: storeConfig.tenantId,
164
+ appName: storeConfig.appName
165
+ });
166
+ const override = readPrefixOverride({
167
+ tenantId: storeConfig.tenantId,
168
+ appName: storeConfig.appName
169
+ });
134
170
  return override ?? basePrefix;
135
171
  };
136
172
  const loadDbNames = (prefix) => {
@@ -183,11 +219,7 @@ const getPouchDb = async () => {
183
219
  ensureBrowser$1();
184
220
  if (!pouchDbPromise) {
185
221
  pouchDbPromise = (async () => {
186
- const [core, indexedDbAdapter, findPlugin] = await Promise.all([
187
- import("pouchdb-core"),
188
- import("pouchdb-adapter-indexeddb"),
189
- import("pouchdb-find")
190
- ]);
222
+ const [core, indexedDbAdapter, findPlugin] = await Promise.all([import("pouchdb-core"), import("pouchdb-adapter-indexeddb"), import("pouchdb-find")]);
191
223
  const PouchDB = unwrapDefault(core);
192
224
  PouchDB.plugin(unwrapDefault(indexedDbAdapter));
193
225
  PouchDB.plugin(unwrapDefault(findPlugin));
@@ -216,7 +248,10 @@ const getCollection = async (modelName, options) => {
216
248
  const existing = collections.get(dbKey);
217
249
  if (existing) return existing;
218
250
  registerDbName(prefix, dbName);
219
- const db = new PouchDB(dbName, { adapter: "indexeddb", revs_limit: 1 });
251
+ const db = new PouchDB(dbName, {
252
+ adapter: "indexeddb",
253
+ revs_limit: 1
254
+ });
220
255
  collections.set(dbKey, db);
221
256
  return db;
222
257
  };
@@ -276,17 +311,21 @@ const runQuery = async ({
276
311
  query = {},
277
312
  options
278
313
  }) => {
279
- const collection = await getCollection(modelName, { uid: options.uid });
280
- const replacedQuery = replaceQueryKeys(
281
- query,
282
- (key) => key.startsWith("_") && key !== "_id" ? `${UNDERSCORE_PREFIX}${key}` : key
283
- );
314
+ const collection = await getCollection(modelName, {
315
+ uid: options.uid
316
+ });
317
+ const replacedQuery = replaceQueryKeys(query, (key) => key.startsWith("_") && key !== "_id" ? `${UNDERSCORE_PREFIX}${key}` : key);
284
318
  const limit = typeof options.limit === "number" ? Math.abs(options.limit) : DEFAULT_FIND_LIMIT;
285
- const { docs } = await collection.find({
319
+ const {
320
+ docs
321
+ } = await collection.find({
286
322
  selector: replacedQuery,
287
323
  limit
288
324
  });
289
- let mappedDocs = docs.map(({ _rev: _revIgnored, ...rest }) => remapDocFromStorage(rest));
325
+ let mappedDocs = docs.map(({
326
+ _rev: _revIgnored,
327
+ ...rest
328
+ }) => remapDocFromStorage(rest));
290
329
  if (options.projection) {
291
330
  mappedDocs = mappedDocs.filter((doc) => satisfiesProjection(doc, options.projection));
292
331
  }
@@ -311,14 +350,27 @@ const runQuery = async ({
311
350
  return 0;
312
351
  });
313
352
  }
314
- return { data: mappedDocs, context: { source: "cache" } };
353
+ return {
354
+ data: mappedDocs,
355
+ context: {
356
+ source: "cache"
357
+ }
358
+ };
315
359
  };
316
360
  const updateDocs = async (modelName, data, uid) => {
317
- const collection = await getCollection(modelName, { uid });
361
+ const collection = await getCollection(modelName, {
362
+ uid
363
+ });
318
364
  const allIds = data.map((doc) => doc._id).filter(Boolean);
319
365
  if (!allIds.length) return;
320
- const { docs: currentDocs } = await collection.find({
321
- selector: { _id: { $in: allIds } },
366
+ const {
367
+ docs: currentDocs
368
+ } = await collection.find({
369
+ selector: {
370
+ _id: {
371
+ $in: allIds
372
+ }
373
+ },
322
374
  fields: ["_id", "_rev"],
323
375
  limit: allIds.length
324
376
  });
@@ -328,12 +380,16 @@ const updateDocs = async (modelName, data, uid) => {
328
380
  return acc;
329
381
  }, {});
330
382
  const newDocs = data.map((mongoDoc) => {
331
- const currentDoc = currentDocsById[mongoDoc._id] ?? { _id: mongoDoc._id };
383
+ const currentDoc = currentDocsById[mongoDoc._id] ?? {
384
+ _id: mongoDoc._id
385
+ };
332
386
  const nextDoc = Object.entries(mongoDoc).reduce((acc, [key, value]) => {
333
387
  const newKey = key !== "_id" && key.startsWith("_") ? `${UNDERSCORE_PREFIX}${key}` : key;
334
388
  acc[newKey] = value;
335
389
  return acc;
336
- }, { ...currentDoc });
390
+ }, {
391
+ ...currentDoc
392
+ });
337
393
  const rev = currentDoc._rev;
338
394
  if (typeof rev === "string" && rev) {
339
395
  nextDoc._rev = rev;
@@ -345,11 +401,19 @@ const updateDocs = async (modelName, data, uid) => {
345
401
  await collection.bulkDocs(newDocs);
346
402
  };
347
403
  const deleteDocs = async (modelName, ids, uid) => {
348
- const collection = await getCollection(modelName, { uid });
404
+ const collection = await getCollection(modelName, {
405
+ uid
406
+ });
349
407
  const allIds = ids.map((id) => String(id ?? "")).filter(Boolean);
350
408
  if (!allIds.length) return;
351
- const { docs: currentDocs } = await collection.find({
352
- selector: { _id: { $in: allIds } },
409
+ const {
410
+ docs: currentDocs
411
+ } = await collection.find({
412
+ selector: {
413
+ _id: {
414
+ $in: allIds
415
+ }
416
+ },
353
417
  fields: ["_id", "_rev"],
354
418
  limit: allIds.length
355
419
  });
@@ -362,17 +426,28 @@ const deleteDocs = async (modelName, ids, uid) => {
362
426
  await collection.bulkDocs(deletions);
363
427
  };
364
428
  const destroyCollection = async (modelName, uid) => {
365
- const collection = await getCollection(modelName, { uid });
429
+ const collection = await getCollection(modelName, {
430
+ uid
431
+ });
366
432
  const prefix = getPrefix();
367
433
  const dbName = `${uid}/${modelName}`;
368
434
  collections.delete(`${prefix}${dbName}`);
369
435
  unregisterDbName(prefix, dbName);
370
436
  await collection.destroy();
371
437
  };
372
- const resetRtsPouchStore = ({ tenantId, appName }) => {
438
+ const resetRtsPouchStore = ({
439
+ tenantId,
440
+ appName
441
+ }) => {
373
442
  ensureBrowser$1();
374
- const basePrefix = computeBasePrefix({ tenantId, appName });
375
- const oldPrefix = readPrefixOverride({ tenantId, appName }) ?? basePrefix;
443
+ const basePrefix = computeBasePrefix({
444
+ tenantId,
445
+ appName
446
+ });
447
+ const oldPrefix = readPrefixOverride({
448
+ tenantId,
449
+ appName
450
+ }) ?? basePrefix;
376
451
  const dbNames = Array.from(loadDbNames(oldPrefix));
377
452
  const openDbs = Array.from(collections.entries()).filter(([key]) => key.startsWith(oldPrefix)).map(([, db]) => db);
378
453
  void (async () => {
@@ -384,7 +459,10 @@ const resetRtsPouchStore = ({ tenantId, appName }) => {
384
459
  const PouchDBForPrefix = PouchDB.defaults?.({}) ?? PouchDB;
385
460
  PouchDBForPrefix.prefix = oldPrefix;
386
461
  await Promise.all(Array.from(remaining).map(async (name) => {
387
- const db = new PouchDBForPrefix(name, { adapter: "indexeddb", revs_limit: 1 });
462
+ const db = new PouchDBForPrefix(name, {
463
+ adapter: "indexeddb",
464
+ revs_limit: 1
465
+ });
388
466
  await db.destroy().then(() => {
389
467
  remaining.delete(name);
390
468
  }).catch(() => {
@@ -399,7 +477,10 @@ const resetRtsPouchStore = ({ tenantId, appName }) => {
399
477
  })();
400
478
  const newPrefix = `${basePrefix}reset-${Date.now().toString(16)}/`;
401
479
  try {
402
- window.localStorage.setItem(getPrefixOverrideKey({ tenantId, appName }), newPrefix);
480
+ window.localStorage.setItem(getPrefixOverrideKey({
481
+ tenantId,
482
+ appName
483
+ }), newPrefix);
403
484
  } catch {
404
485
  return newPrefix;
405
486
  }
@@ -466,7 +547,9 @@ const sendToServer = (message) => {
466
547
  if (socket.readyState !== WebSocket.OPEN) return;
467
548
  socket.send(JSON.stringify(message));
468
549
  };
469
- const resubscribeAll = ({ forceInitialQuery }) => {
550
+ const resubscribeAll = ({
551
+ forceInitialQuery
552
+ }) => {
470
553
  for (const sub of subscriptions.values()) {
471
554
  const runInitialQuery = forceInitialQuery || sub.runInitialNetworkQuery;
472
555
  sendToServer({
@@ -506,7 +589,9 @@ const scheduleReconnect = () => {
506
589
  }
507
590
  reconnectAttempts += 1;
508
591
  reconnectTimer = window.setTimeout(() => {
509
- void connectInternal(currentTenantId, currentUid, connectOptions, { resetReconnectAttempts: false });
592
+ void connectInternal(currentTenantId, currentUid, connectOptions, {
593
+ resetReconnectAttempts: false
594
+ });
510
595
  }, delay);
511
596
  };
512
597
  const isDocWithId = (doc) => {
@@ -523,12 +608,22 @@ const normalizePageInfo$1 = (value) => {
523
608
  return {
524
609
  hasNextPage: raw.hasNextPage,
525
610
  hasPrevPage: raw.hasPrevPage,
526
- ...nextCursor ? { nextCursor } : {},
527
- ...prevCursor ? { prevCursor } : {}
611
+ ...nextCursor ? {
612
+ nextCursor
613
+ } : {},
614
+ ...prevCursor ? {
615
+ prevCursor
616
+ } : {}
528
617
  };
529
618
  };
530
619
  const handleQueryPayload = (payload) => {
531
- const { modelName, queryKey, data, error, txnId } = payload;
620
+ const {
621
+ modelName,
622
+ queryKey,
623
+ data,
624
+ error,
625
+ txnId
626
+ } = payload;
532
627
  const cbKey = `${modelName}.${queryKey}`;
533
628
  const callbacks = queryCallbacks.get(cbKey);
534
629
  if (!callbacks || !callbacks.size) return;
@@ -537,7 +632,14 @@ const handleQueryPayload = (payload) => {
537
632
  const hasPopulate = Boolean(subscription?.options?.populate);
538
633
  const hasPagination = Boolean(subscription?.options?.pagination || pageInfo);
539
634
  const isLocal = !!(txnId && localTxnBuf.includes(txnId));
540
- const context = { source: "network", isLocal, txnId, ...pageInfo ? { pageInfo } : {} };
635
+ const context = {
636
+ source: "network",
637
+ isLocal,
638
+ txnId,
639
+ ...pageInfo ? {
640
+ pageInfo
641
+ } : {}
642
+ };
541
643
  if (error) {
542
644
  for (const cb of callbacks) cb(error, void 0, context);
543
645
  return;
@@ -580,7 +682,11 @@ const addLocalTxn = (txnId) => {
580
682
  localTxnBuf.shift();
581
683
  }
582
684
  };
583
- const getSyncStorageKey = ({ tenantId, uid, appName }) => `rb:rts:changesSeq:${appName ?? ""}:${tenantId}:${uid}`;
685
+ const getSyncStorageKey = ({
686
+ tenantId,
687
+ uid,
688
+ appName
689
+ }) => `rb:rts:changesSeq:${appName ?? ""}:${tenantId}:${uid}`;
584
690
  const readStoredSeq = (key) => {
585
691
  try {
586
692
  const raw = window.localStorage.getItem(key);
@@ -628,15 +734,24 @@ const applyChangeBatch = async (changes, uid) => {
628
734
  const syncRtsChanges = async (tenantId, uid, options = {}) => {
629
735
  ensureBrowser();
630
736
  if (!tenantId || !uid) return;
631
- const storageKey = getSyncStorageKey({ tenantId, uid, appName: options.appName });
737
+ const storageKey = getSyncStorageKey({
738
+ tenantId,
739
+ uid,
740
+ appName: options.appName
741
+ });
632
742
  let sinceSeq = readStoredSeq(storageKey);
633
743
  for (let i = 0; i < 32; i += 1) {
634
744
  const url = `${RTS_CHANGES_ROUTE}?${TENANT_ID_QUERY_PARAM}=${encodeURIComponent(tenantId)}`;
635
745
  const response = await fetch(url, {
636
746
  method: "POST",
637
747
  credentials: "include",
638
- headers: { "Content-Type": "application/json" },
639
- body: JSON.stringify({ sinceSeq, limit: 2e3 })
748
+ headers: {
749
+ "Content-Type": "application/json"
750
+ },
751
+ body: JSON.stringify({
752
+ sinceSeq,
753
+ limit: 2e3
754
+ })
640
755
  });
641
756
  if (!response.ok) return;
642
757
  const payload = await response.json().catch(() => null);
@@ -647,29 +762,37 @@ const syncRtsChanges = async (tenantId, uid, options = {}) => {
647
762
  const latestSeq = Number(payloadObj.latestSeq ?? 0);
648
763
  const needsFullResync = Boolean(payloadObj.needsFullResync);
649
764
  if (needsFullResync) {
650
- resetRtsPouchStore({ tenantId, appName: options.appName });
765
+ resetRtsPouchStore({
766
+ tenantId,
767
+ appName: options.appName
768
+ });
651
769
  writeStoredSeq(storageKey, latestSeq);
652
770
  return;
653
771
  }
654
772
  const changesRaw = payloadObj.changes;
655
773
  const changes = Array.isArray(changesRaw) ? changesRaw : [];
656
- const normalized = changes.map((c) => {
657
- if (!c || typeof c !== "object") return null;
658
- const obj = c;
774
+ const normalized = changes.map((c2) => {
775
+ if (!c2 || typeof c2 !== "object") return null;
776
+ const obj = c2;
659
777
  const seq = Number(obj.seq ?? 0);
660
778
  const modelName = typeof obj.modelName === "string" ? obj.modelName : String(obj.modelName ?? "");
661
779
  const op = obj.op === "reset_model" ? "reset_model" : "delete";
662
780
  const docId = typeof obj.docId === "string" && obj.docId ? obj.docId : obj.docId ? String(obj.docId) : void 0;
663
- return { seq, modelName, op, ...docId ? { docId } : {} };
664
- }).filter((c) => c !== null).filter(
665
- (c) => Number.isFinite(c.seq) && c.seq > 0 && c.modelName && (c.op === "reset_model" || !!c.docId)
666
- );
781
+ return {
782
+ seq,
783
+ modelName,
784
+ op,
785
+ ...docId ? {
786
+ docId
787
+ } : {}
788
+ };
789
+ }).filter((c2) => c2 !== null).filter((c2) => Number.isFinite(c2.seq) && c2.seq > 0 && c2.modelName && (c2.op === "reset_model" || !!c2.docId));
667
790
  if (!normalized.length) {
668
791
  writeStoredSeq(storageKey, latestSeq);
669
792
  return;
670
793
  }
671
794
  await applyChangeBatch(normalized, uid);
672
- const lastSeq = normalized.reduce((max, c) => c.seq > max ? c.seq : max, sinceSeq);
795
+ const lastSeq = normalized.reduce((max, c2) => c2.seq > max ? c2.seq : max, sinceSeq);
673
796
  sinceSeq = lastSeq;
674
797
  writeStoredSeq(storageKey, sinceSeq);
675
798
  if (latestSeq > 0 && sinceSeq >= latestSeq) {
@@ -682,14 +805,18 @@ const ensureSynced = (tenantId, uid, options) => {
682
805
  const key = `${options.appName ?? ""}:${tenantId}:${uid}`;
683
806
  if (syncPromise && syncKey === key) return;
684
807
  syncKey = key;
685
- syncPromise = syncRtsChanges(tenantId, uid, { appName: options.appName }).catch(() => {
808
+ syncPromise = syncRtsChanges(tenantId, uid, {
809
+ appName: options.appName
810
+ }).catch(() => {
686
811
  }).finally(() => {
687
812
  if (syncKey === key) {
688
813
  syncPromise = null;
689
814
  }
690
815
  });
691
816
  };
692
- const connectInternal = (tenantId, uid, options, { resetReconnectAttempts }) => {
817
+ const connectInternal = (tenantId, uid, options, {
818
+ resetReconnectAttempts
819
+ }) => {
693
820
  ensureBrowser();
694
821
  if (!tenantId) return Promise.resolve();
695
822
  if (!uid) throw new Error("Missing uid");
@@ -697,7 +824,10 @@ const connectInternal = (tenantId, uid, options, { resetReconnectAttempts }) =>
697
824
  currentUid = uid;
698
825
  connectOptions = options;
699
826
  if (options.configureStore !== false) {
700
- configureRtsPouchStore({ tenantId, appName: options.appName });
827
+ configureRtsPouchStore({
828
+ tenantId,
829
+ appName: options.appName
830
+ });
701
831
  }
702
832
  ensureSynced(tenantId, uid, options);
703
833
  if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) {
@@ -717,7 +847,9 @@ const connectInternal = (tenantId, uid, options, { resetReconnectAttempts }) =>
717
847
  reconnectAttempts = 0;
718
848
  pendingServerReconnectJitter = false;
719
849
  const forceInitialQuery = hasEstablishedConnection;
720
- resubscribeAll({ forceInitialQuery });
850
+ resubscribeAll({
851
+ forceInitialQuery
852
+ });
721
853
  hasEstablishedConnection = true;
722
854
  resolve();
723
855
  });
@@ -743,7 +875,9 @@ const connectInternal = (tenantId, uid, options, { resetReconnectAttempts }) =>
743
875
  return connectPromise;
744
876
  };
745
877
  const connect = (tenantId, uid, options = {}) => {
746
- return connectInternal(tenantId, uid, options, { resetReconnectAttempts: true });
878
+ return connectInternal(tenantId, uid, options, {
879
+ resetReconnectAttempts: true
880
+ });
747
881
  };
748
882
  const disconnect = () => {
749
883
  explicitDisconnect = true;
@@ -796,7 +930,13 @@ const registerQuery = (modelName, query, optionsOrCallback, callbackMaybe, behav
796
930
  const set = queryCallbacks.get(cbKey) ?? /* @__PURE__ */ new Set();
797
931
  set.add(callback);
798
932
  queryCallbacks.set(cbKey, set);
799
- subscriptions.set(cbKey, { modelName, query, options, queryKey, runInitialNetworkQuery });
933
+ subscriptions.set(cbKey, {
934
+ modelName,
935
+ query,
936
+ options,
937
+ queryKey,
938
+ runInitialNetworkQuery
939
+ });
800
940
  if (currentUid && runInitialLocalQuery && !hasPopulate && !hasPagination) {
801
941
  void runQuery({
802
942
  modelName,
@@ -807,14 +947,28 @@ const registerQuery = (modelName, query, optionsOrCallback, callbackMaybe, behav
807
947
  sort: options.sort,
808
948
  limit: options.limit
809
949
  }
810
- }).then(({ data, context }) => {
950
+ }).then(({
951
+ data,
952
+ context
953
+ }) => {
811
954
  callback?.(null, data, context);
812
955
  }).catch(() => {
813
956
  });
814
957
  }
815
- sendToServer({ type: "register-query", modelName, queryKey, query, options, runInitialQuery: runInitialNetworkQuery });
958
+ sendToServer({
959
+ type: "register-query",
960
+ modelName,
961
+ queryKey,
962
+ query,
963
+ options,
964
+ runInitialQuery: runInitialNetworkQuery
965
+ });
816
966
  return () => {
817
- sendToServer({ type: "remove-query", modelName, queryKey });
967
+ sendToServer({
968
+ type: "remove-query",
969
+ modelName,
970
+ queryKey
971
+ });
818
972
  const callbacks = queryCallbacks.get(cbKey);
819
973
  callbacks?.delete(callback);
820
974
  if (callbacks && callbacks.size === 0) {
@@ -833,10 +987,23 @@ const runNetworkQuery = async ({
833
987
  if (typeof modelName !== "string" || modelName.trim().length === 0) {
834
988
  throw new Error("runNetworkQuery: modelName must be a non-empty string");
835
989
  }
990
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
991
+ if (currentTenantId && currentUid) {
992
+ try {
993
+ await connectInternal(currentTenantId, currentUid, connectOptions, {
994
+ resetReconnectAttempts: false
995
+ });
996
+ } catch {
997
+ }
998
+ }
999
+ }
836
1000
  if (!socket || socket.readyState !== WebSocket.OPEN) {
837
1001
  throw new Error("runNetworkQuery: RTS socket is not connected");
838
1002
  }
839
- const resolvedOptions = options.key ? options : { ...options, key: makeRunQueryKey() };
1003
+ const resolvedOptions = options.key ? options : {
1004
+ ...options,
1005
+ key: makeRunQueryKey()
1006
+ };
840
1007
  const queryKey = computeRtsQueryKey(query, resolvedOptions);
841
1008
  const cbKey = `${modelName}.${queryKey}`;
842
1009
  return await new Promise((resolve, reject) => {
@@ -861,7 +1028,10 @@ const runNetworkQuery = async ({
861
1028
  settle(() => reject(error));
862
1029
  return;
863
1030
  }
864
- settle(() => resolve({ data, context }));
1031
+ settle(() => resolve({
1032
+ data,
1033
+ context
1034
+ }));
865
1035
  };
866
1036
  const callbacks = queryCallbacks.get(cbKey) ?? /* @__PURE__ */ new Set();
867
1037
  callbacks.add(callback);
@@ -871,11 +1041,21 @@ const runNetworkQuery = async ({
871
1041
  settle(() => reject(new Error("runNetworkQuery: request timed out")));
872
1042
  }, timeoutMs);
873
1043
  }
874
- sendToServer({ type: "run-query", modelName, queryKey, query, options: resolvedOptions });
1044
+ sendToServer({
1045
+ type: "run-query",
1046
+ modelName,
1047
+ queryKey,
1048
+ query,
1049
+ options: resolvedOptions
1050
+ });
875
1051
  });
876
1052
  };
877
1053
  const sendMessage = (event, payload) => {
878
- sendToServer({ type: "event", event, payload });
1054
+ sendToServer({
1055
+ type: "event",
1056
+ event,
1057
+ payload
1058
+ });
879
1059
  };
880
1060
  const onMessage = (event, callback) => {
881
1061
  const set = messageCallbacks.get(event) ?? /* @__PURE__ */ new Set();
@@ -897,8 +1077,12 @@ const normalizePageInfo = (value) => {
897
1077
  return {
898
1078
  hasNextPage: raw.hasNextPage,
899
1079
  hasPrevPage: raw.hasPrevPage,
900
- ...nextCursor ? { nextCursor } : {},
901
- ...prevCursor ? { prevCursor } : {}
1080
+ ...nextCursor ? {
1081
+ nextCursor
1082
+ } : {},
1083
+ ...prevCursor ? {
1084
+ prevCursor
1085
+ } : {}
902
1086
  };
903
1087
  };
904
1088
  const getDocId = (doc) => {
@@ -965,14 +1149,8 @@ const useQuery = (modelName, query = {}, options = {}) => {
965
1149
  queryKey
966
1150
  });
967
1151
  }
968
- const seedDataRaw = useMemo(
969
- () => enabled && ssrEnabled ? ssrRuntime ? ssrRuntime.getQueryData(modelName, queryKey) : peekHydratedRtsQueryData(modelName, queryKey) : void 0,
970
- [enabled, ssrEnabled, ssrRuntime, modelName, queryKey]
971
- );
972
- const seedPageInfoRaw = useMemo(
973
- () => enabled && ssrEnabled ? ssrRuntime ? ssrRuntime.getQueryPageInfo(modelName, queryKey) : peekHydratedRtsQueryPageInfo(modelName, queryKey) : void 0,
974
- [enabled, ssrEnabled, ssrRuntime, modelName, queryKey]
975
- );
1152
+ const seedDataRaw = useMemo(() => enabled && ssrEnabled ? ssrRuntime ? ssrRuntime.getQueryData(modelName, queryKey) : peekHydratedRtsQueryData(modelName, queryKey) : void 0, [enabled, ssrEnabled, ssrRuntime, modelName, queryKey]);
1153
+ const seedPageInfoRaw = useMemo(() => enabled && ssrEnabled ? ssrRuntime ? ssrRuntime.getQueryPageInfo(modelName, queryKey) : peekHydratedRtsQueryPageInfo(modelName, queryKey) : void 0, [enabled, ssrEnabled, ssrRuntime, modelName, queryKey]);
976
1154
  const hasSeedData = Array.isArray(seedDataRaw);
977
1155
  const seedData = hasSeedData ? seedDataRaw : void 0;
978
1156
  const seedPageInfo = normalizePageInfo(seedPageInfoRaw);
@@ -993,7 +1171,12 @@ const useQuery = (modelName, query = {}, options = {}) => {
993
1171
  }
994
1172
  })();
995
1173
  const [data, setData] = useState(() => isPaginated ? void 0 : seedData);
996
- const [headPage, setHeadPage] = useState(() => isPaginated && seedData ? { nodes: seedData, ...seedPageInfo ? { pageInfo: seedPageInfo } : {} } : null);
1174
+ const [headPage, setHeadPage] = useState(() => isPaginated && seedData ? {
1175
+ nodes: seedData,
1176
+ ...seedPageInfo ? {
1177
+ pageInfo: seedPageInfo
1178
+ } : {}
1179
+ } : null);
997
1180
  const [previousPages, setPreviousPages] = useState([]);
998
1181
  const [nextPages, setNextPages] = useState([]);
999
1182
  const [source, setSource] = useState(() => hasSeedData ? "cache" : void 0);
@@ -1043,7 +1226,9 @@ const useQuery = (modelName, query = {}, options = {}) => {
1043
1226
  if (isPaginated) {
1044
1227
  setHeadPage({
1045
1228
  nodes: nextSeedData,
1046
- ...seedPageInfo ? { pageInfo: seedPageInfo } : {}
1229
+ ...seedPageInfo ? {
1230
+ pageInfo: seedPageInfo
1231
+ } : {}
1047
1232
  });
1048
1233
  setData(void 0);
1049
1234
  } else {
@@ -1060,78 +1245,64 @@ const useQuery = (modelName, query = {}, options = {}) => {
1060
1245
  if (!enabled) return;
1061
1246
  const runInitialNetworkQuery = refreshOnMount || !hasSeedData;
1062
1247
  const runInitialLocalQuery = !hasSeedData && !hasPopulate && !isPaginated;
1063
- const unsubscribe = registerQuery(
1064
- modelName,
1065
- query,
1066
- {
1067
- key,
1068
- projection: options.projection,
1069
- sort: options.sort,
1070
- limit: options.limit,
1071
- populate: options.populate,
1072
- pagination: options.pagination
1073
- },
1074
- (err, result, context) => {
1075
- if (context.source === "cache" && hasNetworkReply.current) return;
1076
- if (context.source === "network") {
1077
- hasNetworkReply.current = true;
1078
- }
1079
- setLoading(false);
1080
- if (err) {
1081
- setError(err);
1082
- return;
1083
- }
1084
- if (!Array.isArray(result)) return;
1085
- if (context.source === "network" && context.isLocal && options.skipLocal && hasFirstReply.current) {
1086
- return;
1087
- }
1088
- hasFirstReply.current = true;
1089
- const networkPageInfo = context.source === "network" ? context.pageInfo : void 0;
1090
- const payloadForHash = isPaginated ? { result, pageInfo: networkPageInfo } : result;
1091
- let nextJson = "";
1092
- try {
1093
- nextJson = JSON.stringify(payloadForHash);
1094
- } catch {
1095
- nextJson = "";
1096
- }
1097
- if (nextJson && nextJson === lastDataJsonRef.current) {
1098
- setSource(context.source);
1099
- return;
1100
- }
1101
- lastDataJsonRef.current = nextJson;
1248
+ const unsubscribe = registerQuery(modelName, query, {
1249
+ key,
1250
+ projection: options.projection,
1251
+ sort: options.sort,
1252
+ limit: options.limit,
1253
+ populate: options.populate,
1254
+ pagination: options.pagination
1255
+ }, (err, result, context) => {
1256
+ if (context.source === "cache" && hasNetworkReply.current) return;
1257
+ if (context.source === "network") {
1258
+ hasNetworkReply.current = true;
1259
+ }
1260
+ setLoading(false);
1261
+ if (err) {
1262
+ setError(err);
1263
+ return;
1264
+ }
1265
+ if (!Array.isArray(result)) return;
1266
+ if (context.source === "network" && context.isLocal && options.skipLocal && hasFirstReply.current) {
1267
+ return;
1268
+ }
1269
+ hasFirstReply.current = true;
1270
+ const networkPageInfo = context.source === "network" ? context.pageInfo : void 0;
1271
+ const payloadForHash = isPaginated ? {
1272
+ result,
1273
+ pageInfo: networkPageInfo
1274
+ } : result;
1275
+ let nextJson = "";
1276
+ try {
1277
+ nextJson = JSON.stringify(payloadForHash);
1278
+ } catch {
1279
+ nextJson = "";
1280
+ }
1281
+ if (nextJson && nextJson === lastDataJsonRef.current) {
1102
1282
  setSource(context.source);
1103
- setError(void 0);
1104
- if (isPaginated) {
1105
- setHeadPage({
1106
- nodes: result,
1107
- ...networkPageInfo ? { pageInfo: networkPageInfo } : {}
1108
- });
1109
- return;
1110
- }
1111
- setData(result);
1112
- },
1113
- {
1114
- runInitialNetworkQuery,
1115
- runInitialLocalQuery
1283
+ return;
1116
1284
  }
1117
- );
1285
+ lastDataJsonRef.current = nextJson;
1286
+ setSource(context.source);
1287
+ setError(void 0);
1288
+ if (isPaginated) {
1289
+ setHeadPage({
1290
+ nodes: result,
1291
+ ...networkPageInfo ? {
1292
+ pageInfo: networkPageInfo
1293
+ } : {}
1294
+ });
1295
+ return;
1296
+ }
1297
+ setData(result);
1298
+ }, {
1299
+ runInitialNetworkQuery,
1300
+ runInitialLocalQuery
1301
+ });
1118
1302
  return () => {
1119
1303
  unsubscribe?.();
1120
1304
  };
1121
- }, [
1122
- enabled,
1123
- modelName,
1124
- queryKey,
1125
- queryJson,
1126
- projectionJson,
1127
- sortJson,
1128
- limitStr,
1129
- populateJson,
1130
- paginationJson,
1131
- hasSeedData,
1132
- refreshOnMount,
1133
- isPaginated
1134
- ]);
1305
+ }, [enabled, modelName, queryKey, queryJson, projectionJson, sortJson, limitStr, populateJson, paginationJson, hasSeedData, refreshOnMount, isPaginated]);
1135
1306
  const effectivePageInfo = useMemo(() => {
1136
1307
  if (!isPaginated) return void 0;
1137
1308
  const firstPageInfo = previousPages.length > 0 ? previousPages[0]?.pageInfo : headPage?.pageInfo;
@@ -1144,8 +1315,12 @@ const useQuery = (modelName, query = {}, options = {}) => {
1144
1315
  return {
1145
1316
  hasPrevPage,
1146
1317
  hasNextPage,
1147
- ...prevCursor ? { prevCursor } : {},
1148
- ...nextCursor ? { nextCursor } : {}
1318
+ ...prevCursor ? {
1319
+ prevCursor
1320
+ } : {},
1321
+ ...nextCursor ? {
1322
+ nextCursor
1323
+ } : {}
1149
1324
  };
1150
1325
  }, [headPage, isPaginated, nextPages, previousPages]);
1151
1326
  const mergedPaginatedData = useMemo(() => {
@@ -1159,8 +1334,8 @@ const useQuery = (modelName, query = {}, options = {}) => {
1159
1334
  const currentHead = headPageRef.current;
1160
1335
  const currentNextPages = nextPagesRef.current;
1161
1336
  const cursor = currentNextPages.length > 0 ? currentNextPages[currentNextPages.length - 1]?.pageInfo?.nextCursor : currentHead?.pageInfo?.nextCursor;
1162
- const hasNextPage = currentNextPages.length > 0 ? Boolean(currentNextPages[currentNextPages.length - 1]?.pageInfo?.hasNextPage) : Boolean(currentHead?.pageInfo?.hasNextPage);
1163
- if (!cursor || !hasNextPage) return false;
1337
+ const hasNextPage_0 = currentNextPages.length > 0 ? Boolean(currentNextPages[currentNextPages.length - 1]?.pageInfo?.hasNextPage) : Boolean(currentHead?.pageInfo?.hasNextPage);
1338
+ if (!cursor || !hasNextPage_0) return false;
1164
1339
  setPagingDirection("next");
1165
1340
  setLoading(true);
1166
1341
  setError(void 0);
@@ -1184,13 +1359,15 @@ const useQuery = (modelName, query = {}, options = {}) => {
1184
1359
  if (!Array.isArray(response.data)) return false;
1185
1360
  const page = {
1186
1361
  nodes: response.data,
1187
- ...response.context.source === "network" && response.context.pageInfo ? { pageInfo: response.context.pageInfo } : {}
1362
+ ...response.context.source === "network" && response.context.pageInfo ? {
1363
+ pageInfo: response.context.pageInfo
1364
+ } : {}
1188
1365
  };
1189
1366
  setSource("network");
1190
1367
  setNextPages((current) => [...current, page]);
1191
1368
  return true;
1192
- } catch (err) {
1193
- setError(err);
1369
+ } catch (err_0) {
1370
+ setError(err_0);
1194
1371
  return false;
1195
1372
  } finally {
1196
1373
  setPagingDirection(null);
@@ -1200,16 +1377,16 @@ const useQuery = (modelName, query = {}, options = {}) => {
1200
1377
  const fetchPrevious = async () => {
1201
1378
  if (!enabled || !isPaginated || !options.pagination) return false;
1202
1379
  if (pagingDirectionRef.current) return false;
1203
- const currentHead = headPageRef.current;
1380
+ const currentHead_0 = headPageRef.current;
1204
1381
  const currentPreviousPages = previousPagesRef.current;
1205
- const cursor = currentPreviousPages.length > 0 ? currentPreviousPages[0]?.pageInfo?.prevCursor : currentHead?.pageInfo?.prevCursor;
1206
- const hasPrevPage = currentPreviousPages.length > 0 ? Boolean(currentPreviousPages[0]?.pageInfo?.hasPrevPage) : Boolean(currentHead?.pageInfo?.hasPrevPage);
1207
- if (!cursor || !hasPrevPage) return false;
1382
+ const cursor_0 = currentPreviousPages.length > 0 ? currentPreviousPages[0]?.pageInfo?.prevCursor : currentHead_0?.pageInfo?.prevCursor;
1383
+ const hasPrevPage_0 = currentPreviousPages.length > 0 ? Boolean(currentPreviousPages[0]?.pageInfo?.hasPrevPage) : Boolean(currentHead_0?.pageInfo?.hasPrevPage);
1384
+ if (!cursor_0 || !hasPrevPage_0) return false;
1208
1385
  setPagingDirection("prev");
1209
1386
  setLoading(true);
1210
1387
  setError(void 0);
1211
1388
  try {
1212
- const response = await runNetworkQuery({
1389
+ const response_0 = await runNetworkQuery({
1213
1390
  modelName,
1214
1391
  query,
1215
1392
  options: {
@@ -1221,20 +1398,22 @@ const useQuery = (modelName, query = {}, options = {}) => {
1221
1398
  pagination: {
1222
1399
  ...options.pagination,
1223
1400
  direction: "prev",
1224
- cursor
1401
+ cursor: cursor_0
1225
1402
  }
1226
1403
  }
1227
1404
  });
1228
- if (!Array.isArray(response.data)) return false;
1229
- const page = {
1230
- nodes: response.data,
1231
- ...response.context.source === "network" && response.context.pageInfo ? { pageInfo: response.context.pageInfo } : {}
1405
+ if (!Array.isArray(response_0.data)) return false;
1406
+ const page_0 = {
1407
+ nodes: response_0.data,
1408
+ ...response_0.context.source === "network" && response_0.context.pageInfo ? {
1409
+ pageInfo: response_0.context.pageInfo
1410
+ } : {}
1232
1411
  };
1233
1412
  setSource("network");
1234
- setPreviousPages((current) => [page, ...current]);
1413
+ setPreviousPages((current_0) => [page_0, ...current_0]);
1235
1414
  return true;
1236
- } catch (err) {
1237
- setError(err);
1415
+ } catch (err_1) {
1416
+ setError(err_1);
1238
1417
  return false;
1239
1418
  } finally {
1240
1419
  setPagingDirection(null);
@@ -1246,29 +1425,16 @@ const useQuery = (modelName, query = {}, options = {}) => {
1246
1425
  setPreviousPages([]);
1247
1426
  setNextPages([]);
1248
1427
  };
1249
- return useMemo(
1250
- () => ({
1251
- data: isPaginated ? mergedPaginatedData : data,
1252
- pageInfo: effectivePageInfo,
1253
- source,
1254
- error,
1255
- loading,
1256
- fetchNext,
1257
- fetchPrevious,
1258
- resetPagination
1259
- }),
1260
- [
1261
- data,
1262
- effectivePageInfo,
1263
- error,
1264
- fetchNext,
1265
- fetchPrevious,
1266
- isPaginated,
1267
- loading,
1268
- mergedPaginatedData,
1269
- source
1270
- ]
1271
- );
1428
+ return useMemo(() => ({
1429
+ data: isPaginated ? mergedPaginatedData : data,
1430
+ pageInfo: effectivePageInfo,
1431
+ source,
1432
+ error,
1433
+ loading,
1434
+ fetchNext,
1435
+ fetchPrevious,
1436
+ resetPagination
1437
+ }), [data, effectivePageInfo, error, fetchNext, fetchPrevious, isPaginated, loading, mergedPaginatedData, source]);
1272
1438
  };
1273
1439
  export {
1274
1440
  RtsSsrRuntimeProvider as R,
@@ -1296,4 +1462,4 @@ export {
1296
1462
  updateDocs as u,
1297
1463
  useQuery as v
1298
1464
  };
1299
- //# sourceMappingURL=useQuery-ZWQYk25K.js.map
1465
+ //# sourceMappingURL=useQuery-0Z8QorHN.js.map