@powerhousedao/reactor-browser 6.2.3-dev.22 → 6.2.3-dev.24

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 (32) hide show
  1. package/dist/{attachment-service-C14mVTk_.d.ts → attachment-service-cIdRZcTa.d.ts} +36 -9
  2. package/dist/attachment-service-cIdRZcTa.d.ts.map +1 -0
  3. package/dist/{document-by-id-iXB59Ge-.js → document-by-id-DgdUGMVm.js} +163 -35
  4. package/dist/document-by-id-DgdUGMVm.js.map +1 -0
  5. package/dist/{document-model-modules-BSwKnUR_.js → document-model-modules-D1ZEoGjN.js} +21 -9
  6. package/dist/document-model-modules-D1ZEoGjN.js.map +1 -0
  7. package/dist/{document-operations-BjZmu1JC.js → document-operations-DhrcpXMf.js} +42 -26
  8. package/dist/document-operations-DhrcpXMf.js.map +1 -0
  9. package/dist/{global-D4e836Hk.d.ts → global-BGoyNc1s.d.ts} +10 -3
  10. package/dist/global-BGoyNc1s.d.ts.map +1 -0
  11. package/dist/{index-BvJaeywJ.d.ts → index-DrgDweMA.d.ts} +2 -2
  12. package/dist/{index-BvJaeywJ.d.ts.map → index-DrgDweMA.d.ts.map} +1 -1
  13. package/dist/index.d.ts +20 -6
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +73 -20
  16. package/dist/index.js.map +1 -1
  17. package/dist/src/ai/index.d.ts +1 -1
  18. package/dist/src/ai/index.js +2 -2
  19. package/dist/src/analytics/index.js +1 -1
  20. package/dist/src/graphql-client/entry.d.ts +2 -2
  21. package/dist/src/graphql-client/entry.js +3 -3
  22. package/dist/src/renown/index.d.ts +1 -1
  23. package/dist/src/rpc/index.d.ts +1 -1
  24. package/dist/src/rpc/index.js +1 -1
  25. package/dist/{switchboard-Yt6ASJRx.js → switchboard-BEiFkv9K.js} +3 -3
  26. package/dist/{switchboard-Yt6ASJRx.js.map → switchboard-BEiFkv9K.js.map} +1 -1
  27. package/package.json +11 -11
  28. package/dist/attachment-service-C14mVTk_.d.ts.map +0 -1
  29. package/dist/document-by-id-iXB59Ge-.js.map +0 -1
  30. package/dist/document-model-modules-BSwKnUR_.js.map +0 -1
  31. package/dist/document-operations-BjZmu1JC.js.map +0 -1
  32. package/dist/global-D4e836Hk.d.ts.map +0 -1
@@ -1,10 +1,10 @@
1
- import { a as PHGlobal$1, b as IPackagesListener, ct as OperationsCacheEntry, d as UsePHGlobalValue$1, lt as PromiseState, ot as IDocumentCache, rt as IReactorBrowserClient$1, st as IOperationCache, u as SetPHGlobalValue$1, ut as PromiseWithState, v as IPackageListerUnsubscribe, x as PackageManagerInstallResult, y as IPackageManager } from "./global-D4e836Hk.js";
1
+ import { a as PHGlobal$1, at as DocumentRefetchState, b as IPackagesListener, ct as IOperationCache, d as UsePHGlobalValue$1, dt as PromiseWithState, lt as OperationsCacheEntry, rt as IReactorBrowserClient$1, st as IDocumentCache, u as SetPHGlobalValue$1, ut as PromiseState, v as IPackageListerUnsubscribe, x as PackageManagerInstallResult, y as IPackageManager } from "./global-BGoyNc1s.js";
2
2
  import { t as PGlite } from "./pglite-CntadC_p-9NDG14dS.js";
3
3
  import { A as ViewFilterInput, C as GetDocumentQuery, D as PropagationMode$1, E as PhDocumentFieldsFragment, O as Scalars, S as GetDocumentOperationsQuery, b as DocumentChangesSubscription, c as ReactorGraphQLClient, g as ActionInput, k as SdkFunctionWrapper } from "./types-N3Jy6Nry.js";
4
4
  import { Action, DocumentModelLib, DocumentModelModule, Operation, PHDocument } from "document-model";
5
- import { Action as Action$1, DocumentModelModule as DocumentModelModule$1, DocumentOperations, ISigner, Operation as Operation$1, PHBaseState, PHDocument as PHDocument$1, PHDocumentHeader } from "@powerhousedao/shared/document-model";
6
5
  import * as _powerhousedao_reactor0 from "@powerhousedao/reactor";
