@powerhousedao/reactor-browser 6.2.3-dev.1 → 6.2.3-dev.100

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 (107) hide show
  1. package/dist/attachment-service-DXfpfp98.d.ts +1757 -0
  2. package/dist/attachment-service-DXfpfp98.d.ts.map +1 -0
  3. package/dist/auth-DzIYxeEJ.d.ts +32 -0
  4. package/dist/auth-DzIYxeEJ.d.ts.map +1 -0
  5. package/dist/client-1n_ZUXeu.js +135 -0
  6. package/dist/client-1n_ZUXeu.js.map +1 -0
  7. package/dist/{client-BIHN_UyR.d.ts → client-BFk0MY6A.d.ts} +4 -3
  8. package/dist/client-BFk0MY6A.d.ts.map +1 -0
  9. package/dist/{client-DjK30EQ-.js → client-BFnMV-EO.js} +39 -22
  10. package/dist/client-BFnMV-EO.js.map +1 -0
  11. package/dist/dispatch-Cylwl2Dk.js +1173 -0
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/document-by-id-DdvqanGR.js +16 -0
  14. package/dist/document-by-id-DdvqanGR.js.map +1 -0
  15. package/dist/document-model-modules-BG-61uke.js +710 -0
  16. package/dist/document-model-modules-BG-61uke.js.map +1 -0
  17. package/dist/document-operations-D5QXcJbV.js +4609 -0
  18. package/dist/document-operations-D5QXcJbV.js.map +1 -0
  19. package/dist/global-DAAmZGCO.d.ts +612 -0
  20. package/dist/global-DAAmZGCO.d.ts.map +1 -0
  21. package/dist/{index-CkJNhsQo.d.ts → index-Bj1poVfa.d.ts} +32 -100
  22. package/dist/index-Bj1poVfa.d.ts.map +1 -0
  23. package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
  24. package/dist/index-rtDmzViP.d.ts.map +1 -0
  25. package/dist/index.d.ts +938 -405
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +883 -307
  28. package/dist/index.js.map +1 -1
  29. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  30. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  31. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  32. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  33. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  34. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  35. package/dist/{relational-D4sxGPz7.js → relational-DZuyKp2y.js} +66 -5
  36. package/dist/relational-DZuyKp2y.js.map +1 -0
  37. package/dist/{renown-BIEv6bSI.js → renown-B3MUaiq7.js} +78 -33
  38. package/dist/renown-B3MUaiq7.js.map +1 -0
  39. package/dist/renown-CBoTdGrg.js +394 -0
  40. package/dist/renown-CBoTdGrg.js.map +1 -0
  41. package/dist/{types-Dcv1ZLoW.d.ts → schema-Bn6L3QR1.d.ts} +324 -64
  42. package/dist/schema-Bn6L3QR1.d.ts.map +1 -0
  43. package/dist/{client-D66jVnot.js → schema-D0G1oAo9.js} +358 -150
  44. package/dist/schema-D0G1oAo9.js.map +1 -0
  45. package/dist/src/ai/index.d.ts +313 -79
  46. package/dist/src/ai/index.d.ts.map +1 -1
  47. package/dist/src/ai/index.js +1030 -173
  48. package/dist/src/ai/index.js.map +1 -1
  49. package/dist/src/analytics/index.d.ts +36 -44
  50. package/dist/src/analytics/index.d.ts.map +1 -1
  51. package/dist/src/analytics/index.js +4 -4
  52. package/dist/src/analytics/index.js.map +1 -1
  53. package/dist/src/document-model.d.ts +3 -4
  54. package/dist/src/document-model.d.ts.map +1 -1
  55. package/dist/src/document-model.js.map +1 -1
  56. package/dist/src/graphql/client.d.ts +4 -3
  57. package/dist/src/graphql/client.js +1 -1
  58. package/dist/src/graphql-client/entry.d.ts +7 -4
  59. package/dist/src/graphql-client/entry.js +4 -4
  60. package/dist/src/relational/index.d.ts +15 -9
  61. package/dist/src/relational/index.d.ts.map +1 -1
  62. package/dist/src/relational/index.js +1 -1
  63. package/dist/src/renown/index.d.ts +3 -2
  64. package/dist/src/renown/index.js +3 -3
  65. package/dist/src/rpc/index.d.ts +217 -140
  66. package/dist/src/rpc/index.d.ts.map +1 -1
  67. package/dist/src/rpc/index.js +602 -623
  68. package/dist/src/rpc/index.js.map +1 -1
  69. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  70. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  71. package/dist/switchboard-directory-CWf5SRo7.js +435 -0
  72. package/dist/switchboard-directory-CWf5SRo7.js.map +1 -0
  73. package/dist/switchboards-D-_JBUbF.d.ts +75 -0
  74. package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
  75. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  76. package/dist/types-520nWrB3.d.ts.map +1 -0
  77. package/dist/types-CyPDurGV.d.ts +63 -0
  78. package/dist/types-CyPDurGV.d.ts.map +1 -0
  79. package/package.json +24 -23
  80. package/dist/attachment-service-CdwHrbDH.d.ts +0 -1063
  81. package/dist/attachment-service-CdwHrbDH.d.ts.map +0 -1
  82. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  83. package/dist/client-D66jVnot.js.map +0 -1
  84. package/dist/client-DjK30EQ-.js.map +0 -1
  85. package/dist/document-by-id-BSZqTN66.js +0 -517
  86. package/dist/document-by-id-BSZqTN66.js.map +0 -1
  87. package/dist/document-model-modules-DfQBNGc-.js +0 -419
  88. package/dist/document-model-modules-DfQBNGc-.js.map +0 -1
  89. package/dist/document-operations-Bgo6A6W2.js +0 -2545
  90. package/dist/document-operations-Bgo6A6W2.js.map +0 -1
  91. package/dist/global-BggszP4X.d.ts +0 -401
  92. package/dist/global-BggszP4X.d.ts.map +0 -1
  93. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  94. package/dist/index-CkJNhsQo.d.ts.map +0 -1
  95. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  96. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  97. package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
  98. package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
  99. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  100. package/dist/relational-D4sxGPz7.js.map +0 -1
  101. package/dist/renown-BHxwP7xU.js +0 -97
  102. package/dist/renown-BHxwP7xU.js.map +0 -1
  103. package/dist/renown-BIEv6bSI.js.map +0 -1
  104. package/dist/switchboard-D4-_jwk-.js +0 -271
  105. package/dist/switchboard-D4-_jwk-.js.map +0 -1
  106. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  107. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