7
6
  import { Database, DocumentChangeEvent, DocumentModelSource, IDocumentModelRegistry, ISyncManager, OperationFilter, PagedResults, PagingOptions, PropagationMode, SearchFilter, ViewFilter } from "@powerhousedao/reactor";
7
+ import { Action as Action$1, ActionSigningTarget, DocumentModelModule as DocumentModelModule$1, DocumentOperations, ISigner, Operation as Operation$1, PHBaseState, PHDocument as PHDocument$1, PHDocumentHeader } from "@powerhousedao/shared/document-model";
8
8
  import { ReactNode } from "react";
9
9
  import { GraphQLClient, Variables } from "graphql-request";
10
10
  import * as graphql from "graphql";
@@ -15,6 +15,10 @@ import { Kysely } from "kysely";
15
15
  import { AddPHGlobalEventHandler, BrowserReactorClientModule, IReactorBrowserClient, SetPHGlobalValue, UsePHGlobalValue, WorkerReactorClientModule } from "@powerhousedao/reactor-browser";
16
16
  import { RegistryPackageSource } from "@powerhousedao/shared";
17
17
 
18
+ //#region src/document-refetcher.d.ts
19
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
20
+ declare const IDLE_REFETCH_STATE: DocumentRefetchState;
21
+ //#endregion
18
22
  //#region src/document-cache.d.ts
19
23
  declare function addPromiseState<T>(promise: Promise<T>): PromiseWithState<T>;
20
24
  declare function readPromiseState<T>(promise: Promise<T> | PromiseWithState<T>): PromiseState<T>;
@@ -35,6 +39,7 @@ declare class DocumentCache implements IDocumentCache, IOperationCache {
35
39
  private documents;
36
40
  private batchPromises;
37
41
  private listeners;
42
+ private refetcher;
38
43
  /**
39
44
  * Cache keys that fetched a document under a name other than its id --
40
45
  * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
@@ -53,12 +58,14 @@ declare class DocumentCache implements IDocumentCache, IOperationCache {
53
58
  private handleDocumentChange;
54
59
  private handleDocumentDeleted;
55
60
  private handleDocumentUpdated;
61
+ private notifyListeners;
56
62
  /** The id an event dispatches by, plus every alias the document is cached under. */
57
63
  private cacheKeysFor;
58
64
  /** Records that `key` cached the document change events know as `header.id`. */
59
65
  private recordAlias;
60
66
  private invalidateBatchesContaining;
61
67
  get(id: string, refetch?: boolean): Promise<PHDocument$1>;
68
+ getRefetchState(id: string): DocumentRefetchState;
62
69
  getBatch(ids: string[]): Promise<PHDocument$1[]>;
63
70
  subscribe(id: string | string[], callback: () => void): () => void;
64
71
  getOperationsState(documentId: string, scope: string): OperationsCacheEntry;
@@ -801,12 +808,12 @@ type MutateDocumentWithOperationsResult = {
801
808
  */
802
809
  declare function stampAction(action: Action$1, document: PHDocument$1, revision?: number): Action$1;
803
810
  /**
804
- * Signs a stamped action, preserving any signatures it already carries.
805
- *
806
- * The signer reads `context.prevOpHash` off the action, so this must run after
807
- * {@link stampAction}.
811
+ * Signs a stamped action for `target`, keeping any signatures it already
812
+ * carries. The signer reads `context.prevOpHash`, so this runs after
813
+ * {@link stampAction}. A v2 tuple covers the signer's identity, so the context
814
+ * takes the signer's user and app even when the action named others.
808
815
  */
809
- declare function signStampedAction(action: Action$1, signer: ISigner, signal?: AbortSignal): Promise<Action$1>;
816
+ declare function signStampedAction(action: Action$1, signer: ISigner, target: ActionSigningTarget, signal?: AbortSignal): Promise<Action$1>;
810
817
  /**
811
818
  * Stamps and signs a batch of actions against one document snapshot, so every
812
819
  * action carries the head its predecessor will leave behind.
@@ -978,6 +985,8 @@ declare function useDocument(id: string | null | undefined): PHDocument$1 | unde
978
985
  * - isPending: Whether the document is currently loading
979
986
  * - error: Any error that occurred during loading (e.g., document not found)
980
987
  * - reload: Function to force a refetch, or undefined when no id is supplied
988
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
989
+ * - refetchError: The last refetch failure that kept the loaded document
981
990
  */
982
991
  declare function useDocumentSafe(id: string | null | undefined): {
983
992
  readonly status: "initial";
@@ -985,20 +994,28 @@ declare function useDocumentSafe(id: string | null | undefined): {
985
994
  readonly error: undefined;
986
995
  readonly data: undefined;
987
996
  readonly reload: undefined;
997
+ readonly isRefetching: false;
998
+ readonly refetchError: undefined;
988
999
  } | {
989
1000
  readonly reload: () => Promise<PHDocument$1>;
1001
+ readonly isRefetching: boolean;
1002
+ readonly refetchError: unknown;
990
1003
  readonly status: "pending";
991
1004
  readonly isPending: true;
992
1005
  readonly error: undefined;
993
1006
  readonly data: undefined;
994
1007
  } | {
995
1008
  readonly reload: () => Promise<PHDocument$1>;
1009
+ readonly isRefetching: boolean;
1010
+ readonly refetchError: unknown;
996
1011
  readonly status: "success";
997
1012
  readonly isPending: false;
998
1013
  readonly error: undefined;
999
1014
  readonly data: PHDocument$1;
1000
1015
  } | {
1001
1016
  readonly reload: () => Promise<PHDocument$1>;
1017
+ readonly isRefetching: boolean;
1018
+ readonly refetchError: unknown;
1002
1019
  readonly status: "error";
1003
1020
  readonly isPending: false;
1004
1021
  readonly error: unknown;
@@ -1037,6 +1054,8 @@ declare function useGetDocuments(): (ids: string[]) => Promise<PHDocument$1[]>;
1037
1054
  * - isPending: Boolean indicating if the document is currently loading
1038
1055
  * - error: Any error that occurred during loading
1039
1056
  * - reload: Function to force reload the document from cache
1057
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1058
+ * - refetchError: The last refetch failure that kept the loaded document
1040
1059
  */
1041
1060
  declare function useGetDocumentAsync(id: string | null | undefined): {
1042
1061
  readonly status: "initial";
@@ -1044,20 +1063,28 @@ declare function useGetDocumentAsync(id: string | null | undefined): {
1044
1063
  readonly isPending: false;
1045
1064
  readonly error: undefined;
1046
1065
  readonly reload: undefined;
1066
+ readonly isRefetching: false;
1067
+ readonly refetchError: undefined;
1047
1068
  } | {
1048
1069
  readonly reload: () => Promise<PHDocument$1>;
1070
+ readonly isRefetching: boolean;
1071
+ readonly refetchError: unknown;
1049
1072
  readonly status: "pending";
1050
1073
  readonly isPending: true;
1051
1074
  readonly error: undefined;
1052
1075
  readonly data: undefined;
1053
1076
  } | {
1054
1077
  readonly reload: () => Promise<PHDocument$1>;
1078
+ readonly isRefetching: boolean;
1079
+ readonly refetchError: unknown;
1055
1080
  readonly status: "success";
1056
1081
  readonly isPending: false;
1057
1082
  readonly error: undefined;
1058
1083
  readonly data: PHDocument$1;
1059
1084
  } | {
1060
1085
  readonly reload: () => Promise<PHDocument$1>;
1086
+ readonly isRefetching: boolean;
1087
+ readonly refetchError: unknown;
1061
1088
  readonly status: "error";
1062
1089
  readonly isPending: false;
1063
1090
  readonly error: unknown;
@@ -1165,5 +1192,5 @@ declare const setAttachmentService: SetPHGlobalValue<IAttachmentService>;
1165
1192
  /** Registers the attachmentService window event handler */
1166
1193
  declare const addAttachmentServiceEventHandler: AddPHGlobalEventHandler;
1167
1194
  //#endregion
1168
- export { useSwitchboardClient as $, useGetDocument as A, RemoteControllerOptions as At, StaticPackageManager as B, isOperationCache as Bt, useSyncList as C, GetDocumentWithOperationsResult as Ct, useDocumentCache as D, MergeHandler as Dt, useDocument as E, IRemoteController as Et, DocumentChangesSubscriptionOptions as F, SyncStatus$1 as Ft, stampAction as G, resolveDocumentModelModule as H, isAuthRefusalClose as I, TrackedAction as It, MutateDocumentWithOperationsVariables as J, MutateDocumentWithOperationsDocument as K, makeAuthConnectionParams as L, DocumentCache as Lt, useGetDocuments as M, RemoteDocumentData as Mt, ConnectionParams as N, RemoteOperation as Nt, useDocumentSafe as O, PushResult as Ot, DocumentChangesEventPayload as P, RemoteOperationResultPage as Pt, ensurePHEventHandlers as Q, startDocumentChangesSubscription as R, IDLE_OPERATIONS_ENTRY as Rt, useSync as S, GetDocumentResult as St, setDocumentCache as T, IRemoteClient as Tt, prepareSignedActions as U, packageFromDocumentModels as V, readPromiseState as Vt, signStampedAction as W, GraphQLReactorProvider as X, ReactorOperationFieldsFragmentDoc as Y, GraphQLReactorProviderProps as Z, useDatabase as _, phDocumentFromMutation as _t, DocumentOperationsState as a, SubgraphSdkFactory as at, useReactorClient as b, ConflictStrategy as bt, useDocumentModelModuleById as c, describeGraphQLDocument as ct, UseDispatchResult as d, ambientRenownTokenProvider as dt, GraphQLReactorClient as et, useDispatch as f, makeAuthMiddleware as ft, setReactorClientModule as g, phDocumentFromGetDocument as gt, setReactorClient as h, RevisionsListSelection as ht, DocumentOperationsResult as i, GraphQLRequestOptions as it, useGetDocumentAsync as j, RemoteDocumentChangeEvent as jt, useDocuments as k, RemoteControllerGraphQLClient as kt, useDocumentModelModules as l, subgraphUrlFromGraphqlUrl as lt, addReactorClientModuleEventHandler as m, GetDocumentQueryResult as mt, setAttachmentService as n, isGraphQLReactorClient as nt, UseDocumentOperationsOptions as o, SubgraphSdkRegistry as ot, addReactorClientEventHandler as p, GetDocumentQueryFields as pt, MutateDocumentWithOperationsResult as q, useAttachmentService as r, viewFilterInputFromViewFilter as rt, useDocumentOperations as s, TypedGraphQLDocument as st, addAttachmentServiceEventHandler as t, GraphQLReactorClientOptions as tt, DispatchFn as u, BearerTokenProvider as ut, useModelRegistry as v, revisionMapFromRevisionsList as vt, addDocumentCacheEventHandler as w, GetOperationsResult as wt, useReactorClientModule as x, DocumentChangeListener as xt, usePGlite as y, ConflictInfo as yt, subscriptionsUrlFromGraphqlUrl as z, addPromiseState as zt };
1169
- //# sourceMappingURL=attachment-service-C14mVTk_.d.ts.map
1195
+ export { useSwitchboardClient as $, useGetDocument as A, RemoteControllerOptions as At, StaticPackageManager as B, isOperationCache as Bt, useSyncList as C, GetDocumentWithOperationsResult as Ct, useDocumentCache as D, MergeHandler as Dt, useDocument as E, IRemoteController as Et, DocumentChangesSubscriptionOptions as F, SyncStatus$1 as Ft, stampAction as G, resolveDocumentModelModule as H, IDLE_REFETCH_STATE as Ht, isAuthRefusalClose as I, TrackedAction as It, MutateDocumentWithOperationsVariables as J, MutateDocumentWithOperationsDocument as K, makeAuthConnectionParams as L, DocumentCache as Lt, useGetDocuments as M, RemoteDocumentData as Mt, ConnectionParams as N, RemoteOperation as Nt, useDocumentSafe as O, PushResult as Ot, DocumentChangesEventPayload as P, RemoteOperationResultPage as Pt, ensurePHEventHandlers as Q, startDocumentChangesSubscription as R, IDLE_OPERATIONS_ENTRY as Rt, useSync as S, GetDocumentResult as St, setDocumentCache as T, IRemoteClient as Tt, prepareSignedActions as U, packageFromDocumentModels as V, readPromiseState as Vt, signStampedAction as W, GraphQLReactorProvider as X, ReactorOperationFieldsFragmentDoc as Y, GraphQLReactorProviderProps as Z, useDatabase as _, phDocumentFromMutation as _t, DocumentOperationsState as a, SubgraphSdkFactory as at, useReactorClient as b, ConflictStrategy as bt, useDocumentModelModuleById as c, describeGraphQLDocument as ct, UseDispatchResult as d, ambientRenownTokenProvider as dt, GraphQLReactorClient as et, useDispatch as f, makeAuthMiddleware as ft, setReactorClientModule as g, phDocumentFromGetDocument as gt, setReactorClient as h, RevisionsListSelection as ht, DocumentOperationsResult as i, GraphQLRequestOptions as it, useGetDocumentAsync as j, RemoteDocumentChangeEvent as jt, useDocuments as k, RemoteControllerGraphQLClient as kt, useDocumentModelModules as l, subgraphUrlFromGraphqlUrl as lt, addReactorClientModuleEventHandler as m, GetDocumentQueryResult as mt, setAttachmentService as n, isGraphQLReactorClient as nt, UseDocumentOperationsOptions as o, SubgraphSdkRegistry as ot, addReactorClientEventHandler as p, GetDocumentQueryFields as pt, MutateDocumentWithOperationsResult as q, useAttachmentService as r, viewFilterInputFromViewFilter as rt, useDocumentOperations as s, TypedGraphQLDocument as st, addAttachmentServiceEventHandler as t, GraphQLReactorClientOptions as tt, DispatchFn as u, BearerTokenProvider as ut, useModelRegistry as v, revisionMapFromRevisionsList as vt, addDocumentCacheEventHandler as w, GetOperationsResult as wt, useReactorClientModule as x, DocumentChangeListener as xt, usePGlite as y, ConflictInfo as yt, subscriptionsUrlFromGraphqlUrl as z, addPromiseState as zt };
1196
+ //# sourceMappingURL=attachment-service-cIdRZcTa.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachment-service-cIdRZcTa.d.ts","names":[],"sources":["../src/document-refetcher.ts","../src/document-cache.ts","../src/remote-controller/types.ts","../src/graphql-client/adapter.ts","../src/graphql-client/auth.ts","../src/graphql-client/subgraph.ts","../src/graphql-client/graphql-reactor-client.ts","../src/graphql-client/graphql-reactor-provider.tsx","../src/graphql-client/operations.ts","../src/graphql-client/signing.ts","../src/graphql-client/static-package-manager.ts","../src/graphql-client/subscriptions.ts","../src/hooks/document-cache.ts","../src/hooks/reactor.ts","../src/hooks/dispatch.ts","../src/hooks/document-model-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AkB,SAAA,EAAW,OAAA;;;iBCpBhB,uBAAA,CAAA,GAA2B,mBAAA;;;;;;;;;iBAuB3B,0BAAA,CACd,EAAA,6BACA,OAAA,YACC,mBAAA;;;KCvBS,4BAAA;;;;;;EAMV,KAAA;EAEA,OAAA;AAAA;;KAIU,wBAAA;kEAEV,UAAA,WAAqB,WAAA;EAErB,SAAA;EAEA,KAAA,EAAO,KAAA,chBZP;EgBcA,WAAA,WhBjB+B;EgBmB/B,UAAA;EAEA,aAAA;EAEA,OAAA;AAAA;;;;;KAaU,uBAAA;EACV,gBAAA,EAAkB,WAAA;EAClB,eAAA,EAAiB,WAAA;EACjB,SAAA;EACA,KAAA,EAAO,KAAA;EACP,OAAA;AAAA;;iBAqFc,qBAAA,CACd,UAAA,8BACC,uBAAA;;;Af9FH;;;;;;;;;;;;;;iBe+GgB,qBAAA,CACd,UAAA,6BACA,KAAA,UACA,OAAA,GAAU,4BAAA,GACT,wBAAA;;;;cClJU,oBAAA,EAAsB,gBAAA,CAAiB,kBAAA;;cAIvC,oBAAA,EAAsB,gBAAA,CAAiB,kBAAA;;cAIvC,gCAAA,EAAkC,uBAAA"}
@@ -1,6 +1,5 @@
1
1
  import { t as makePHEventFunctions } from "./make-ph-event-functions-DBq3iWYn.js";
2
2
  import { logger } from "document-model";
3
- import { buildSignedAction } from "@powerhousedao/shared/document-model";
4
3
  import { use, useCallback, useEffect, useReducer, useSyncExternalStore } from "react";
5
4
  //#region src/actions/queue.ts
6
5
  async function queueActions(document, actionOrActions) {
@@ -49,16 +48,6 @@ async function uploadOperations(documentId, allOperations, pushOperations, optio
49
48
  }
50
49
  //#endregion
51
50
  //#region src/actions/sign.ts
52
- async function signAction(action, document) {
53
- const renown = window.ph?.renown;
54
- if (!renown?.user) return action;
55
- if (!action.context?.signer) return action;
56
- const reactorClient = window.ph?.reactorClientModule?.client;
57
- if (!reactorClient) return action;
58
- const reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;
59
- const actionSigner = action.context.signer;
60
- return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
61
- }
62
51
  function addActionContext(action) {
63
52
  const renown = window.ph?.renown;
64
53
  if (!renown?.user) return action;
@@ -78,7 +67,7 @@ function addActionContext(action) {
78
67
  ...action
79
68
  };
80
69
  }
81
- async function makeSignedActionWithContext(action, document) {
70
+ function makeSignedActionWithContext(action, document) {
82
71
  if (!action) {
83
72
  logger.error("No action found");
84
73
  return;
@@ -87,15 +76,14 @@ async function makeSignedActionWithContext(action, document) {
87
76
  logger.error("No document found");
88
77
  return;
89
78
  }
90
- return addActionContext(await signAction(action, document));
79
+ return addActionContext(action);
91
80
  }
92
- async function makeSignedActionsWithContext(actionOrActions, document) {
81
+ function makeSignedActionsWithContext(actionOrActions, document) {
93
82
  if (!actionOrActions) {
94
83
  logger.error("No actions found");
95
84
  return;
96
85
  }
97
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
98
- return (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);
86
+ return (Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]).map((action) => makeSignedActionWithContext(action, document)).filter((a) => a !== void 0);
99
87
  }
100
88
  //#endregion
101
89
  //#region src/actions/dispatch.ts
@@ -122,7 +110,7 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
122
110
  logger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);
123
111
  return;
124
112
  }
125
- const signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);
113
+ const signedActionsWithContext = makeSignedActionsWithContext(actionOrActions, document);
126
114
  if (!signedActionsWithContext) {
127
115
  logger.error("No signed actions with context found");
128
116
  return;
@@ -135,6 +123,116 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
135
123
  if (onSuccess && result) onSuccess(result);
136
124
  return result;
137
125
  }
126
+ //#endregion
127
+ //#region src/document-refetcher.ts
128
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
129
+ const IDLE_REFETCH_STATE = Object.freeze({
130
+ isRefetching: false,
131
+ error: void 0
132
+ });
133
+ function fulfilledPromise(value) {
134
+ const promise = Promise.resolve(value);
135
+ promise.status = "fulfilled";
136
+ promise.value = value;
137
+ return promise;
138
+ }
139
+ function rejectedPromise(reason) {
140
+ const promise = Promise.reject(reason);
141
+ promise.status = "rejected";
142
+ promise.reason = reason;
143
+ promise.catch(() => void 0);
144
+ return promise;
145
+ }
146
+ const MISSING_DOCUMENT_ERRORS = ["DocumentNotFoundError", "DocumentDeletedError"];
147
+ function isMissingDocumentError(error) {
148
+ if (!(error instanceof Error)) return false;
149
+ return MISSING_DOCUMENT_ERRORS.includes(error.name) || error.message.startsWith("Document not found");
150
+ }
151
+ const noop = () => void 0;
152
+ /** Background refetch of loaded documents: readers keep the loaded promise until it settles. */
153
+ var DocumentRefetcher = class {
154
+ refetches = /* @__PURE__ */ new Map();
155
+ states = /* @__PURE__ */ new Map();
156
+ constructor(host) {
157
+ this.host = host;
158
+ }
159
+ getState(id) {
160
+ return this.states.get(id) ?? IDLE_REFETCH_STATE;
161
+ }
162
+ /** Serializes refetches per key: one runs, later requests share one queued run. */
163
+ refetch(id) {
164
+ let entry = this.refetches.get(id);
165
+ if (!entry) {
166
+ entry = {
167
+ running: void 0,
168
+ queued: void 0
169
+ };
170
+ this.refetches.set(id, entry);
171
+ const current = this.host.documents.get(id);
172
+ if (current?.status !== "pending") return this.start(id, entry);
173
+ entry.running = current;
174
+ }
175
+ const inFlight = entry;
176
+ inFlight.queued ??= (inFlight.running ?? Promise.resolve()).then(noop, noop).then(() => this.start(id, inFlight));
177
+ return inFlight.queued;
178
+ }
179
+ /** Stops any refetch of `id` from writing back, e.g. on deletion. */
180
+ forget(id) {
181
+ this.refetches.delete(id);
182
+ this.states.delete(id);
183
+ }
184
+ clear() {
185
+ this.refetches.clear();
186
+ this.states.clear();
187
+ }
188
+ start(id, entry) {
189
+ entry.queued = void 0;
190
+ entry.running = this.run(id, entry);
191
+ return entry.running;
192
+ }
193
+ async run(id, entry) {
194
+ const isCurrent = () => this.refetches.get(id) === entry;
195
+ if (!isCurrent()) return this.host.fetch(id);
196
+ if (this.setState(id, {
197
+ isRefetching: true,
198
+ error: this.getState(id).error
199
+ })) this.host.notify(id);
200
+ try {
201
+ const document = await this.host.fetch(id);
202
+ if (isCurrent()) {
203
+ this.host.onFetched?.(id, document);
204
+ this.host.documents.set(id, fulfilledPromise(document));
205
+ this.finish(id, entry, void 0);
206
+ }
207
+ return document;
208
+ } catch (error) {
209
+ if (isCurrent()) if (isMissingDocumentError(error)) {
210
+ this.host.documents.set(id, rejectedPromise(error));
211
+ this.finish(id, entry, void 0);
212
+ } else {
213
+ console.warn("[DocumentCache] Refetch failed; keeping the loaded document:", error);
214
+ this.finish(id, entry, error);
215
+ }
216
+ throw error;
217
+ }
218
+ }
219
+ finish(id, entry, error) {
220
+ if (!entry.queued) this.refetches.delete(id);
221
+ this.setState(id, {
222
+ isRefetching: entry.queued !== void 0,
223
+ error
224
+ });
225
+ this.host.notify(id);
226
+ }
227
+ /** Returns whether the snapshot changed; the caller notifies. */
228
+ setState(id, state) {
229
+ const current = this.getState(id);
230
+ if (current.isRefetching === state.isRefetching && current.error === state.error) return false;
231
+ if (!state.isRefetching && state.error === void 0) this.states.delete(id);
232
+ else this.states.set(id, Object.freeze({ ...state }));
233
+ return true;
234
+ }
235
+ };
138
236
  /**
139
237
  * The reactor's `DocumentChangeType` members, typed as the enum so they can be
140
238
  * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
@@ -236,6 +334,14 @@ var DocumentCache = class {
236
334
  documents = /* @__PURE__ */ new Map();
237
335
  batchPromises = /* @__PURE__ */ new Map();
238
336
  listeners = /* @__PURE__ */ new Map();
337
+ refetcher = new DocumentRefetcher({
338
+ documents: this.documents,
339
+ fetch: (id) => this.client.get(id),
340
+ notify: (id) => this.notifyListeners(id),
341
+ onFetched: (id, document) => {
342
+ if (document.header.id !== id) this.recordAlias(document.header.id, id);
343
+ }
344
+ });
239
345
  /**
240
346
  * Cache keys that fetched a document under a name other than its id --
241
347
  * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
@@ -274,6 +380,7 @@ var DocumentCache = class {
274
380
  for (const key of this.cacheKeysFor(documentId)) {
275
381
  const listeners = this.listeners.get(key);
276
382
  this.documents.delete(key);
383
+ this.refetcher.forget(key);
277
384
  this.invalidateBatchesContaining(key);
278
385
  if (listeners) listeners.forEach((listener) => listener());
279
386
  this.listeners.delete(key);
@@ -281,12 +388,11 @@ var DocumentCache = class {
281
388
  this.aliasKeys.delete(documentId);
282
389
  }
283
390
  async handleDocumentUpdated(documentId) {
284
- for (const key of this.cacheKeysFor(documentId)) {
285
- if (!this.documents.has(key)) continue;
286
- await this.get(key, true);
287
- const listeners = this.listeners.get(key);
288
- if (listeners) listeners.forEach((listener) => listener());
289
- }
391
+ const refetches = this.cacheKeysFor(documentId).filter((key) => this.documents.has(key)).map((key) => this.get(key, true));
392
+ await Promise.all(refetches);
393
+ }
394
+ notifyListeners(key) {
395
+ for (const listener of this.listeners.get(key) ?? []) listener();
290
396
  }
291
397
  /** The id an event dispatches by, plus every alias the document is cached under. */
292
398
  cacheKeysFor(documentId) {
@@ -303,10 +409,9 @@ var DocumentCache = class {
303
409
  }
304
410
  get(id, refetch) {
305
411
  const currentData = this.documents.get(id);
306
- if (currentData) {
307
- if (currentData.status === "pending") return currentData;
308
- if (!refetch) return currentData;
309
- }
412
+ if (currentData && !refetch) return currentData;
413
+ if (currentData && currentData.status !== "rejected") return this.refetcher.refetch(id);
414
+ this.refetcher.forget(id);
310
415
  const documentPromise = this.client.get(id);
311
416
  documentPromise.then((doc) => {
312
417
  if (doc.header.id !== id) this.recordAlias(doc.header.id, id);
@@ -314,6 +419,9 @@ var DocumentCache = class {
314
419
  this.documents.set(id, addPromiseState(documentPromise));
315
420
  return documentPromise;
316
421
  }
422
+ getRefetchState(id) {
423
+ return this.refetcher.getState(id);
424
+ }
317
425
  getBatch(ids) {
318
426
  const key = ids.join(",");
319
427
  const cached = this.batchPromises.get(key);
@@ -530,6 +638,7 @@ var DocumentCache = class {
530
638
  for (const requests of this.operationRequests.values()) for (const request of requests.values()) request.controller.abort();
531
639
  this.operationRequests.clear();
532
640
  this.operationEntries.clear();
641
+ this.refetcher.clear();
533
642
  this.operationListeners.clear();
534
643
  }
535
644
  };
@@ -597,10 +706,14 @@ function useDocument(id) {
597
706
  * - isPending: Whether the document is currently loading
598
707
  * - error: Any error that occurred during loading (e.g., document not found)
599
708
  * - reload: Function to force a refetch, or undefined when no id is supplied
709
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
710
+ * - refetchError: The last refetch failure that kept the loaded document
600
711
  */
601
712
  function useDocumentSafe(id) {
602
713
  const documentCache = useDocumentCache();
603
- const promise = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);
714
+ const subscribe = (cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {};
715
+ const promise = useSyncExternalStore(subscribe, () => id ? documentCache?.get(id) : void 0);
716
+ const refetch = useSyncExternalStore(subscribe, () => readRefetchState(documentCache, id));
604
717
  const [, bumpOnSettle] = useReducer((count) => count + 1, 0);
605
718
  const pendingPromise = promise && readPromiseState(promise).status === "pending" ? promise : null;
606
719
  useEffect(() => {
@@ -619,13 +732,20 @@ function useDocumentSafe(id) {
619
732
  isPending: false,
620
733
  error: void 0,
621
734
  data: void 0,
622
- reload: void 0
735
+ reload: void 0,
736
+ isRefetching: false,
737
+ refetchError: void 0
623
738
  };
624
739
  return {
625
740
  ...getDocumentQueryState(promise),
626
- reload: () => documentCache.get(id, true)
741
+ reload: () => documentCache.get(id, true),
742
+ isRefetching: refetch.isRefetching,
743
+ refetchError: refetch.error
627
744
  };
628
745
  }
746
+ function readRefetchState(documentCache, id) {
747
+ return id && documentCache?.getRefetchState?.(id) || IDLE_REFETCH_STATE;
748
+ }
629
749
  /**
630
750
  * Retrieves multiple documents from the reactor using React Suspense.
631
751
  * This hook will suspend rendering while any of the documents are loading.
@@ -675,6 +795,8 @@ function useGetDocuments() {
675
795
  * - isPending: Boolean indicating if the document is currently loading
676
796
  * - error: Any error that occurred during loading
677
797
  * - reload: Function to force reload the document from cache
798
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
799
+ * - refetchError: The last refetch failure that kept the loaded document
678
800
  */
679
801
  function useGetDocumentAsync(id) {
680
802
  const documentCache = useDocumentCache();
@@ -683,11 +805,17 @@ function useGetDocumentAsync(id) {
683
805
  data: void 0,
684
806
  isPending: false,
685
807
  error: void 0,
686
- reload: void 0
808
+ reload: void 0,
809
+ isRefetching: false,
810
+ refetchError: void 0
687
811
  };
812
+ const state = getDocumentQueryState(documentCache.get(id));
813
+ const refetch = readRefetchState(documentCache, id);
688
814
  return {
689
- ...getDocumentQueryState(documentCache.get(id)),
690
- reload: () => documentCache.get(id, true)
815
+ ...state,
816
+ reload: () => documentCache.get(id, true),
817
+ isRefetching: refetch.isRefetching,
818
+ refetchError: refetch.error
691
819
  };
692
820
  }
693
821
  //#endregion
@@ -718,6 +846,6 @@ function useDocumentsByIds(ids) {
718
846
  return useDocuments(ids);
719
847
  }
720
848
  //#endregion
721
- export { queueOperations as C, queueActions as S, readPromiseState as _, setDocumentCache as a, isDuplicateModuleError as b, useDocumentSafe as c, useGetDocumentAsync as d, useGetDocuments as f, isOperationCache as g, addPromiseState as h, addDocumentCacheEventHandler as i, useDocuments as l, IDLE_OPERATIONS_ENTRY as m, useDocumentsByIds as n, useDocument as o, DocumentCache as p, useDispatch as r, useDocumentCache as s, useDocumentById as t, useGetDocument as u, DOCUMENT_CHANGE_TYPE as v, uploadOperations as w, dispatchActions as x, isDuplicateManifestError as y };
849
+ export { dispatchActions as C, uploadOperations as E, IDLE_REFETCH_STATE as S, queueOperations as T, readPromiseState as _, setDocumentCache as a, isDuplicateModuleError as b, useDocumentSafe as c, useGetDocumentAsync as d, useGetDocuments as f, isOperationCache as g, addPromiseState as h, addDocumentCacheEventHandler as i, useDocuments as l, IDLE_OPERATIONS_ENTRY as m, useDocumentsByIds as n, useDocument as o, DocumentCache as p, useDispatch as r, useDocumentCache as s, useDocumentById as t, useGetDocument as u, DOCUMENT_CHANGE_TYPE as v, queueActions as w, DocumentRefetcher as x, isDuplicateManifestError as y };
722
850
 
723
- //# sourceMappingURL=document-by-id-iXB59Ge-.js.map
851
+ //# sourceMappingURL=document-by-id-DgdUGMVm.js.map