@@ -0,0 +1,1757 @@
1
+ import { _ as Sdk, a as DocumentChangesSubscription, c as GetDocumentQuery, g as Scalars, h as PropagationMode$1, m as PhDocumentFieldsFragment, s as GetDocumentOperationsQuery, t as ActionInput, u as JobChangesSubscription, v as SdkFunctionWrapper, y as ViewFilterInput } from "./schema-Bn6L3QR1.js";
2
+ import { t as BearerTokenProvider } from "./auth-DzIYxeEJ.js";
3
+ import { $ as IPackageManager, Gt as PromiseState, Ht as IDocumentTypeCache, Kt as PromiseWithState, Q as IPackageListerUnsubscribe, Rt as DocumentRefetchState, Ut as IOperationCache, Vt as IDocumentCache, Wt as OperationsCacheEntry, b as UsePHGlobalValue$1, et as IPackagesListener, s as PHGlobal$1, tt as PackageManagerInstallResult, v as SetPHGlobalValue$1, zt as DocumentsOfTypeEntry } from "./global-DAAmZGCO.js";
4
+ import { a as IReactorBrowserReadClient, i as IReactorBrowserClient$1, o as IReactorBrowserWriteClient } from "./switchboards-D-_JBUbF.js";
5
+ import { t as PGlite } from "./pglite-CntadC_p-DTkdF8sr.js";
6
+ import { c as ReactorGraphQLClient } from "./types-CyPDurGV.js";
7
+ import { ReactNode } from "react";
8
+ import { Action, DocumentModelLib, DocumentModelModule, Operation, PHDocument } from "document-model";
9
+ import { Action as Action$1, ActionSigningTarget, DispatchOutcome, DocumentModelModule as DocumentModelModule$1, DocumentOperations, ISigner, Operation as Operation$1, PHBaseState, PHDocument as PHDocument$1, PHDocumentHeader, ProtocolVersions, SignaturePolicy } from "@powerhousedao/shared/document-model";
10
+ import { BatchExecutionRequest, BatchExecutionResult, ConsistencyToken, CreateProtocolVersionsOptions, Database, DocumentChangeEvent, DocumentModelSource, DocumentRelationship, DriveNodeKind, DriveNodePage, DriveNodeRecord, IDocumentModelRegistry, IDriveNodeSource, IDriveReadClient, IReactorClient, ISyncManager, JobInfo, NewDocumentOptions, OperationFilter, PagedResults, PagingOptions, PropagationMode, SearchFilter, UndoRedoAvailability, UndoRedoTargets, ViewFilter } from "@powerhousedao/reactor";
11
+ import { Node } from "@powerhousedao/shared/document-drive";
12
+ import { DocumentNode } from "graphql";
13
+ import { GraphQLClient, Variables } from "graphql-request";
14
+ import { IAttachmentService } from "@powerhousedao/reactor-attachments/client";
15
+ import { Kysely } from "kysely";
16
+ import { AddPHGlobalEventHandler, BrowserReactorClientModule, IReactorBrowserClient, ReactorBrowserHalves, SetPHGlobalValue, UsePHGlobalValue, WorkerReactorClientModule } from "@powerhousedao/reactor-browser";
17
+ import { RegistryPackageSource } from "@powerhousedao/shared";
18
+ import { ReactorReach, RoutableBackendConfig } from "@powerhousedao/reactor-router";
19
+ //#region src/actions/dispatch.d.ts
20
+ /** Called once the write lands; `outcome.rejected` is empty when every action applied. */
21
+ type DispatchSuccessCallback = (result: PHDocument$1, outcome: DispatchOutcome) => void;
22
+ /**
23
+ * Dispatches actions to a document.
24
+ * @param actionOrActions - The action or actions to dispatch.
25
+ * @param document - The document to dispatch actions to.
26
+ * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
27
+ * document did not apply, or with why nothing was dispatched. Runs before `onSuccess`.
28
+ * @param onSuccess - Callback invoked with the updated document once the write lands, after
29
+ * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
30
+ * @returns The updated document, or undefined if the dispatch failed.
31
+ */
32
+ declare function dispatchActions<TDocument = PHDocument$1, TAction = Action$1>(actionOrActions: TAction[] | TAction | undefined, document: TDocument | undefined, onErrors?: (errors: Error[]) => void, onSuccess?: DispatchSuccessCallback): Promise<PHDocument$1 | undefined>;
33
+ /**
34
+ * Dispatches actions to a document.
35
+ * @param actionOrActions - The action or actions to dispatch.
36
+ * @param documentId - The ID of the document to dispatch actions to.
37
+ * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
38
+ * document did not apply. Runs before `onSuccess`.
39
+ * @param onSuccess - Callback invoked with the updated document once the write lands, after
40
+ * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
41
+ * @returns The updated document, or undefined if the dispatch failed.
42
+ */
43
+ declare function dispatchActions(actionOrActions: Action$1[] | Action$1 | undefined, documentId: string, onErrors?: (errors: Error[]) => void, onSuccess?: DispatchSuccessCallback): Promise<PHDocument$1 | undefined>;
44
+ //#endregion
45
+ //#region src/document-refetcher.d.ts
46
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
47
+ declare const IDLE_REFETCH_STATE: DocumentRefetchState;
48
+ //#endregion
49
+ //#region src/document-cache.d.ts
50
+ /**
51
+ * The reads a {@link DocumentCache} makes. `getMany` is optional: without it,
52
+ * a batch reads each uncached id with `get`.
53
+ */
54
+ interface IDocumentCacheReader extends Pick<IReactorBrowserReadClient, "get" | "find" | "getOperations" | "subscribe">, Partial<Pick<IReactorBrowserReadClient, "getMany">> {}
55
+ /** The most ids one `getMany` call is asked for. */
56
+ declare const GET_MANY_CHUNK_SIZE = 100;
57
+ declare function addPromiseState<T>(promise: Promise<T>): PromiseWithState<T>;
58
+ declare function readPromiseState<T>(promise: Promise<T> | PromiseWithState<T>): PromiseState<T>;
59
+ /** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */
60
+ declare const IDLE_OPERATIONS_ENTRY: OperationsCacheEntry;
61
+ /** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */
62
+ declare function isOperationCache(cache: unknown): cache is IOperationCache;
63
+ /** The snapshot every unloaded type reads as, frozen so `useSyncExternalStore` sees one value. */
64
+ declare const IDLE_DOCUMENTS_OF_TYPE_ENTRY: DocumentsOfTypeEntry;
65
+ /** Whether a document cache also lists documents by type. */
66
+ declare function isDocumentTypeCache(cache: unknown): cache is IDocumentTypeCache;
67
+ /**
68
+ * Document cache implementation that uses the new ReactorClient API.
69
+ *
70
+ * This cache subscribes to document change events through the client's read half
71
+ * and automatically updates the cache when documents are created, updated, or deleted.
72
+ * It is built over a browser client, whose `read` half it uses, or over a read
73
+ * half directly.
74
+ * It also holds paginated operation history per document scope (see `IOperationCache`),
75
+ * which is dropped for a document whenever a change event for it arrives.
76
+ */
77
+ declare class DocumentCache implements IDocumentCache, IOperationCache, IDocumentTypeCache {
78
+ private documents;
79
+ private batchPromises;
80
+ private listeners;
81
+ private refetcher;
82
+ /**
83
+ * Cache keys that fetched a document under a name other than its id --
84
+ * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
85
+ * so without this mapping a slug-keyed entry (and its listeners) would never
86
+ * see an update: keyed by the id the events carry, valued by the other keys
87
+ * the same document is cached under.
88
+ */
89
+ private aliasKeys;
90
+ /** Operations by document id, then scope. Entries are replaced, never mutated. */
91
+ private operationEntries;
92
+ /** In-flight controllers and the next page's cursor/limit, by document id then scope. */
93
+ private operationRequests;
94
+ private operationListeners;
95
+ /** Documents by type and page size, keyed by typeKey. */
96
+ private typeEntries;
97
+ private typeRequests;
98
+ private typeListeners;
99
+ private unsubscribe;
100
+ private readonly client;
101
+ constructor(client: IReactorBrowserClient$1 | IDocumentCacheReader);
102
+ private handleDocumentChange;
103
+ private handleDocumentDeleted;
104
+ private handleDocumentUpdated;
105
+ private notifyListeners;
106
+ /** The id an event dispatches by, plus every alias the document is cached under. */
107
+ private cacheKeysFor;
108
+ /** Records that `key` cached the document change events know as `header.id`. */
109
+ private recordAlias;
110
+ private invalidateBatchesContaining;
111
+ get(id: string, refetch?: boolean): Promise<PHDocument$1>;
112
+ getRefetchState(id: string): DocumentRefetchState;
113
+ getBatch(ids: string[]): Promise<PHDocument$1[]>;
114
+ /**
115
+ * Reserves an entry for every id not yet cached and fills them from
116
+ * `getMany`, in chunks of {@link GET_MANY_CHUNK_SIZE}. Each id keeps its own
117
+ * entry, settled as `get` would settle it.
118
+ */
119
+ private loadMany;
120
+ /**
121
+ * `getMany` rejects when any id is unavailable, so a failed chunk is split
122
+ * in half and retried; a single id is read with `get`, so it settles exactly
123
+ * as a single read would.
124
+ */
125
+ private settleMany;
126
+ private settleFetched;
127
+ subscribe(id: string | string[], callback: () => void): () => void;
128
+ getOperationsState(documentId: string, scope: string): OperationsCacheEntry;
129
+ loadOperations(documentId: string, scope: string, limit: number): void;
130
+ loadMoreOperations(documentId: string, scope: string): void;
131
+ /**
132
+ * Bring a document's cached scopes up to date after it changed, without
133
+ * throwing away what is already loaded.
134
+ *
135
+ * The operation stream is append-only: an update adds operations at higher
136
+ * revisions and never rewrites the ones below, so history already paged in
137
+ * is still correct. Dropping it meant a panel showing a fully loaded
138
+ * document re-walked every page on each edit -- the cost of which grows
139
+ * with the document, exactly where it hurts most. Each scope instead asks
140
+ * only for what comes after the newest revision it holds, using the
141
+ * `sinceRevision` filter, and appends the answer.
142
+ *
143
+ * A scope that has not finished paging is dropped as before: it has no
144
+ * meaningful "newest revision" to resume from, since asking for everything
145
+ * past the newest row it happens to hold would skip the pages between that
146
+ * row and the end of the stream.
147
+ */
148
+ private refreshOperations;
149
+ /** Drops one scope of a document, aborting its request if one is in flight. */
150
+ private invalidateOperationsScope;
151
+ invalidateOperations(documentId: string): void;
152
+ subscribeOperations(documentId: string, callback: () => void): () => void;
153
+ private settleOperationsPage;
154
+ private setOperationsEntry;
155
+ private setOperationsRequest;
156
+ private notifyOperationListeners;
157
+ getDocumentsOfTypeState(type: string, limit: number): DocumentsOfTypeEntry;
158
+ loadDocumentsOfType(type: string, limit: number): Promise<void>;
159
+ loadMoreDocumentsOfType(type: string, limit: number): void;
160
+ subscribeDocumentsOfType(type: string, limit: number, callback: () => void): () => void;
161
+ /** Loads one page after `before` and appends it; never rejects, the entry holds the error. */
162
+ private loadTypePage;
163
+ /** Reloads every loaded page of a type a created or deleted document belongs to. */
164
+ private reloadTypesChangedBy;
165
+ private primeDocument;
166
+ private getTypeEntry;
167
+ private setTypeEntry;
168
+ /**
169
+ * Disposes of the cache and unsubscribes from document change events.
170
+ */
171
+ dispose(): void;
172
+ }
173
+ //#endregion
174
+ //#region src/remote-controller/types.d.ts
175
+ type RemoteControllerGraphQLClient = Pick<ReactorGraphQLClient, "GetDocument" | "GetDocumentWithOperations" | "GetDocumentOperations" | "MutateDocument" | "CreateDocument" | "CreateEmptyDocument" | "GetCreateDefaults" | "GetCreateProtocolVersions" | "DeleteDocument" | "BatchGetDocumentOperations" | "BatchGetDocumentWithOperations">;
176
+ type RemoteDocumentData = PhDocumentFieldsFragment;
177
+ type RemoteOperation = GetDocumentOperationsQuery["documentOperations"]["items"][number];
178
+ type RemoteOperationResultPage = GetDocumentOperationsQuery["documentOperations"];
179
+ /**
180
+ * Options for creating a RemoteDocumentController.
181
+ */
182
+ type RemoteControllerOptions = {
183
+ client: RemoteControllerGraphQLClient;
184
+ /** Remote document id. Omit for new documents. */
185
+ documentId?: string;
186
+ /** "batch" requires explicit push(), "streaming" auto-pushes after actions. Defaults to "batch" */
187
+ mode?: "batch" | "streaming";
188
+ /** Optional signer for action signing. */
189
+ signer?: ISigner;
190
+ /** Branch name, defaults to "main". */
191
+ branch?: string;
192
+ /** Parent document identifier for creating new documents. */
193
+ parentIdentifier?: string;
194
+ /** Conflict resolution strategy when remote has new operations. Default: no check (current behavior). */
195
+ onConflict?: ConflictStrategy;
196
+ /** Called when a streaming-mode push fails. If not provided, errors are silently swallowed. */
197
+ onPushError?: (error: unknown) => void;
198
+ /** Number of operations to fetch per page. Defaults to 100. */
199
+ operationsPageSize?: number;
200
+ };
201
+ /**
202
+ * Result of a push operation.
203
+ */
204
+ type PushResult = {
205
+ remoteDocument: RemoteDocumentData;
206
+ actionCount: number;
207
+ /** The actions that were sent to the server (after signing, if applicable). */
208
+ operations: ReadonlyArray<Action$1>;
209
+ };
210
+ /**
211
+ * Sync status of the controller.
212
+ */
213
+ type SyncStatus$1 = {
214
+ pendingActionCount: number;
215
+ connected: boolean;
216
+ documentId: string;
217
+ remoteRevision: Record<string, number>;
218
+ };
219
+ /**
220
+ * A tracked action with operation context for signing.
221
+ */
222
+ type TrackedAction = {
223
+ action: Action$1;
224
+ prevOpHash: string;
225
+ prevOpIndex: number;
226
+ };
227
+ /** Information about a detected conflict. */
228
+ type ConflictInfo = {
229
+ /** Remote operations added since the last pull, grouped by scope. */
230
+ remoteOperations: Record<string, RemoteOperation[]>;
231
+ /** Local actions pending push. */
232
+ localActions: TrackedAction[];
233
+ /** Remote revision at last pull. */
234
+ knownRevision: Record<string, number>;
235
+ /** Current remote revision. */
236
+ currentRevision: Record<string, number>;
237
+ };
238
+ /** Custom merge handler receives conflict info and returns actions to push (or throws to abort). */
239
+ type MergeHandler = (conflict: ConflictInfo) => Action$1[] | Promise<Action$1[]>;
240
+ /** Conflict resolution strategy. */
241
+ type ConflictStrategy = "reject" | "rebase" | MergeHandler;
242
+ /** Event emitted when the document changes. */
243
+ type RemoteDocumentChangeEvent = {
244
+ source: "action" | "pull";
245
+ document: PHDocument$1<PHBaseState>;
246
+ };
247
+ /** Listener for document change events. */
248
+ type DocumentChangeListener = (event: RemoteDocumentChangeEvent) => void;
249
+ /** Result of fetching operations. */
250
+ type GetOperationsResult = {
251
+ operationsByScope: Record<string, RemoteOperation[]>;
252
+ };
253
+ /** Result of fetching a document together with its operations. */
254
+ type GetDocumentWithOperationsResult = {
255
+ document: RemoteDocumentData;
256
+ childIds: ReadonlyArray<string>;
257
+ operations: GetOperationsResult;
258
+ };
259
+ interface IRemoteClient {
260
+ getDocument(identifier: string, branch?: string): Promise<GetDocumentResult | null>;
261
+ /** Fetch document metadata and operations in a single call. */
262
+ getDocumentWithOperations(identifier: string, branch?: string, sinceRevision?: Record<string, number>, scopes?: string[]): Promise<GetDocumentWithOperationsResult | null>;
263
+ getAllOperations(documentId: string, branch?: string, sinceRevision?: Record<string, number>, scopes?: string[]): Promise<GetOperationsResult>;
264
+ pushActions(documentIdentifier: string, actions: ReadonlyArray<ActionInput>, branch?: string): Promise<RemoteDocumentData>;
265
+ createDocument(document: NonNullable<unknown>, parentIdentifier?: string): Promise<RemoteDocumentData>;
266
+ createEmptyDocument(documentType: string, parentIdentifier?: string): Promise<RemoteDocumentData>;
267
+ deleteDocument(identifier: string, propagate?: PropagationMode$1): Promise<boolean>;
268
+ }
269
+ type GetDocumentResult = {
270
+ document: RemoteDocumentData;
271
+ childIds: ReadonlyArray<string>;
272
+ };
273
+ interface IRemoteController<TState extends PHBaseState = PHBaseState> {
274
+ readonly header: PHDocumentHeader;
275
+ readonly state: TState;
276
+ readonly operations: DocumentOperations;
277
+ readonly document: PHDocument$1<TState>;
278
+ readonly status: SyncStatus$1;
279
+ onChange(listener: DocumentChangeListener): () => void;
280
+ push(): Promise<PushResult>;
281
+ pull(): Promise<RemoteDocumentData>;
282
+ delete(propagate?: PropagationMode$1): Promise<boolean>;
283
+ }
284
+ //#endregion
285
+ //#region src/graphql-client/adapter.d.ts
286
+ /** The `document` payload of a `GetDocument` query, once the null case is handled. */
287
+ type GetDocumentQueryResult = NonNullable<GetDocumentQuery["document"]>;
288
+ /** The `PHDocumentFields` fragment as returned by `GetDocument`. */
289
+ type GetDocumentQueryFields = GetDocumentQueryResult["document"];
290
+ /** The `revisionsList` selection of the `PHDocumentFields` fragment. */
291
+ type RevisionsListSelection = GetDocumentQueryFields["revisionsList"];
292
+ /**
293
+ * Converts a `GetDocument` result into a `PHDocument`.
294
+ *
295
+ * Unlike the legacy `src/graphql/adapters.ts` this preserves the per-scope
296
+ * revision map, which the write path needs to compute the `prevOpIndex` of a
297
+ * signed action. `sig` is filled with the empty shape used by
298
+ * `createPresignedHeader`: the creation signature is not fetchable over
299
+ * GraphQL and is not part of the operation signing payload.
300
+ *
301
+ * The read path never fetches operation history, so `operations` maps each
302
+ * scope of the document's state and revisions to an empty array.
303
+ *
304
+ * `branch` is the branch the document was read from. The GraphQL type does not
305
+ * carry it, so it has to be passed back in by the caller; it defaults to the
306
+ * server's own default branch.
307
+ */
308
+ declare function phDocumentFromGetDocument<TDocument extends PHDocument = PHDocument>(document: GetDocumentQueryFields, branch?: string): TDocument;
309
+ /**
310
+ * Converts a mutation result into a `PHDocument`, carrying the operations the
311
+ * mutation produced.
312
+ *
313
+ * `dispatchActions` reads per-action failures out of `operations[scope]`, so
314
+ * unlike the read path this one must not return empty operation lists.
315
+ */
316
+ declare function phDocumentFromMutation<TDocument extends PHDocument = PHDocument>(document: GetDocumentQueryFields, operations: readonly RemoteOperation[], branch?: string): TDocument;
317
+ /** Turns a `revisionsList` selection into the header's per-scope revision map. */
318
+ declare function revisionMapFromRevisionsList(revisionsList: RevisionsListSelection): Record<string, number>;
319
+ /** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */
320
+ declare function isoStringFromDateTime(value: string | Date): string;
321
+ //#endregion
322
+ //#region src/graphql-client/drive-nodes.d.ts
323
+ /** The node queries a {@link GraphQLDriveNodeSource} runs. */
324
+ type DriveNodeQueries = Pick<Sdk, "GetDriveNodes" | "GetDriveNode" | "GetDriveDescendants">;
325
+ /**
326
+ * The reactor subgraph's type-neutral node queries (`driveNodes`, `driveNode`,
327
+ * `driveDescendants`) as an {@link IDriveNodeSource}, so a browser reads a
328
+ * legacy drive and a reactor-drive alike. The Switchboard serves only the
329
+ * nodes the caller may read. Drive ids must be canonical ids, not slugs.
330
+ */
331
+ declare class GraphQLDriveNodeSource implements IDriveNodeSource {
332
+ private readonly queries;
333
+ private readonly headersFor;
334
+ constructor(queries: DriveNodeQueries, headersFor?: (driveId: string) => Record<string, string> | undefined);
335
+ getNode(driveId: string, nodeId: string, signal?: AbortSignal): Promise<DriveNodeRecord | undefined>;
336
+ listChildren(driveId: string, parentFolder: string | null | undefined, paging?: PagingOptions, signal?: AbortSignal, kind?: DriveNodeKind): Promise<DriveNodePage>;
337
+ getDescendants(driveId: string, root: string, signal?: AbortSignal): Promise<DriveNodeRecord[]>;
338
+ listAll(driveId: string, signal?: AbortSignal): Promise<DriveNodeRecord[]>;
339
+ }
340
+ /**
341
+ * `read.drives` over a node source: the reactor's {@link IDriveReadClient},
342
+ * answering in the legacy `Node` shape for every drive type.
343
+ */
344
+ declare class GraphQLDriveReadClient implements IDriveReadClient {
345
+ private readonly nodes;
346
+ constructor(nodes: IDriveNodeSource);
347
+ getNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<Node>;
348
+ listNodes(driveIdentifier: string, parentFolder?: string | null, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Node>>;
349
+ }
350
+ /** A node record in the legacy `Node` shape. */
351
+ declare function toLegacyNode(node: DriveNodeRecord): Node;
352
+ //#endregion
353
+ //#region src/graphql-client/errors.d.ts
354
+ /** A call the Switchboard GraphQL surface cannot express. */
355
+ declare class GraphQLOperationNotSupportedError extends Error {
356
+ readonly name = "GraphQLOperationNotSupportedError";
357
+ readonly operation: string;
358
+ constructor(operation: string, reason: string);
359
+ static isError(error: unknown): error is GraphQLOperationNotSupportedError;
360
+ }
361
+ /**
362
+ * The Switchboard refused a request with 421 Misdirected Request: the
363
+ * `Drive-Id` it carried names a drive that Switchboard does not own.
364
+ */
365
+ declare class GraphQLWrongBackendError extends Error {
366
+ readonly name = "GraphQLWrongBackendError";
367
+ readonly status = 421;
368
+ /** The drive the Switchboard refused, or `""` when its answer names none. */
369
+ readonly driveId: string;
370
+ /** The response body, parsed when it is JSON. */
371
+ readonly payload: unknown;
372
+ constructor(driveId: string, payload: unknown, options?: ErrorOptions);
373
+ static isError(error: unknown): error is GraphQLWrongBackendError;
374
+ }
375
+ /**
376
+ * The reactor's `BatchJobFailedError`, rebuilt from a batch result; this entry
377
+ * imports the reactor for types only. The shared name lets either `isError`
378
+ * recognise it.
379
+ */
380
+ declare class BatchJobFailedError extends Error {
381
+ readonly name = "BatchJobFailedError";
382
+ readonly key: string;
383
+ readonly jobs: Readonly<Record<string, JobInfo>>;
384
+ constructor(key: string, jobs: Record<string, JobInfo>);
385
+ static isError(error: unknown): error is BatchJobFailedError;
386
+ }
387
+ /** A validation error naming root field `field` unknown: a host from before it. */
388
+ declare function queriesUnknownField(error: unknown, field: string): boolean;
389
+ /** A validation error naming `argument` unknown: a host from before it. */
390
+ declare function queriesUnknownArgument(error: unknown, argument: string): boolean;
391
+ /**
392
+ * The reactor's `JobFailedError`, rebuilt from a job the Switchboard reported
393
+ * FAILED; this entry imports the reactor for types only. A write handle's
394
+ * stage rejects with it. The message is the job error's message, as the
395
+ * reactor's is.
396
+ */
397
+ declare class JobFailedError extends Error {
398
+ readonly name = "JobFailedError";
399
+ readonly job: JobInfo;
400
+ constructor(job: JobInfo);
401
+ static isError(error: unknown): error is JobFailedError;
402
+ }
403
+ //#endregion
404
+ //#region src/graphql-client/transport.d.ts
405
+ /** The `fetch` a client's HTTP requests go through. */
406
+ type GraphQLFetch = typeof globalThis.fetch;
407
+ /** The global `fetch`, read per call so a later replacement is honoured. */
408
+ declare const globalFetch: GraphQLFetch;
409
+ /**
410
+ * Whether `fetch` here is Node's (undici), which resends a request answered
411
+ * 421 and can fail the resend of a buffered body. A page, Electron's renderer
412
+ * included, has a `document`.
413
+ */
414
+ declare function isNodeFetch(): boolean;
415
+ /**
416
+ * Sends a string body as a stream, which fetch never resends, so a 421 comes
417
+ * back as itself. Browsers keep buffered bodies: Chrome streams an upload only
418
+ * over HTTP/2.
419
+ */
420
+ declare function withStreamedBodies(inner?: GraphQLFetch): GraphQLFetch;
421
+ /** A Switchboard backend's default transport: streamed bodies under Node only. */
422
+ declare const switchboardFetch: GraphQLFetch;
423
+ /** Bounds each request, headers through body; rejects with a `TimeoutError`. */
424
+ declare function withRequestDeadline(timeoutMs: number, inner?: GraphQLFetch): GraphQLFetch;
425
+ /**
426
+ * Whether a request failed at a deadline rather than by its caller's abort:
427
+ * this transport's own (`TimeoutError`, a DOMException) or the router's probe
428
+ * deadline (`ProbeTimeoutError`, reactor-router's dispatcher.ts).
429
+ */
430
+ declare function isDeadlineError(error: unknown): boolean;
431
+ //#endregion
432
+ //#region src/graphql-client/subgraph.d.ts
433
+ /**
434
+ * The factory a GraphQL code generator produces for a schema.
435
+ *
436
+ * It is the signature of `getSdk` emitted by the `typescript-graphql-request`
437
+ * plugin - the generated `getSdk` in `src/graphql/gen/schema.ts` is the
438
+ * canonical example - so a project can hand its own generated function straight
439
+ * to {@link SubgraphSdkRegistry.get} and keep every operation typed.
440
+ */
441
+ type SubgraphSdkFactory<TSdk> = (client: GraphQLClient, withWrapper?: SdkFunctionWrapper) => TSdk;
442
+ /**
443
+ * A GraphQL document that carries its result and variable types.
444
+ *
445
+ * This is the shape a code generator gives a document (`TypedDocumentNode`),
446
+ * declared structurally so that reactor-browser needs no dependency on
447
+ * `@graphql-typed-document-node/core`. A plain `DocumentNode` satisfies it too,
448
+ * with the result type falling back to whatever the caller passes explicitly.
449
+ */
450
+ type TypedGraphQLDocument<TResult, TVariables> = DocumentNode & {
451
+ __apiType?: (variables: TVariables) => TResult;
452
+ };
453
+ /** Extras for a one-off request. */
454
+ type GraphQLRequestOptions = {
455
+ /**
456
+ * The operation name reported to the auth and logging middleware. Read off
457
+ * the document when it is not given.
458
+ */
459
+ operationName?: string;
460
+ /**
461
+ * The operation type reported to the middleware, e.g. `"mutation"`. Read off
462
+ * the document when it is not given.
463
+ */
464
+ operationType?: string;
465
+ signal?: AbortSignal;
466
+ };
467
+ /**
468
+ * Derives a subgraph's endpoint from the Switchboard's GraphQL endpoint.
469
+ *
470
+ * Subgraphs are served next to the supergraph, at `<graphql base>/<name>`, so
471
+ * `http://localhost:4001/graphql` plus `statements` is
472
+ * `http://localhost:4001/graphql/statements`.
473
+ */
474
+ declare function subgraphUrlFromGraphqlUrl(url: string, name: string): string;
475
+ /**
476
+ * Reads the operation name and type off a document, for the middleware.
477
+ *
478
+ * Nothing depends on getting this right - it is reported to the middleware, not
479
+ * sent to the server - so an unreadable document falls back to an anonymous
480
+ * query rather than throwing.
481
+ */
482
+ declare function describeGraphQLDocument(document: string | DocumentNode): {
483
+ operationName: string;
484
+ operationType: string;
485
+ };
486
+ /**
487
+ * Binds typed subgraph SDKs to one Switchboard's transport and auth.
488
+ *
489
+ * Every capability a Switchboard exposes lives behind the same base URL, so an
490
+ * app should not have to build a second client - with a second copy of the auth
491
+ * configuration - to reach a project's own subgraph. The registry derives the
492
+ * endpoint, reuses one transport per subgraph and hands the code generator's
493
+ * `getSdk` the very middleware the reactor operations already go through.
494
+ *
495
+ * Transport and typing only: subgraph results are not cached and produce no
496
+ * change events.
497
+ */
498
+ declare class SubgraphSdkRegistry {
499
+ private readonly url;
500
+ private readonly middleware;
501
+ private readonly fetch;
502
+ private readonly bindings;
503
+ constructor(url: string, middleware?: SdkFunctionWrapper, fetch?: GraphQLFetch);
504
+ /**
505
+ * Returns the subgraph's SDK, building it on first use.
506
+ *
507
+ * The transport is kept per subgraph name, so repeated calls do not rebuild
508
+ * it. The SDK itself is only reused when the same factory is passed again -
509
+ * two different generated SDKs over one subgraph each get their own, rather
510
+ * than the second call being handed the first one's methods.
511
+ */
512
+ get<TSdk>(name: string, getSdk: SubgraphSdkFactory<TSdk>): TSdk;
513
+ /** Returns the subgraph's endpoint, for diagnostics and tests. */
514
+ urlFor(name: string): string;
515
+ private binding;
516
+ }
517
+ //#endregion
518
+ //#region src/graphql-client/graphql-reactor-client.d.ts
519
+ /** A call the client asks {@link GraphQLReactorClientOptions.driveIdFor} about. */
520
+ type DriveIdCall = {
521
+ readonly method: "create" | "execute" | "executeBatch" | "deleteDocument" | "find";
522
+ readonly documentId?: string;
523
+ readonly parentId?: string;
524
+ readonly jobs?: readonly {
525
+ readonly documentId: string;
526
+ }[];
527
+ };
528
+ type GraphQLReactorClientOptions = {
529
+ /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */
530
+ url: string;
531
+ /**
532
+ * A pre-built SDK to use instead of the transport derived from `url`.
533
+ * Mainly a test seam.
534
+ *
535
+ * A client built this way carries no auth middleware and no 421 mapping:
536
+ * the injected SDK owns its own transport, and therefore its own headers
537
+ * and transport errors.
538
+ */
539
+ graphqlClient?: ReactorGraphQLClient;
540
+ /**
541
+ * Resolves the bearer token sent with every request, per request.
542
+ *
543
+ * Defaults to {@link ambientRenownTokenProvider}, i.e. the token of the
544
+ * logged-in Renown user, or none when nobody is logged in.
545
+ */
546
+ tokenProvider?: BearerTokenProvider;
547
+ /**
548
+ * The Switchboard GraphQL subscriptions endpoint, e.g.
549
+ * `ws://localhost:4001/graphql/subscriptions`.
550
+ *
551
+ * Defaults to the endpoint derived from `url` by
552
+ * {@link subscriptionsUrlFromGraphqlUrl}.
553
+ */
554
+ subscriptionsUrl?: string;
555
+ /**
556
+ * Whether server-pushed changes are delivered to subscribers.
557
+ *
558
+ * On by default: the first `subscribe` call opens a websocket and every
559
+ * change the Switchboard reports is emitted to matching subscribers, so
560
+ * documents another user, tab or processor writes invalidate the cache.
561
+ *
562
+ * Set it to `false` where there is no websocket to talk to. The client then
563
+ * only emits the changes it made itself.
564
+ */
565
+ realtime?: boolean;
566
+ /**
567
+ * The document model modules used to sign a batch of two or more actions.
568
+ *
569
+ * Signing action N+1 needs the state action N leaves behind, and only the
570
+ * document's own reducer can predict it - so a batch is signable only when
571
+ * the module matching the document's type AND its exact
572
+ * `state.document.version` is here. One action needs no prediction and is
573
+ * signed without any of this.
574
+ *
575
+ * An array is read once, when the client is built; a function is called at
576
+ * every batch, for a registry that gains models later. Below
577
+ * `GraphQLReactorProvider` this is its `documentModels` prop; a client
578
+ * constructed directly passes its own.
579
+ */
580
+ documentModels?: readonly DocumentModelModule<any>[] | (() => readonly DocumentModelModule<any>[]);
581
+ /**
582
+ * Signs the actions this client pushes, instead of the logged-in Renown user.
583
+ *
584
+ * Left out - the normal case - the signer is resolved per push from
585
+ * `window.ph.renown`, so a page signs as whoever is logged in and pushes
586
+ * unsigned when nobody is. Set it where there is no Renown to read: tests,
587
+ * scripts, and integration suites that must sign deterministically. A
588
+ * function is called per push, and pushes unsigned when it returns
589
+ * `undefined`.
590
+ */
591
+ signer?: ISigner | (() => ISigner | undefined);
592
+ /**
593
+ * Names the drive a call belongs to when the client cannot prove it itself,
594
+ * for its `Drive-Id` header; `undefined` sends none. Return only a drive id
595
+ * the caller knows: a Switchboard that does not own it answers 421. Where
596
+ * the client has proof of its own and the two disagree, the proof is sent.
597
+ */
598
+ driveIdFor?: (call: DriveIdCall) => string | undefined;
599
+ /**
600
+ * Bounds each HTTP request, headers through body, in milliseconds; a request
601
+ * past it rejects with a `TimeoutError`. Unset, requests are unbounded.
602
+ */
603
+ requestTimeoutMs?: number;
604
+ /**
605
+ * Bounds an `executeBatch` request in place of `requestTimeoutMs`. The
606
+ * mutation answers once its jobs are readable, and it has no form that does
607
+ * not wait, so one request lasts as long as the write does.
608
+ */
609
+ batchRequestTimeoutMs?: number;
610
+ /** The `fetch` every HTTP request goes through; the global one by default. */
611
+ fetch?: GraphQLFetch;
612
+ };
613
+ /**
614
+ * The marker {@link isGraphQLReactorClient} looks for.
615
+ *
616
+ * A page can end up with two copies of this module - an app that bundles a
617
+ * package carrying its own copy, or a dev server that hot-replaced it - and
618
+ * then `instanceof` compares an instance against the other copy's class object
619
+ * and answers `false`. A branded property survives both.
620
+ */
621
+ declare const graphQLReactorClientBrand: "__powerhouseGraphQLReactorClient";
622
+ /** The read half of {@link GraphQLReactorClient}: the hooks' reads plus `drives`. */
623
+ interface GraphQLReactorReadClient extends IReactorBrowserReadClient {
624
+ /** A drive's nodes from the node queries, for every drive type. */
625
+ readonly drives: IDriveReadClient;
626
+ }
627
+ /**
628
+ * A light implementation of {@link IReactorBrowserClient} that talks plain
629
+ * GraphQL to a Switchboard, with no reactor in the bundle.
630
+ *
631
+ * It fills the same `window.ph` slots the full in-browser reactor client fills,
632
+ * so the reactor-browser hooks cannot tell the two apart.
633
+ */
634
+ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
635
+ /** See {@link isGraphQLReactorClient}. */
636
+ readonly [graphQLReactorClientBrand] = true;
637
+ private readonly sdk;
638
+ /** For `executeBatch`, the one write a request waits for: see {@link batchRequestTimeoutMs}. */
639
+ private readonly batchSdk;
640
+ private readonly subgraphs;
641
+ private readonly listeners;
642
+ private readonly tokenProvider;
643
+ private readonly subscriptionsUrl;
644
+ private readonly documentModels;
645
+ private readonly resolveSigner;
646
+ private readonly driveIdFor;
647
+ private readonly undoRedoChains;
648
+ private stopRealtime;
649
+ private realtimeStarted;
650
+ private realtimeGeneration;
651
+ private realtimeErrorLogged;
652
+ /** Whether the last socket died because the Switchboard refused its credentials. */
653
+ private realtimeRefusedCredentials;
654
+ /** The socket write handles wait on; opened by the first stage wait. */
655
+ private jobSocket;
656
+ /** Set once the `jobChanges` subscription failed; stage waits then only poll. */
657
+ private jobRealtimeBroken;
658
+ /** Set once the Switchboard refused the `document` query's `consistency` argument. */
659
+ private consistencyUnsupported;
660
+ private readonly driveNodes;
661
+ /**
662
+ * The read half: the reads the hooks make. Every method is this client's
663
+ * own; nothing that writes is reachable from it.
664
+ */
665
+ readonly read: GraphQLReactorReadClient;
666
+ /**
667
+ * The write half. `execute` submits through `executeAsync` and hands back a
668
+ * handle whose `written` and `readable` resolve from `jobStatus`, woken by
669
+ * the `jobChanges` subscription when realtime is on, and whose `document()`
670
+ * runs the `document` query bounded by the receipt's token. `create` and
671
+ * `deleteDocument` have no asynchronous mutation: they run the synchronous
672
+ * ones and hand back a settled handle.
673
+ */
674
+ readonly write: IReactorBrowserWriteClient;
675
+ constructor(options: GraphQLReactorClientOptions);
676
+ /**
677
+ * The Switchboard's drive node queries as a node source, for every drive
678
+ * type. `read.drives` answers from it.
679
+ */
680
+ nodeSource(): IDriveNodeSource;
681
+ /**
682
+ * Reads a document. With a consistency token that names any coordinate, the
683
+ * Switchboard waits until its read models hold them; one without the
684
+ * `document` query's `consistency` argument is read without it, which after
685
+ * a write's `readable` stage still sees the write on a single node.
686
+ */
687
+ get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal, consistencyToken?: ConsistencyToken): Promise<TDocument>;
688
+ /**
689
+ * Reads documents by id, in the order given; throws if any is missing. Each
690
+ * chunk of {@link GET_MANY_CHUNK_SIZE} ids is one request holding an aliased
691
+ * `document` field per id, with the selection and arguments `get` sends.
692
+ */
693
+ getMany<TDocument extends PHDocument>(documentIds: string[], view?: ViewFilter, signal?: AbortSignal, consistencyToken?: ConsistencyToken): Promise<TDocument[]>;
694
+ /** One chunk of `getMany`, with the `consistency` argument while the Switchboard accepts it. */
695
+ private getDocumentChunk;
696
+ private runGetDocuments;
697
+ /**
698
+ * Whether the Switchboard would serve the document to this client's caller,
699
+ * from its `documentServed` query: the same read gate `find` passes. Absent
700
+ * or withheld is `false`; a failure to decide throws.
701
+ *
702
+ * A point-in-time view throws {@link GraphQLOperationNotSupportedError}, as
703
+ * does a Switchboard without the query.
704
+ */
705
+ isServed(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<boolean>;
706
+ getOperations(documentIdentifier: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
707
+ /**
708
+ * Filters documents by criteria over the Switchboard's `findDocuments` query.
709
+ *
710
+ * The query filters by `type` and `parentId` only, at head. A search naming
711
+ * `ids` or `slugs` (present, whatever its length) and a point-in-time view are
712
+ * each by-contract limitations the query cannot express -- running it anyway
713
+ * would return every document instead of the named ones, or head instead of
714
+ * the asked-for revision, a silently wrong answer. {@link findIsServableOverGraphQL}
715
+ * is the single predicate that decides this, and an unservable `find` throws
716
+ * {@link GraphQLOperationNotSupportedError}. Drive enumeration itself filters
717
+ * by `type` at head, which is served.
718
+ */
719
+ find<TDocument extends PHDocument = PHDocument>(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<TDocument>>;
720
+ getOutgoingRelationships(sourceIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
721
+ getIncomingRelationships(targetIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
722
+ getOutgoingRelationshipEdges(sourceIdentifier: string, relationshipType?: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
723
+ getIncomingRelationshipEdges(targetIdentifier: string, relationshipType?: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
724
+ create<TDocument extends PHDocument = PHDocument>(document: PHDocument, parentIdentifier?: string, signal?: AbortSignal): Promise<TDocument>;
725
+ /**
726
+ * Pushes actions to the Switchboard and returns the updated document.
727
+ *
728
+ * The document is fetched first: the response is the baseline for the
729
+ * `sinceRevision` filter that narrows the returned operations to the ones
730
+ * this call appended, and it carries the state hash a signed action is
731
+ * stamped with.
732
+ *
733
+ * The emitted `Updated` event carries the document's id, never the
734
+ * identifier this was called with: subscribers - including `DocumentCache` -
735
+ * work in id space.
736
+ *
737
+ * `IReactorClient.execute`'s trailing `subject` is deliberately not accepted
738
+ * here. It names the subject a local read gate answers as, and this client
739
+ * runs no gate: the Switchboard decides what to serve from the bearer on the
740
+ * request. Declaring it would suggest a per-call choice that does not exist.
741
+ */
742
+ execute<TDocument extends PHDocument>(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<TDocument>;
743
+ /**
744
+ * What `execute` writes, without waiting: returns the job once the Switchboard
745
+ * holds it, so a write slower than one request's deadline still lands and is
746
+ * reported. It is announced as the write half's `execute` announces it.
747
+ */
748
+ executeAsync(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<JobInfo>;
749
+ /**
750
+ * Undoes the last applied operation of `scope` under this client's own
751
+ * signature: UNDO below base-reducer 3; on it, a RETRACT of the target the
752
+ * Switchboard resolves with {@link undoRedoTargets}. One at a time per
753
+ * document, scope and branch. A stale target is refused, not re-resolved.
754
+ */
755
+ undo<TDocument extends PHDocument = PHDocument>(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<TDocument>;
756
+ /** Redoes the last undo of `scope`; see {@link undo}. */
757
+ redo<TDocument extends PHDocument = PHDocument>(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<TDocument>;
758
+ /** Exact on base-reducer 3, from the targets the Switchboard resolves. */
759
+ undoRedoAvailability(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<UndoRedoAvailability>;
760
+ /**
761
+ * The rows a base-reducer 3 undo and redo would retract, resolved by the
762
+ * Switchboard as the caller. A Switchboard without the query is refused
763
+ * with {@link GraphQLOperationNotSupportedError}. `view.subject` is not
764
+ * sent: the Switchboard reads the caller from the bearer.
765
+ */
766
+ undoRedoTargets(documentIdentifier: string, scope?: string, view?: ViewFilter, signal?: AbortSignal): Promise<UndoRedoTargets>;
767
+ private undoOrRedo;
768
+ /** An older Switchboard serves no header versions; then CREATE_DOCUMENT names them, else it is 1. */
769
+ private undoCapabilities;
770
+ /**
771
+ * Runs multiple mutation jobs in dependency order over the Switchboard's
772
+ * `executeBatch` mutation and waits for all to settle, returning the result
773
+ * shaped like `IReactor.executeBatch`'s so the reference `DriveClient`
774
+ * consumes it unchanged.
775
+ *
776
+ * Not atomic: each job commits on its own and a failed job still releases
777
+ * its dependents. A FAILED job throws {@link BatchJobFailedError}, naming the
778
+ * first failed plan key and carrying every job's final state.
779
+ *
780
+ * Each job's actions are signed independently for the job's own
781
+ * `(documentId, branch)` target -- the per-action signing the reactor's own
782
+ * `signActions` does, not the batch state-prediction `execute` uses for a
783
+ * multi-action push. A drive job such as `addFile`'s is `CREATE_DOCUMENT` +
784
+ * `UPGRADE_DOCUMENT` + `ADD_RELATIONSHIP`, which the prediction path rejects
785
+ * outright and which has no fetchable baseline to stamp against. The reactor
786
+ * records but does not verify the stamped previous-state head, so signing
787
+ * each action bare is exactly what the in-process `DriveClient` relies on.
788
+ *
789
+ * The mutation is synchronous server-side: a job it returns is already
790
+ * settled, so {@link waitForJob} resolves from it without polling.
791
+ */
792
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal): Promise<BatchExecutionResult>;
793
+ /** The job as `jobStatus` reports it now; `undefined` when it reports none. */
794
+ getJob(jobId: string, signal?: AbortSignal): Promise<JobInfo | undefined>;
795
+ /** The job as `jobStatus` reports it now; throws when it reports none. */
796
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
797
+ /** Polls `jobStatus` until the job is READ_READY or FAILED. */
798
+ waitForJob(jobOrId: string | JobInfo, signal?: AbortSignal): Promise<JobInfo>;
799
+ /** See {@link readCreateSignaturePolicy}. */
800
+ getCreateSignaturePolicy(): Promise<SignaturePolicy>;
801
+ /** See {@link readCreateProtocolVersions}; fitted to `documentModels`. */
802
+ getCreateProtocolVersions(options: CreateProtocolVersionsOptions, signal?: AbortSignal): Promise<ProtocolVersions>;
803
+ /** See {@link IReactorClient.newDocument}; the module comes from `documentModels`. */
804
+ newDocument<TDocument extends PHDocument = PHDocument>(documentType: string, options?: NewDocumentOptions, signal?: AbortSignal): Promise<TDocument>;
805
+ /**
806
+ * Sets or, with `null`, clears the preferred editor as a client-signed
807
+ * action, as the in-process client does.
808
+ */
809
+ setPreferredEditor(documentIdentifier: string, preferredEditor: string | null, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
810
+ /** The `Drive-Id` header for a call: the client's own proof, else the hook's. */
811
+ private driveIdHeaders;
812
+ /**
813
+ * Emits the changes the batch's settled jobs made, as `create` and `execute`
814
+ * do, so a cache is invalidated without a realtime socket. The documents a
815
+ * job wrote to are its own and those its consistency token names.
816
+ */
817
+ private announceBatch;
818
+ /**
819
+ * The id a job's actions are signed for: a signature covers the document id,
820
+ * and the server resolves a slug before verifying. A document created by this
821
+ * job or an earlier one is named by its id. When the server has no such
822
+ * document the identifier is used as given, and the server decides; any
823
+ * other failure to read it throws, so nothing is signed for a slug.
824
+ */
825
+ private batchWriteTarget;
826
+ /**
827
+ * Signs one batch job's actions for the job's own log.
828
+ *
829
+ * Each action is signed on its own for `(documentId, branch)`, the same
830
+ * per-action signing the reactor's `signActions` does: no state prediction
831
+ * across the job, so a job carrying a `CREATE_DOCUMENT` the push-prediction
832
+ * path rejects still signs. An action already signed under a key is left
833
+ * as it is: the reference `DriveClient` signs its jobs before handing them
834
+ * here. With no signer the actions pass through unsigned, matching
835
+ * {@link execute}.
836
+ */
837
+ private signBatchJobActions;
838
+ /**
839
+ * Deletes a document and announces it as a `Deleted` event.
840
+ *
841
+ * Pass a document id. The server resolves a slug just as happily, but
842
+ * `deleteDocument` returns a boolean - there is no document left to read an
843
+ * id off - so the identifier is announced verbatim on `context.childId`. A
844
+ * subscriber keyed by id, `DocumentCache` included, therefore only reacts to
845
+ * a delete by id.
846
+ */
847
+ deleteDocument(identifier: string, propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
848
+ /**
849
+ * Registers a change subscriber and returns its unsubscribe function.
850
+ *
851
+ * Two things produce the events delivered here. Every successful `create`,
852
+ * `execute` and `deleteDocument` emits one, which is what makes a
853
+ * `DocumentCache` built on this client invalidate after a dispatch. And,
854
+ * unless realtime is switched off, the first call to this method opens a
855
+ * websocket to the Switchboard and every change it reports - from another
856
+ * user, another tab or a server-side processor - is emitted too. A write of
857
+ * this client's own is therefore announced twice, once locally and once by
858
+ * the server; the cache refetches twice, which is harmless.
859
+ *
860
+ * A websocket that cannot be opened or is refused is logged once and then
861
+ * ignored: realtime is an enhancement, never a dependency. The failed socket
862
+ * is closed, so the next subscriber to arrive tries again.
863
+ *
864
+ * `view` is accepted for interface compatibility and ignored: the emitted
865
+ * documents are whatever the write returned, so there is nothing to re-scope.
866
+ *
867
+ * Events live in id space: `search.ids` is matched against the resolved
868
+ * document id, never against the identifier the write was issued with. The
869
+ * one exception is `deleteDocument`, which has no document to resolve an id
870
+ * from - see its own note. A `DocumentCache` on this client must therefore
871
+ * be read by id: a slug-keyed entry is never invalidated.
872
+ */
873
+ subscribe(search: SearchFilter, callback: (event: DocumentChangeEvent) => void, view?: ViewFilter): () => void;
874
+ /**
875
+ * Closes the realtime socket, if one was opened.
876
+ *
877
+ * Registered subscribers are left in place: they still receive the events
878
+ * this client produces itself.
879
+ *
880
+ * Disposing is NOT final - a later `subscribe` opens a new socket. React
881
+ * remounts a tree by running an effect's cleanup and then the effect again,
882
+ * on the same client, and `StrictMode` does exactly that on every mount; a
883
+ * terminal flag here would leave those pages without realtime for good, with
884
+ * nothing logged.
885
+ */
886
+ dispose(): void;
887
+ /**
888
+ * Binds a project's generated SDK to this client's transport and auth.
889
+ *
890
+ * Subgraphs are served next to the reactor's own supergraph, so the endpoint
891
+ * is derived from the client's `url` by appending the name, and the SDK is
892
+ * handed the same auth middleware every reactor call goes through. An app
893
+ * therefore configures one URL and one token provider, and reaches every
894
+ * capability of its Switchboard through this one client.
895
+ *
896
+ * `getSdk` is the function a GraphQL code generator emits for the subgraph's
897
+ * schema - see the README in this folder for the codegen recipe.
898
+ *
899
+ * Transport and typing only. Subgraph results are not cached, produce no
900
+ * change events and never reach `useDocument`.
901
+ */
902
+ subgraph<TSdk>(name: string, getSdk: SubgraphSdkFactory<TSdk>): TSdk;
903
+ /**
904
+ * Runs a one-off GraphQL document against the Switchboard's own endpoint,
905
+ * through the same transport and auth as everything else.
906
+ *
907
+ * The escape hatch for an operation not worth generating an SDK for. Pass a
908
+ * document a code generator typed and the result type follows; pass a plain
909
+ * `gql` document or a string and name the result type at the call site.
910
+ */
911
+ request<TResult = unknown, TVariables extends Variables = Variables>(document: TypedGraphQLDocument<TResult, TVariables> | string, variables?: TVariables, options?: GraphQLRequestOptions): Promise<TResult>;
912
+ /**
913
+ * Shapes a document result page into the reactor's {@link PagedResults}.
914
+ *
915
+ * The items carry the same `PHDocumentFields` fragment as `get`, so the same
916
+ * adapter rebuilds each one. `hasNextPage` gates the cursor exactly as
917
+ * `getOperations` does: no cursor means no `next`.
918
+ */
919
+ private toDocumentResults;
920
+ /**
921
+ * Shapes a relationship-edge result page into the reactor's
922
+ * {@link PagedResults}, restoring each edge's `Date` fields.
923
+ */
924
+ private toRelationshipResults;
925
+ /**
926
+ * The write half's `execute`: signs as the facade's `execute` does, submits
927
+ * through `executeAsync` and returns once the job is accepted. When anyone
928
+ * subscribes, the document is read back once the job is readable and
929
+ * announced as `Updated`, as the facade's `execute` announces it; the handle
930
+ * shares that read with its own `document()`.
931
+ */
932
+ private submitExecute;
933
+ /** The write half's `create`: the synchronous mutation, a settled handle. */
934
+ private submitCreate;
935
+ /** The write half's `deleteDocument`: the synchronous mutation, a settled handle. */
936
+ private submitDeleteDocument;
937
+ /** Reads a write's document back, bounded by its receipt's token. */
938
+ private handleReader;
939
+ /** Announces a write's document as `Updated` once it is readable. */
940
+ private announceWrite;
941
+ /**
942
+ * Waits for a job to settle a stage, resolving with a FAILED job too. Polls
943
+ * `jobStatus` with a doubling interval; with realtime on, a `jobChanges`
944
+ * event for the job wakes the wait early and the interval is only a safety
945
+ * net. A failed subscription is logged once and the wait keeps polling.
946
+ */
947
+ private waitForStage;
948
+ /**
949
+ * Subscribes to one job's `jobChanges` when realtime is on and the
950
+ * subscription has not failed before. Returns the stop function, or
951
+ * undefined when nothing was subscribed.
952
+ */
953
+ private watchJob;
954
+ /**
955
+ * The `document` query with the `consistency` argument, or without it once
956
+ * the Switchboard has refused the argument.
957
+ */
958
+ private getDocumentAtConsistency;
959
+ /**
960
+ * Opens the realtime socket on the first subscriber.
961
+ *
962
+ * The subscription is a firehose - no `search` argument - and this client
963
+ * applies each subscriber's own filter on the way out, exactly as it does for
964
+ * its own emissions.
965
+ */
966
+ private startRealtime;
967
+ /**
968
+ * Gives up on a failed socket so that a later subscriber can try again.
969
+ *
970
+ * `graphql-ws` retries on its own and only reports here once it has given up,
971
+ * or once the Switchboard refused the credentials the socket carried - which
972
+ * `shouldRetry` declines to retry at all. Keeping the dead stop function
973
+ * would make every later `subscribe` a no-op, so realtime would stay off for
974
+ * the life of the page even after the user signs in.
975
+ *
976
+ * Why it died is recorded: a refusal is undone by a credential change and
977
+ * nothing else, and {@link notifyCredentialsChanged} acts only on that.
978
+ *
979
+ * The generation stamp discards a report from a socket that has already been
980
+ * replaced or disposed.
981
+ */
982
+ private handleRealtimeFailure;
983
+ /**
984
+ * Reopens realtime after a sign-in, a sign-out or a token swap.
985
+ *
986
+ * Call it whenever the credentials this client authenticates with change.
987
+ *
988
+ * A live socket is replaced. `connectionParams` are resolved once, when the
989
+ * socket opens, so a socket keeps presenting the credentials it was opened
990
+ * with until something closes it - and a sign-out closes nothing. That left
991
+ * a signed-out tab still receiving the previous identity's document changes,
992
+ * on a shared machine, for as long as the socket happened to survive.
993
+ *
994
+ * A refused socket is reopened, for the same reason from the other side:
995
+ * otherwise it stays closed until an unrelated component happens to
996
+ * `subscribe`, so signing in leaves realtime off with nothing said - the
997
+ * state `handleRealtimeFailure` resets to avoid.
998
+ *
999
+ * A socket that died for any other reason is left alone: a network failure
1000
+ * is not something a new token fixes, and reopening one here would turn a
1001
+ * credential change into a reconnect loop.
1002
+ */
1003
+ notifyCredentialsChanged(): void;
1004
+ /** Closes the socket and lets a later subscriber open a new one. */
1005
+ private teardownRealtime;
1006
+ /** Maps a server event onto the client-side event and emits it. */
1007
+ private emitServerEvent;
1008
+ /**
1009
+ * Reports a broken realtime socket once per client, however many sockets it
1010
+ * goes through.
1011
+ *
1012
+ * `graphql-ws` retries on its own, and a Switchboard without a websocket
1013
+ * endpoint would otherwise fill the console for as long as the page is open.
1014
+ */
1015
+ private logRealtimeError;
1016
+ /**
1017
+ * Delivers an event to every matching subscriber.
1018
+ *
1019
+ * A subscriber that throws is logged and skipped so one bad listener cannot
1020
+ * stop the others from being notified.
1021
+ */
1022
+ private emitChange;
1023
+ }
1024
+ /** {@link GraphQLReactorClient.nodeSource}, as a function. */
1025
+ declare function createGraphQLDriveNodeSource(client: GraphQLReactorClient): IDriveNodeSource;
1026
+ /**
1027
+ * Whether a value is a {@link GraphQLReactorClient}, including one built by
1028
+ * another copy of this module.
1029
+ *
1030
+ * Use this rather than `instanceof`: the brand it tests for is shared by every
1031
+ * copy of the class, so a client built by a hot-replaced module or by a package
1032
+ * that bundled its own copy is still recognised.
1033
+ */
1034
+ declare function isGraphQLReactorClient(client: unknown): client is GraphQLReactorClient;
1035
+ /**
1036
+ * Maps a reactor `ViewFilter` onto the GraphQL `ViewFilterInput`.
1037
+ *
1038
+ * Point-in-time reads are rejected: the Switchboard read API has no revision
1039
+ * argument, so silently returning the head state would be wrong.
1040
+ */
1041
+ declare function viewFilterInputFromViewFilter(view?: ViewFilter): ViewFilterInput | undefined;
1042
+ /**
1043
+ * The single source of truth for whether the Switchboard `findDocuments` query
1044
+ * can serve a `find`. It is servable iff the search names neither `ids` nor
1045
+ * `slugs` (present, regardless of length) AND the view is not point-in-time:
1046
+ * each is a by-contract limitation of a surface that filters only by
1047
+ * `type`/`parentId` at head. Exported so a caller can route around an
1048
+ * unservable search instead of catching the error `find` throws for it.
1049
+ */
1050
+ declare function findIsServableOverGraphQL(search: SearchFilter, view?: ViewFilter): boolean;
1051
+ /** Resolves the signer of the logged-in user, if there is one. */
1052
+ /** The logged-in Renown user's signer, read per call; none when nobody is. */
1053
+ declare function ambientRenownSigner(): ISigner | undefined;
1054
+ //#endregion
1055
+ //#region src/graphql-client/graphql-reactor-provider.d.ts
1056
+ declare global {
1057
+ interface Window {
1058
+ /** Set by {@link ensurePHEventHandlers}; see its doc comment. */
1059
+ __phEventHandlersRegistered?: boolean;
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Registers the `window.ph` event handlers once per page.
1064
+ *
1065
+ * The `set*` helpers only dispatch CustomEvents - nothing writes `window.ph`
1066
+ * until `addPHEventHandlers` has registered the listeners that do. Registration
1067
+ * is guarded by a marker on `window` rather than a module-level flag so that a
1068
+ * hot module replacement, or two copies of this module, still register once.
1069
+ */
1070
+ declare function ensurePHEventHandlers(): void;
1071
+ type GraphQLReactorProviderProps = {
1072
+ /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */
1073
+ url: string;
1074
+ /**
1075
+ * Resolves the bearer token sent with every request, per request. Defaults to
1076
+ * the token of the logged-in Renown user, or none when nobody is logged in.
1077
+ */
1078
+ tokenProvider?: GraphQLReactorClientOptions["tokenProvider"];
1079
+ /**
1080
+ * The Switchboard GraphQL subscriptions endpoint, e.g.
1081
+ * `ws://localhost:4001/graphql/subscriptions`. Defaults to the endpoint
1082
+ * derived from `url`.
1083
+ */
1084
+ subscriptionsUrl?: GraphQLReactorClientOptions["subscriptionsUrl"];
1085
+ /**
1086
+ * Whether server-pushed changes are delivered. On by default; set it to
1087
+ * `false` where there is no websocket to talk to.
1088
+ */
1089
+ realtime?: GraphQLReactorClientOptions["realtime"];
1090
+ /**
1091
+ * The attachment service the editors below this provider read attachments
1092
+ * through, published into the same `window.ph` slot Connect publishes it in.
1093
+ *
1094
+ * The app constructs it: attachments are a separate package, and which
1095
+ * storage an app talks to is the app's business. Leave it out and the slot
1096
+ * stays empty, exactly as it is without this provider.
1097
+ */
1098
+ attachmentService?: PHGlobal$1["attachmentService"];
1099
+ /**
1100
+ * The document model modules the app works with, imported from its generated
1101
+ * package's `document-models` SUBPATH:
1102
+ *
1103
+ * ```tsx
1104
+ * import { TodoV1, TodoV2 } from "my-models/document-models";
1105
+ * <GraphQLReactorProvider url={url} documentModels={[TodoV1, TodoV2]}>
1106
+ * ```
1107
+ *
1108
+ * Wrapped via {@link packageFromDocumentModels} and published through a
1109
+ * {@link StaticPackageManager} into the same `window.ph.vetraPackageManager`
1110
+ * slot Connect fills, so `useDocumentModelModules` and
1111
+ * `useDocumentModelModuleById` work below this provider.
1112
+ *
1113
+ * Modules only, deliberately - not whole packages. Editors are not portable
1114
+ * outside Connect yet (they read the selected document from Connect's
1115
+ * drive/node selection) and would inflate the bundle; a light app that needs
1116
+ * an editor imports the React component directly.
1117
+ *
1118
+ * Import from the `document-models` subpath, never from the package ROOT:
1119
+ * the root entry also exports the package's `processorFactory`, and module
1120
+ * resolution happens before tree-shaking, so a root import drags processor
1121
+ * (server-side) code into the browser bundle and can break the build.
1122
+ *
1123
+ * They are also what lets the client SIGN a batch of two or more actions:
1124
+ * signing the second action needs the state the first one leaves behind, and
1125
+ * only the document's own reducer can predict it, so a batch is signable only
1126
+ * while the module matching the document's type and exact version is here.
1127
+ * Single actions are signed without any of this.
1128
+ *
1129
+ * Optional on purpose: a light app may equally ship NO modules and let the
1130
+ * Switchboard own the model entirely - both modes are supported.
1131
+ *
1132
+ * Like `url`, this is read once, when the client is built.
1133
+ */
1134
+ documentModels?: readonly DocumentModelModule<any>[];
1135
+ children: ReactNode;
1136
+ };
1137
+ /**
1138
+ * Mounts a {@link GraphQLReactorClient} into the `window.ph` slots the
1139
+ * reactor-browser hooks read, so `useDocument`, `useDispatch` and
1140
+ * `useReactorClient` work below it against a Switchboard, with no reactor in
1141
+ * the bundle.
1142
+ *
1143
+ * It fills the document slots, plus `window.ph.vetraPackageManager` when
1144
+ * `documentModels` is given (a fixed {@link StaticPackageManager}, which makes
1145
+ * the document-model hooks work). The same modules go to the client itself, so
1146
+ * a dispatch of two or more actions is signed rather than refused.
1147
+ * `window.ph.reactorClientModule` always stays empty, so full-reactor surfaces
1148
+ * (drives, jobs, editor auto-discovery) find nothing - an app below this
1149
+ * provider renders components it imports itself.
1150
+ *
1151
+ * The client is built on the client only: on the server the slots stay empty
1152
+ * and the hooks report their normal loading states. The props are read once,
1153
+ * when the client is built - changing `url` afterwards does not rebuild it.
1154
+ *
1155
+ * The effect's cleanup disposes the cache and the client's socket, and the
1156
+ * effect rebuilds both if it runs again on the same client - which is what a
1157
+ * `StrictMode` mount does.
1158
+ */
1159
+ declare function GraphQLReactorProvider({ url, tokenProvider, subscriptionsUrl, realtime, attachmentService, documentModels, children }: GraphQLReactorProviderProps): import("react/jsx-runtime").JSX.Element;
1160
+ /**
1161
+ * Returns the {@link GraphQLReactorClient} mounted by
1162
+ * {@link GraphQLReactorProvider}, or `undefined` when the slot holds something
1163
+ * else - the full in-browser reactor client, or nothing yet.
1164
+ *
1165
+ * `useReactorClient` is typed as the narrow `IReactorBrowserClient` subset both
1166
+ * implementations share. This is how a component reaches the light client's own
1167
+ * surface, i.e. `subgraph` and `request`.
1168
+ *
1169
+ * The narrowing is by brand, not by `instanceof`: a page can carry two copies
1170
+ * of this module - a bundled package with its own copy, or a hot-replaced one -
1171
+ * and `instanceof` would then answer `false` for a perfectly good client and
1172
+ * leave the component silently without one.
1173
+ */
1174
+ declare function useSwitchboardClient(): GraphQLReactorClient | undefined;
1175
+ //#endregion
1176
+ //#region src/graphql-client/operations.d.ts
1177
+ /**
1178
+ * The operation selection of `GetDocumentOperations`, lifted into a fragment so
1179
+ * the write path can reuse `remoteOperationToLocal` on the items it selects.
1180
+ */
1181
+ declare const ReactorOperationFieldsFragmentDoc: import("graphql").DocumentNode;
1182
+ /**
1183
+ * `mutateDocument` plus the operations the mutation produced.
1184
+ *
1185
+ * The generated `MutateDocument` only selects the document fields, but
1186
+ * `dispatchActions` reads per-action failures out of `result.operations[scope]`
1187
+ * (`src/actions/dispatch.ts`), so the reducer-level errors would be lost.
1188
+ *
1189
+ * The operations filter keeps the extra selection to the operations this call
1190
+ * could have appended rather than the whole history. All three of its fields
1191
+ * matter:
1192
+ * - `sinceRevision` is the lowest head revision across the targeted scopes, so
1193
+ * it is only a safe window when the selection is scope-limited as well;
1194
+ * - `scopes` limits the response to the scopes the pushed actions target,
1195
+ * without it the server walks every scope of the document
1196
+ * (`packages/reactor/src/core/reactor.ts` `getOperations`);
1197
+ * - `branch` selects the branch the operations are read from, and is the same
1198
+ * variable the mutation writes to. It used to be two - the write went through
1199
+ * a `view`, the filter took its own `branch` - and they had to be kept equal
1200
+ * by hand or the operations came from `main` while the actions were applied
1201
+ * elsewhere. One variable cannot disagree with itself.
1202
+ */
1203
+ declare const MutateDocumentWithOperationsDocument: import("graphql").DocumentNode;
1204
+ type MutateDocumentWithOperationsVariables = {
1205
+ documentIdentifier: Scalars["String"]["input"];
1206
+ actions: ReadonlyArray<ActionInput>;
1207
+ sinceRevision?: Scalars["Int"]["input"];
1208
+ scopes?: ReadonlyArray<Scalars["String"]["input"]>;
1209
+ branch?: Scalars["String"]["input"];
1210
+ };
1211
+ type MutateDocumentWithOperationsResult = {
1212
+ readonly mutateDocument: PhDocumentFieldsFragment & {
1213
+ readonly operations?: {
1214
+ readonly items: ReadonlyArray<RemoteOperation>;
1215
+ } | null;
1216
+ };
1217
+ };
1218
+ /**
1219
+ * `document`, bounded by a consistency token: the read waits until the
1220
+ * Switchboard's read models hold every operation the token names. The
1221
+ * `consistency` argument is additive on the Switchboard; one without it refuses
1222
+ * this document, and the client falls back to the plain `GetDocument`.
1223
+ */
1224
+ declare const GetDocumentAtConsistencyDocument: import("graphql").DocumentNode;
1225
+ type GetDocumentAtConsistencyVariables = {
1226
+ identifier: Scalars["String"]["input"];
1227
+ view?: ViewFilterInput;
1228
+ consistency: {
1229
+ version: number;
1230
+ createdAtUtcIso: string;
1231
+ coordinates: ReadonlyArray<{
1232
+ documentId: string;
1233
+ scope: string;
1234
+ branch: string;
1235
+ operationIndex: number;
1236
+ }>;
1237
+ };
1238
+ };
1239
+ type GetDocumentAtConsistencyResult = {
1240
+ readonly document?: {
1241
+ readonly document: PhDocumentFieldsFragment;
1242
+ readonly childIds: ReadonlyArray<string>;
1243
+ } | null;
1244
+ };
1245
+ //#endregion
1246
+ //#region src/graphql-client/signing.d.ts
1247
+ /**
1248
+ * Stamps an action with the head of the scope it targets.
1249
+ *
1250
+ * `prevOpHash` is the hash of the scope state the action is meant to apply to;
1251
+ * for a document at head that is the hash of the last operation in the scope,
1252
+ * which the read path cannot fetch, so it is recomputed from the state.
1253
+ * `prevOpIndex` is the index of that last operation: revisions count
1254
+ * operations and indices are zero based, so an empty scope stamps `-1`, which
1255
+ * matches what the remote controller records.
1256
+ *
1257
+ * `revision` overrides the scope revision the index is derived from. Only a
1258
+ * batch needs it - {@link prepareSignedActions} stamps action N at the revision
1259
+ * the N actions before it will have produced, which the document itself does
1260
+ * not know yet. `prevOpHash` always comes from the supplied document's state.
1261
+ */
1262
+ declare function stampAction(action: Action$1, document: PHDocument$1, revision?: number): Action$1;
1263
+ /**
1264
+ * Signs a stamped action for `target`, keeping any signatures it already
1265
+ * carries. The signer reads `context.prevOpHash`, so this runs after
1266
+ * {@link stampAction}. A v2 tuple covers the signer's identity, so the context
1267
+ * takes the signer's user and app even when the action named others.
1268
+ */
1269
+ declare function signStampedAction(action: Action$1, signer: ISigner, target: ActionSigningTarget, signal?: AbortSignal): Promise<Action$1>;
1270
+ /**
1271
+ * Stamps and signs a batch of actions against one document snapshot, so every
1272
+ * action carries the head its predecessor will leave behind.
1273
+ *
1274
+ * The server executes the array in order, each action against the state the one
1275
+ * before it produced. The snapshot the light client reads has correct state and
1276
+ * per-scope revisions but NO operation history (see `adapter.ts`), so the chain
1277
+ * is predicted here: reduce action N over the working document to get the state
1278
+ * action N+1 hashes, and carry a virtual revision alongside it. The revision has
1279
+ * to be tracked separately because the reducer derives operation indices from
1280
+ * the last stored operation, and with an empty history that counts from zero
1281
+ * rather than from the document's real revision.
1282
+ *
1283
+ * A single action needs no prediction and therefore no `module`, which keeps
1284
+ * today's callers working unchanged. Two or more require the document's exact
1285
+ * reducer, one shared scope (the reactor rejects mixed-scope jobs) and only
1286
+ * append-only actions. Anything else rejects: a batch that cannot be predicted
1287
+ * must fail before the mutation, never be downgraded to unsigned.
1288
+ */
1289
+ declare function prepareSignedActions(actions: readonly Action$1[], snapshot: PHDocument$1, signer: ISigner, module?: DocumentModelModule$1<any>, signal?: AbortSignal): Promise<Action$1[]>;
1290
+ //#endregion
1291
+ //#region src/graphql-client/static-package-manager.d.ts
1292
+ /**
1293
+ * A fixed set of packages presented through the `IPackageManager` interface,
1294
+ * so the package-derived hooks - `useDocumentModelModules`,
1295
+ * `useDocumentModelModuleById`, `useEditorModules`, `useVetraPackages` - work
1296
+ * below `GraphQLReactorProvider` exactly as they do below Connect.
1297
+ *
1298
+ * Connect's package manager installs, updates and removes packages at runtime.
1299
+ * A light app instead declares its packages once, as code it imports itself
1300
+ * (every generated package root exports `manifest`, `documentModels`, `editors`
1301
+ * and `upgradeManifests` by name), so every mutating member throws and
1302
+ * `subscribe` never emits. For hand-picked modules without package artifacts,
1303
+ * {@link packageFromDocumentModels} wraps them in one synthetic package.
1304
+ */
1305
+ declare class StaticPackageManager implements IPackageManager {
1306
+ readonly registryUrl: null;
1307
+ readonly packages: DocumentModelLib[];
1308
+ constructor(packages: readonly DocumentModelLib<any>[]);
1309
+ /**
1310
+ * Resolves a module by document type across all packages. Mirrors the
1311
+ * registry's semantics (`IDocumentModelRegistry.getModule`): the LATEST
1312
+ * version wins, with `version ?? 1` as each module's default.
1313
+ */
1314
+ load(documentType: string): Promise<DocumentModelSource>;
1315
+ subscribe(_handler: IPackagesListener): IPackageListerUnsubscribe;
1316
+ getPackageSource(_packageName: string): RegistryPackageSource | null;
1317
+ getPackageVersion(_packageName: string): string | undefined;
1318
+ getPackageSpec(_packageName: string): string | undefined;
1319
+ getRegistryPackages(): {
1320
+ name: string;
1321
+ version: string | undefined;
1322
+ }[];
1323
+ addPackage(_packageName: string): PackageManagerInstallResult;
1324
+ addPackages(_packageNames: string[]): PackageManagerInstallResult[];
1325
+ removePackage(_name: string): void;
1326
+ updateLocalPackage(_pkg: DocumentModelLib, _version?: string): void;
1327
+ addLocalPackage(_name: string, _loadedPackage: DocumentModelLib, _version?: string): void;
1328
+ }
1329
+ /**
1330
+ * Resolves one document-model module out of a flat module list, with the same
1331
+ * rule the reactor registry uses (`IDocumentModelRegistry.getModule`, at
1332
+ * packages/reactor/src/registry/implementation.ts): with a `version`, only an
1333
+ * EXACT `version ?? 1` match resolves; without one, the LATEST version wins.
1334
+ *
1335
+ * Signing an existing document needs the exact rule. A document carries the
1336
+ * model version it was written with in `state.document.version`, and its
1337
+ * reducer is the only one whose operations that document's history can accept -
1338
+ * so "latest" is correct only when no version is asked for.
1339
+ *
1340
+ * Pure and dependency-free on purpose: this is reachable from the browser
1341
+ * entry, so it must not pull the reactor registry in as a value.
1342
+ */
1343
+ declare function resolveDocumentModelModule(modules: readonly DocumentModelModule<any>[], documentType: string, version?: number): DocumentModelModule<any>;
1344
+ /**
1345
+ * Wraps hand-picked modules in one synthetic `DocumentModelLib`, for apps that
1346
+ * assemble their model list from mixed sources instead of passing whole
1347
+ * packages. The manifest is fabricated - loose modules carry none - so prefer
1348
+ * the `packages` prop with the real package exports when you have them: a real
1349
+ * package also carries `editors`, which makes the editor hooks work.
1350
+ */
1351
+ declare function packageFromDocumentModels(documentModels: readonly DocumentModelModule<any>[]): DocumentModelLib;
1352
+ //#endregion
1353
+ //#region src/graphql-client/subscriptions.d.ts
1354
+ /** The `documentChanges` payload, exactly as the Switchboard sends it. */
1355
+ type DocumentChangesEventPayload = DocumentChangesSubscription["documentChanges"];
1356
+ /** The connection payload sent with the `ConnectionInit` message. */
1357
+ type ConnectionParams = Record<string, string>;
1358
+ type DocumentChangesSubscriptionOptions = {
1359
+ /** The websocket endpoint, e.g. `ws://localhost:4001/graphql/subscriptions`. */
1360
+ wsUrl: string;
1361
+ /**
1362
+ * Resolves the `ConnectionInit` payload. Called again on every reconnect, so
1363
+ * a token that expired while the socket was down is refreshed on the way back
1364
+ * up.
1365
+ */
1366
+ connectionParams?: () => Promise<ConnectionParams>;
1367
+ /** Called once per server event. */
1368
+ onEvent: (event: DocumentChangesEventPayload) => void;
1369
+ /**
1370
+ * Called when the socket gives up: the retries built into `graphql-ws` are
1371
+ * exhausted, or the server rejected the subscription. Realtime is an
1372
+ * enhancement, so callers are expected to log and carry on.
1373
+ */
1374
+ onError: (error: unknown) => void;
1375
+ };
1376
+ /**
1377
+ * Whether a socket failure is the Switchboard refusing the credentials sent.
1378
+ *
1379
+ * Keyed on the close reason, not the code: both refusals close 4403, because
1380
+ * `connectionParams` is resolved per connect and a reconnect carrying a fresh
1381
+ * token genuinely succeeds. What the reason adds is that *this* attempt cannot
1382
+ * be fixed by repeating it.
1383
+ */
1384
+ declare function isAuthRefusalClose(error: unknown): boolean;
1385
+ /**
1386
+ * Opens one `documentChanges` subscription and feeds every event to `onEvent`.
1387
+ *
1388
+ * The subscription is a firehose: no `search` argument, so the server sends
1389
+ * every change the connection is allowed to see and the caller filters. This is
1390
+ * the only module that knows about `graphql-ws`.
1391
+ *
1392
+ * Returns the stop function, which cancels the subscription and closes the
1393
+ * socket. It is safe to call more than once.
1394
+ */
1395
+ declare function startDocumentChangesSubscription(options: DocumentChangesSubscriptionOptions): () => void;
1396
+ /** The `jobChanges` payload, exactly as the Switchboard sends it. */
1397
+ type JobChangesEventPayload = JobChangesSubscription["jobChanges"];
1398
+ /**
1399
+ * One socket carrying `jobChanges` subscriptions, one per watched job. The
1400
+ * socket opens on the first watch and closes when nothing is watched.
1401
+ */
1402
+ interface IJobChangesSocket {
1403
+ /**
1404
+ * Watches one job. `onEvent` is called per status change the Switchboard
1405
+ * reports; `onError` once if the subscription fails. Returns the stop
1406
+ * function, safe to call more than once.
1407
+ */
1408
+ watch(jobId: string, onEvent: (event: JobChangesEventPayload) => void, onError: (error: unknown) => void): () => void;
1409
+ /** Closes the socket; a later watch opens a new one. */
1410
+ dispose(): void;
1411
+ }
1412
+ type JobChangesSocketOptions = {
1413
+ /** The websocket endpoint, e.g. `ws://localhost:4001/graphql/subscriptions`. */
1414
+ wsUrl: string;
1415
+ /** Resolves the `ConnectionInit` payload, per connect. */
1416
+ connectionParams?: () => Promise<ConnectionParams>;
1417
+ };
1418
+ /**
1419
+ * Opens the socket write handles wait on. `graphql-ws` multiplexes every
1420
+ * watched job over it and closes it once the last watch stops.
1421
+ */
1422
+ declare function createJobChangesSocket(options: JobChangesSocketOptions): IJobChangesSocket;
1423
+ /**
1424
+ * Derives the websocket endpoint from the GraphQL http endpoint.
1425
+ *
1426
+ * `http://host/graphql` becomes `ws://host/graphql/subscriptions`, which is
1427
+ * where the Switchboard mounts its websocket server (`packages/reactor-api`
1428
+ * `startServer`). A URL that already speaks `ws`/`wss` only gets the path.
1429
+ */
1430
+ declare function subscriptionsUrlFromGraphqlUrl(url: string): string;
1431
+ /**
1432
+ * Turns a bearer token provider into `connectionParams`.
1433
+ *
1434
+ * The header key is the lowercase `authorization` the Switchboard's websocket
1435
+ * context factory reads. Without a token the payload is empty: an open
1436
+ * Switchboard serves anonymous subscribers.
1437
+ */
1438
+ declare function makeAuthConnectionParams(tokenProvider: BearerTokenProvider): () => Promise<ConnectionParams>;
1439
+ //#endregion
1440
+ //#region src/graphql-client/switchboard-backend.d.ts
1441
+ type SwitchboardBackendDescriptor = {
1442
+ /** Router backend name; unique and stable for the router's life. */
1443
+ readonly name: string;
1444
+ /** `<origin>[/<prefix>]/graphql`. */
1445
+ readonly url: string;
1446
+ /** Resolves the bearer per request and for the realtime socket. */
1447
+ readonly tokenProvider: BearerTokenProvider;
1448
+ /** Read per push when a function; `undefined` pushes unsigned, never ambient. */
1449
+ readonly signer: ISigner | (() => ISigner | undefined) | undefined;
1450
+ /** Models for signing a batch, read per batch. */
1451
+ readonly documentModels: () => readonly DocumentModelModule$1<any>[];
1452
+ readonly realtime?: boolean;
1453
+ /** Default `"rpc"`. */
1454
+ readonly inspection?: ReactorReach["inspection"];
1455
+ /** Bound on one request, headers through body. Default 30_000. */
1456
+ readonly requestTimeoutMs?: number;
1457
+ /** Bound on a batch, which waits for its jobs. Default 120_000. */
1458
+ readonly batchRequestTimeoutMs?: number;
1459
+ /** Unset fields take {@link DEFAULT_BREAKER}; `false` never opens. */
1460
+ readonly breaker?: SwitchboardBreaker;
1461
+ /** The transport under the deadline and the breaker; {@link switchboardFetch} by default. */
1462
+ readonly fetch?: GraphQLFetch;
1463
+ };
1464
+ declare const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
1465
+ declare const DEFAULT_BATCH_REQUEST_TIMEOUT_MS = 120000;
1466
+ declare const DEFAULT_BREAKER: Readonly<{
1467
+ failures: 3;
1468
+ openMs: 30000;
1469
+ }>;
1470
+ /** After `failures` failed requests in a row, send nothing for `openMs`. */
1471
+ type SwitchboardBreaker = false | {
1472
+ readonly failures?: number;
1473
+ readonly openMs?: number;
1474
+ };
1475
+ type SwitchboardBackend = {
1476
+ /** reach `{hosting: "remote", inspection}`; `refusesMisroutes: false`. */
1477
+ readonly config: RoutableBackendConfig;
1478
+ /** Reopens the realtime socket on the new credentials. */
1479
+ notifyCredentialsChanged(): void;
1480
+ /** Closes the realtime socket. */
1481
+ dispose(): void;
1482
+ };
1483
+ /** The Switchboard's circuit is open: nothing was sent. */
1484
+ declare class SwitchboardUnreachableError extends Error {
1485
+ readonly backend: string;
1486
+ readonly retryAt: number;
1487
+ readonly name = "SwitchboardUnreachableError";
1488
+ constructor(backend: string, retryAt: number);
1489
+ }
1490
+ /** A Switchboard as a router backend; members GraphQL cannot serve are absent. */
1491
+ declare function createSwitchboardBackend(descriptor: SwitchboardBackendDescriptor): SwitchboardBackend;
1492
+ //#endregion
1493
+ //#region src/hooks/document-cache.d.ts
1494
+ /** Returns all documents in the reactor. */
1495
+ declare const useDocumentCache: UsePHGlobalValue$1<IDocumentCache>;
1496
+ /** Sets all of the documents in the reactor. */
1497
+ declare const setDocumentCache: SetPHGlobalValue$1<IDocumentCache>;
1498
+ /** Adds an event handler for all of the documents in the reactor. */
1499
+ declare const addDocumentCacheEventHandler: () => void;
1500
+ /**
1501
+ * Retrieves a document from the reactor and subscribes to changes using React Suspense.
1502
+ * This hook will suspend rendering while the document is loading.
1503
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
1504
+ * @returns The document if found, or undefined if id is null/undefined
1505
+ */
1506
+ declare function useDocument(id: string | null | undefined): PHDocument$1 | undefined;
1507
+ /**
1508
+ * Retrieves a document from the reactor and subscribes to changes without
1509
+ * suspending or throwing. Use this when the ID might be stale (e.g., a
1510
+ * previously selected node that has since been deleted) and the consumer
1511
+ * wants to render a placeholder instead of crashing.
1512
+ *
1513
+ * Unlike {@link useGetDocumentAsync}, this hook subscribes to cache
1514
+ * updates, so the returned state stays in sync with reactor changes.
1515
+ *
1516
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
1517
+ * @returns An object containing:
1518
+ * - status: "initial" | "pending" | "success" | "error"
1519
+ * - data: The document if successfully loaded
1520
+ * - isPending: Whether the document is currently loading
1521
+ * - error: Any error that occurred during loading (e.g., document not found)
1522
+ * - reload: Function to force a refetch, or undefined when no id is supplied
1523
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1524
+ * - refetchError: The last refetch failure that kept the loaded document
1525
+ */
1526
+ declare function useDocumentSafe(id: string | null | undefined): {
1527
+ readonly status: "initial";
1528
+ readonly isPending: false;
1529
+ readonly error: undefined;
1530
+ readonly data: undefined;
1531
+ readonly reload: undefined;
1532
+ readonly isRefetching: false;
1533
+ readonly refetchError: undefined;
1534
+ } | {
1535
+ readonly status: "pending";
1536
+ readonly isPending: true;
1537
+ readonly error: undefined;
1538
+ readonly data: undefined;
1539
+ readonly reload: () => Promise<PHDocument$1>;
1540
+ readonly isRefetching: boolean;
1541
+ readonly refetchError: unknown;
1542
+ } | {
1543
+ readonly status: "success";
1544
+ readonly isPending: false;
1545
+ readonly error: undefined;
1546
+ readonly data: PHDocument$1;
1547
+ readonly reload: () => Promise<PHDocument$1>;
1548
+ readonly isRefetching: boolean;
1549
+ readonly refetchError: unknown;
1550
+ } | {
1551
+ readonly status: "error";
1552
+ readonly isPending: false;
1553
+ readonly error: unknown;
1554
+ readonly data: undefined;
1555
+ readonly reload: () => Promise<PHDocument$1>;
1556
+ readonly isRefetching: boolean;
1557
+ readonly refetchError: unknown;
1558
+ };
1559
+ /**
1560
+ * Retrieves multiple documents from the reactor using React Suspense.
1561
+ * This hook will suspend rendering while any of the documents are loading.
1562
+ *
1563
+ * Uses getBatch from the document cache which handles promise caching internally,
1564
+ * ensuring stable references for useSyncExternalStore.
1565
+ *
1566
+ * @param ids - Array of document IDs to retrieve, or null/undefined to skip retrieval
1567
+ * @returns An array of documents if found, or empty array if ids is null/undefined
1568
+ */
1569
+ declare function useDocuments(ids: string[] | null | undefined): PHDocument$1[];
1570
+ /**
1571
+ * Returns a function to retrieve a document from the cache.
1572
+ * The returned function fetches and returns a document by ID.
1573
+ * @returns A function that takes a document ID and returns a Promise of the document
1574
+ */
1575
+ declare function useGetDocument(): (id: string) => Promise<PHDocument$1>;
1576
+ /**
1577
+ * Returns a function to retrieve multiple documents from the cache.
1578
+ * The returned function fetches and returns documents by their IDs.
1579
+ * @returns A function that takes an array of document IDs and returns a Promise of the documents
1580
+ */
1581
+ declare function useGetDocuments(): (ids: string[]) => Promise<PHDocument$1[]>;
1582
+ /**
1583
+ * Retrieves a document from the reactor without suspending rendering.
1584
+ * Returns the current state of the document loading operation.
1585
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
1586
+ * @returns An object containing:
1587
+ * - status: "initial" | "pending" | "success" | "error"
1588
+ * - data: The document if successfully loaded
1589
+ * - isPending: Boolean indicating if the document is currently loading
1590
+ * - error: Any error that occurred during loading
1591
+ * - reload: Function to force reload the document from cache
1592
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1593
+ * - refetchError: The last refetch failure that kept the loaded document
1594
+ */
1595
+ declare function useGetDocumentAsync(id: string | null | undefined): {
1596
+ readonly status: "initial";
1597
+ readonly data: undefined;
1598
+ readonly isPending: false;
1599
+ readonly error: undefined;
1600
+ readonly reload: undefined;
1601
+ readonly isRefetching: false;
1602
+ readonly refetchError: undefined;
1603
+ } | {
1604
+ readonly status: "pending";
1605
+ readonly isPending: true;
1606
+ readonly error: undefined;
1607
+ readonly data: undefined;
1608
+ readonly reload: () => Promise<PHDocument$1>;
1609
+ readonly isRefetching: boolean;
1610
+ readonly refetchError: unknown;
1611
+ } | {
1612
+ readonly status: "success";
1613
+ readonly isPending: false;
1614
+ readonly error: undefined;
1615
+ readonly data: PHDocument$1;
1616
+ readonly reload: () => Promise<PHDocument$1>;
1617
+ readonly isRefetching: boolean;
1618
+ readonly refetchError: unknown;
1619
+ } | {
1620
+ readonly status: "error";
1621
+ readonly isPending: false;
1622
+ readonly error: unknown;
1623
+ readonly data: undefined;
1624
+ readonly reload: () => Promise<PHDocument$1>;
1625
+ readonly isRefetching: boolean;
1626
+ readonly refetchError: unknown;
1627
+ };
1628
+ //#endregion
1629
+ //#region src/hooks/reactor.d.ts
1630
+ /** Returns the reactor client module (in-process or worker-backed) */
1631
+ declare const useReactorClientModule: UsePHGlobalValue<BrowserReactorClientModule | WorkerReactorClientModule>;
1632
+ /** Sets the reactor client module */
1633
+ declare const setReactorClientModule: SetPHGlobalValue<BrowserReactorClientModule | WorkerReactorClientModule>;
1634
+ /** Adds an event handler for the reactor client module */
1635
+ declare const addReactorClientModuleEventHandler: AddPHGlobalEventHandler;
1636
+ /** Returns the reactor client */
1637
+ declare const useReactorClient: UsePHGlobalValue<IReactorBrowserClient>;
1638
+ /**
1639
+ * Sets the reactor client, and `window.ph.reactor` to its read and write
1640
+ * halves. A client without halves leaves `reactor` unset.
1641
+ */
1642
+ declare const setReactorClient: SetPHGlobalValue<IReactorBrowserClient>;
1643
+ /** Returns the reactor client's read and write halves */
1644
+ declare const useReactorHalves: UsePHGlobalValue<ReactorBrowserHalves>;
1645
+ /** Adds an event handler for the reactor client's halves */
1646
+ declare const addReactorHalvesEventHandler: AddPHGlobalEventHandler;
1647
+ /** Adds an event handler for the reactor client */
1648
+ declare const addReactorClientEventHandler: AddPHGlobalEventHandler;
1649
+ /** Sets the client full-client actions use instead of the module's */
1650
+ declare const setFullReactorClient: SetPHGlobalValue<IReactorClient>;
1651
+ /** Adds an event handler for the full reactor client */
1652
+ declare const addFullReactorClientEventHandler: AddPHGlobalEventHandler;
1653
+ /** The client full-client actions use: the one set, else the module's. */
1654
+ declare function getFullReactorClient(): IReactorClient | undefined;
1655
+ declare const useSync: () => ISyncManager | undefined;
1656
+ declare const useSyncList: () => import("@powerhousedao/reactor").Remote[];
1657
+ declare const useModelRegistry: () => IDocumentModelRegistry | undefined;
1658
+ declare const useDatabase: () => Kysely<Database> | undefined;
1659
+ declare const usePGlite: () => PGlite | undefined;
1660
+ //#endregion
1661
+ //#region src/hooks/dispatch.d.ts
1662
+ /** Dispatches actions.
1663
+ *
1664
+ * Once the write lands, `onErrors` runs first, with an `OperationRejectedError` per action
1665
+ * the document did not apply; it is skipped when every action applied. Then `onSuccess`
1666
+ * runs with the document and an outcome, whether or not any action was rejected:
1667
+ * `outcome.rejected` holds the same errors, and is empty only when every action applied.
1668
+ * If `onErrors` throws, `onSuccess` does not run.
1669
+ *
1670
+ * When nothing lands (no document, no reactor, a failed write), only `onErrors` runs, with why. */
1671
+ type DispatchFn<TAction> = (actionOrActions: TAction[] | TAction | undefined, onErrors?: (errors: Error[]) => void, onSuccess?: DispatchSuccessCallback) => void;
1672
+ type UseDispatchResult<TDocument, TAction> = readonly [TDocument | undefined, DispatchFn<TAction>];
1673
+ /** A dispatch to the document `getDocument` returns when it runs. */
1674
+ declare function createDispatch<TDocument = PHDocument$1, TAction = Action$1>(getDocument: () => TDocument | undefined): DispatchFn<TAction>;
1675
+ /** Returns the document and a dispatch to it; see `DispatchFn` for the callbacks' order. */
1676
+ declare function useDispatch<TDocument = PHDocument$1, TAction = Action$1>(document: TDocument | undefined): UseDispatchResult<TDocument, TAction>;
1677
+ //#endregion
1678
+ //#region src/hooks/document-model-modules.d.ts
1679
+ declare function useDocumentModelModules(): DocumentModelModule[] | undefined;
1680
+ /**
1681
+ * Resolves a document model module by document type, mirroring the registry's
1682
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
1683
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
1684
+ * with `version` given only an exact match is returned. The reactor resolves
1685
+ * modules the same way when a document is created, so metadata read through
1686
+ * this hook and the version a creation actually uses cannot disagree.
1687
+ */
1688
+ declare function useDocumentModelModuleById(id: string | null | undefined, version?: number): DocumentModelModule | undefined;
1689
+ //#endregion
1690
+ //#region src/hooks/document-operations.d.ts
1691
+ type UseDocumentOperationsOptions = {
1692
+ /**
1693
+ * Operations per page. Default 100. Applies to the next first-page load;
1694
+ * changing it while pages are already loaded has no effect until the next
1695
+ * invalidation or `refetch`.
1696
+ */
1697
+ limit?: number;
1698
+ /** Whether to fetch at all. Default true. Pass false until the operations are needed. */
1699
+ enabled?: boolean;
1700
+ };
1701
+ /** What `useDocumentOperations` returns; exported so consumers can name it. */
1702
+ type DocumentOperationsResult = {
1703
+ /** Every operation of the scope loaded so far, oldest first. */
1704
+ operations: readonly Operation$1[];
1705
+ /** A page is in flight. */
1706
+ isLoading: boolean;
1707
+ /** The last page failed. Operations loaded before it stay available. */
1708
+ error: Error | undefined;
1709
+ /** The last page reported a further page. */
1710
+ hasNextPage: boolean;
1711
+ /** Loads the next page and appends it. No-op while loading or when there is none. */
1712
+ fetchNextPage: () => void;
1713
+ /** Drops the document's cached operations and reloads from the first page. */
1714
+ refetch: () => void;
1715
+ };
1716
+ /**
1717
+ * Legacy result of `useDocumentOperations(documentId)`.
1718
+ * @deprecated Call `useDocumentOperations(documentId, scope, options)` and read `operations`. Removed in the next major.
1719
+ */
1720
+ type DocumentOperationsState = {
1721
+ globalOperations: Operation$1[];
1722
+ localOperations: Operation$1[];
1723
+ isLoading: boolean;
1724
+ error: Error | undefined;
1725
+ refetch: () => void;
1726
+ };
1727
+ /** @deprecated Pass a scope: `useDocumentOperations(documentId, "global")`. The legacy form fetches the whole global and local history eagerly. Removed in the next major. */
1728
+ declare function useDocumentOperations(documentId: string | null | undefined): DocumentOperationsState;
1729
+ /**
1730
+ * Operation history of a document, read from the document cache and kept in
1731
+ * step with it: a change event for the document drops the cached pages and
1732
+ * the hook loads the first page again.
1733
+ *
1734
+ * Pages arrive oldest first. A view that wants the whole history calls
1735
+ * `fetchNextPage` while `hasNextPage` is true.
1736
+ *
1737
+ * An empty first page is a final result; there is no retry. When the active
1738
+ * document cache does not serve operations, the result is empty and not
1739
+ * loading.
1740
+ *
1741
+ * @param documentId - The document id, or null/undefined to skip fetching
1742
+ * @param scope - The operation scope, for example "global" or "local"
1743
+ * @param options - Page size and whether fetching is enabled
1744
+ */
1745
+ declare function useDocumentOperations(documentId: string | null | undefined, scope: string, options?: UseDocumentOperationsOptions): DocumentOperationsResult;
1746
+ //#endregion
1747
+ //#region src/hooks/attachment-service.d.ts
1748
+ /** Returns the attachment service from window.ph */
1749
+ declare const useAttachmentService: UsePHGlobalValue<IAttachmentService>;
1750
+ /** Sets the attachment service on window.ph */
1751
+ declare const setAttachmentService: SetPHGlobalValue<IAttachmentService>;
1752
+ /** Registers the attachmentService window event handler */
1753
+ declare const addAttachmentServiceEventHandler: AddPHGlobalEventHandler;
1754
+ //#endregion
1755
+ export { createJobChangesSocket as $, GetDocumentQueryFields as $t, addDocumentCacheEventHandler as A, isDocumentTypeCache as An, GraphQLRequestOptions as At, DEFAULT_BREAKER as B, switchboardFetch as Bt, useModelRegistry as C, TrackedAction as Cn, GraphQLReactorClientOptions as Ct, useReactorHalves as D, IDLE_OPERATIONS_ENTRY as Dn, findIsServableOverGraphQL as Dt, useReactorClientModule as E, IDLE_DOCUMENTS_OF_TYPE_ENTRY as En, createGraphQLDriveNodeSource as Et, useDocuments as F, subgraphUrlFromGraphqlUrl as Ft, SwitchboardUnreachableError as G, GraphQLWrongBackendError as Gt, SwitchboardBackend as H, withStreamedBodies as Ht, useGetDocument as I, GraphQLFetch as It, DocumentChangesEventPayload as J, queriesUnknownField as Jt, createSwitchboardBackend as K, JobFailedError as Kt, useGetDocumentAsync as L, globalFetch as Lt, useDocument as M, readPromiseState as Mn, SubgraphSdkRegistry as Mt, useDocumentCache as N, IDLE_REFETCH_STATE as Nn, TypedGraphQLDocument as Nt, useSync as O, IDocumentCacheReader as On, isGraphQLReactorClient as Ot, useDocumentSafe as P, dispatchActions as Pn, describeGraphQLDocument as Pt, JobChangesSocketOptions as Q, toLegacyNode as Qt, useGetDocuments as R, isDeadlineError as Rt, useDatabase as S, SyncStatus$1 as Sn, GraphQLReactorClient as St, useReactorClient as T, GET_MANY_CHUNK_SIZE as Tn, ambientRenownSigner as Tt, SwitchboardBackendDescriptor as U, BatchJobFailedError as Ut, DEFAULT_REQUEST_TIMEOUT_MS as V, withRequestDeadline as Vt, SwitchboardBreaker as W, GraphQLOperationNotSupportedError as Wt, IJobChangesSocket as X, GraphQLDriveNodeSource as Xt, DocumentChangesSubscriptionOptions as Y, DriveNodeQueries as Yt, JobChangesEventPayload as Z, GraphQLDriveReadClient as Zt, addReactorHalvesEventHandler as _, RemoteControllerOptions as _n, GraphQLReactorProvider as _t, DocumentOperationsState as a, revisionMapFromRevisionsList as an, packageFromDocumentModels as at, setReactorClient as b, RemoteOperation as bn, useSwitchboardClient as bt, useDocumentModelModuleById as c, DocumentChangeListener as cn, signStampedAction as ct, UseDispatchResult as d, GetOperationsResult as dn, GetDocumentAtConsistencyResult as dt, GetDocumentQueryResult as en, isAuthRefusalClose as et, createDispatch as f, IRemoteClient as fn, GetDocumentAtConsistencyVariables as ft, addReactorClientModuleEventHandler as g, RemoteControllerGraphQLClient as gn, ReactorOperationFieldsFragmentDoc as gt, addReactorClientEventHandler as h, PushResult as hn, MutateDocumentWithOperationsVariables as ht, DocumentOperationsResult as i, phDocumentFromMutation as in, StaticPackageManager as it, setDocumentCache as j, isOperationCache as jn, SubgraphSdkFactory as jt, useSyncList as k, addPromiseState as kn, viewFilterInputFromViewFilter as kt, useDocumentModelModules as l, GetDocumentResult as ln, stampAction as lt, addFullReactorClientEventHandler as m, MergeHandler as mn, MutateDocumentWithOperationsResult as mt, setAttachmentService as n, isoStringFromDateTime as nn, startDocumentChangesSubscription as nt, UseDocumentOperationsOptions as o, ConflictInfo as on, resolveDocumentModelModule as ot, useDispatch as p, IRemoteController as pn, MutateDocumentWithOperationsDocument as pt, ConnectionParams as q, queriesUnknownArgument as qt, useAttachmentService as r, phDocumentFromGetDocument as rn, subscriptionsUrlFromGraphqlUrl as rt, useDocumentOperations as s, ConflictStrategy as sn, prepareSignedActions as st, addAttachmentServiceEventHandler as t, RevisionsListSelection as tn, makeAuthConnectionParams as tt, DispatchFn as u, GetDocumentWithOperationsResult as un, GetDocumentAtConsistencyDocument as ut, getFullReactorClient as v, RemoteDocumentChangeEvent as vn, GraphQLReactorProviderProps as vt, usePGlite as w, DocumentCache as wn, GraphQLReactorReadClient as wt, setReactorClientModule as x, RemoteOperationResultPage as xn, DriveIdCall as xt, setFullReactorClient as y, RemoteDocumentData as yn, ensurePHEventHandlers as yt, DEFAULT_BATCH_REQUEST_TIMEOUT_MS as z, isNodeFetch as zt };
1756
+ export {};
1757
+ //# sourceMappingURL=attachment-service-DXfpfp98.d.ts.map