@powerhousedao/reactor-browser 6.2.3-dev.10 → 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 (106) hide show
  1. package/dist/{attachment-service-BW1v0OAT.d.ts → attachment-service-DXfpfp98.d.ts} +767 -108
  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-CxJD0Ck2.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-CBjFO54H.d.ts → index-Bj1poVfa.d.ts} +31 -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 +907 -411
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +851 -306
  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-D1RB45sA.js → relational-DZuyKp2y.js} +66 -5
  36. package/dist/relational-DZuyKp2y.js.map +1 -0
  37. package/dist/{renown-rqK8sokh.js → renown-B3MUaiq7.js} +61 -31
  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-N3Jy6Nry.d.ts → schema-Bn6L3QR1.d.ts} +255 -65
  42. package/dist/schema-Bn6L3QR1.d.ts.map +1 -0
  43. package/dist/{client-D4bkR4pH.js → schema-D0G1oAo9.js} +247 -152
  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 +600 -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-BW1v0OAT.d.ts.map +0 -1
  81. package/dist/client-CxJD0Ck2.d.ts.map +0 -1
  82. package/dist/client-D4bkR4pH.js.map +0 -1
  83. package/dist/client-DjK30EQ-.js.map +0 -1
  84. package/dist/document-by-id-B4FIzG1w.js +0 -519
  85. package/dist/document-by-id-B4FIzG1w.js.map +0 -1
  86. package/dist/document-model-modules-bTP87nyr.js +0 -419
  87. package/dist/document-model-modules-bTP87nyr.js.map +0 -1
  88. package/dist/document-operations-Cm4EtaZs.js +0 -2603
  89. package/dist/document-operations-Cm4EtaZs.js.map +0 -1
  90. package/dist/global-CgCouXuH.d.ts +0 -401
  91. package/dist/global-CgCouXuH.d.ts.map +0 -1
  92. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  93. package/dist/index-CBjFO54H.d.ts.map +0 -1
  94. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  95. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  96. package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
  97. package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
  98. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  99. package/dist/relational-D1RB45sA.js.map +0 -1
  100. package/dist/renown-BHxwP7xU.js +0 -97
  101. package/dist/renown-BHxwP7xU.js.map +0 -1
  102. package/dist/renown-rqK8sokh.js.map +0 -1
  103. package/dist/switchboard-CaXQ4-5Q.js +0 -271
  104. package/dist/switchboard-CaXQ4-5Q.js.map +0 -1
  105. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  106. package/dist/types-N3Jy6Nry.d.ts.map +0 -1
@@ -0,0 +1,4609 @@
1
+ import { c as getPHStore, f as usePHStore, t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
2
+ import { A as DocumentModelNotFoundError, D as queueActions, O as queueOperations, P as UnsupportedDocumentTypeError, b as DOCUMENT_CHANGE_TYPE, f as DocumentCache, h as IDLE_OPERATIONS_ENTRY, i as setDocumentCache, k as uploadOperations, o as useDocumentCache, r as addDocumentCacheEventHandler, v as isOperationCache } from "./dispatch-Cylwl2Dk.js";
3
+ import { B as addFullReactorClientEventHandler, D as setSelectedNodeId, H as addReactorClientModuleEventHandler, K as setReactorClient, N as addDrivesEventHandler, S as addSelectedNodeIdEventHandler, U as addReactorHalvesEventHandler, V as addReactorClientEventHandler, W as getFullReactorClient, Z as useReactorClient, _t as ambientRenownTokenProvider, a as setVetraPackageManager, at as invalidateDriveNodes, c as addSwitchboardsEventHandler, d as addSelectedDriveIdEventHandler, h as setSelectedDriveId, ht as listAllDriveNodes, it as getDriveNode, nt as addDriveNodesEventHandler, p as selectDrive, r as addVetraPackageManagerEventHandler, rt as dropDriveNode, st as markLocalDriveWrite, v as useSelectedDriveId, vt as makeAuthMiddleware, x as addResetSelectedNodeEventHandler } from "./document-model-modules-BG-61uke.js";
4
+ import { A as openTargetWith, C as getCurrentPathname, E as hasHostNavigation, G as extractNodeIdFromSlug, I as searchToRecord, J as findDriveBySlug, K as extractNodeSlugFromPath, L as setBrowserOpenSync, N as recordToSearch, U as extractDriveSlugFromPath, f as addLoadingEventHandler, k as openTarget, t as addRenownEventHandler, w as getPHNavigation, z as targetPathname } from "./renown-CBoTdGrg.js";
5
+ import { a as JobChangesDocument, o as PhDocumentFieldsFragmentDoc, t as DocumentChangesDocument } from "./schema-D0G1oAo9.js";
6
+ import { t as createClient$1 } from "./client-1n_ZUXeu.js";
7
+ import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
8
+ import { Fragment, jsx } from "react/jsx-runtime";
9
+ import { logger } from "document-model";
10
+ import { FLAGS_FOR_EVERY_VERSION, PEER_CAPABILITIES, UnsupportedDocumentModelVersionError, actionSignerIdentity, actionSigningTarget, actions, assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, capSelection, capabilitiesOf, createCopyHeader, createPresignedHeader, createZip, creationState, deserializeSignature, documentModelDocumentType, fitCreateBaseReducer, generateId, hasDerivedDocumentId, hashDocumentStateForScope, headNewDocument, isSignaturePolicy, localSupports, normalizeDocumentModelVersion, replayDocumentVersioned, resolveBaseReducerVersion, selectDocumentModelModule, serializeByKey, setName, setPreferredEditor, signaturePolicyOf, toTransportAction, undoCapabilitiesOf, undoNeedsTargets, undoRedoActions, undoRedoAvailabilityOf, withSignaturePolicy } from "@powerhousedao/shared/document-model";
11
+ import { addFolder, copyNode, driveDocumentModelModule, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
12
+ import { allPass, conditional, constant, forEachObj, funnel, isDefined, isNot, isStrictEqual, isString, isTruthy, once } from "remeda";
13
+ import { DRIVE_CHILD_RELATIONSHIP_TYPE } from "@powerhousedao/reactor-drive";
14
+ import { gql } from "graphql-tag";
15
+ import { Kind, print } from "graphql";
16
+ import { GraphQLClient } from "graphql-request";
17
+ import { createClient } from "graphql-ws/client";
18
+ //#region src/hooks/url-state.ts
19
+ /** The nearest store's navigation, else the bound store's, else the browser's.
20
+ * Hosts set it once, so hook order holds. */
21
+ function usePHNavigation() {
22
+ return usePHStore()?.navigation ?? getPHNavigation();
23
+ }
24
+ /** The current query params. */
25
+ function useSearchParams() {
26
+ return usePHNavigation().useSearchParams();
27
+ }
28
+ /** Sets query params: an object merges into them, a function returns them all. */
29
+ function useSetSearchParams() {
30
+ return usePHNavigation().useSetSearchParams();
31
+ }
32
+ //#endregion
33
+ //#region src/hooks/link-props.ts
34
+ /** A plain primary click; modified and other-button clicks stay the browser's. */
35
+ function isPlainClick(event) {
36
+ return !event.defaultPrevented && event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
37
+ }
38
+ /** Props for an `<a>` that opens `target` in the app on a plain click, and
39
+ * leaves new tabs and windows to the browser; acts on the store in context. */
40
+ function useLinkProps(target, open) {
41
+ const navigation = usePHNavigation();
42
+ const href = navigation.hrefFor?.(target) ?? targetPathname(target);
43
+ const isCurrent = navigation.useIsCurrent?.(target) ?? false;
44
+ const preload = () => navigation.preload?.(target);
45
+ const openTarget = open ?? (() => openTargetWith(navigation, target));
46
+ return {
47
+ href,
48
+ onClick: (event) => {
49
+ if (!isPlainClick(event)) return;
50
+ event.preventDefault();
51
+ openTarget();
52
+ },
53
+ onMouseEnter: preload,
54
+ onFocus: preload,
55
+ "aria-current": isCurrent ? "page" : void 0
56
+ };
57
+ }
58
+ //#endregion
59
+ //#region src/hooks/modals.ts
60
+ const modalEventFunctions = makePHEventFunctions("modal");
61
+ /** Returns the current modal */
62
+ const usePHModal = modalEventFunctions.useValue;
63
+ /** Sets the current modal */
64
+ const setPHModal = modalEventFunctions.setValue;
65
+ /** Adds an event handler for the modal */
66
+ const addModalEventHandler = modalEventFunctions.addEventHandler;
67
+ /** The query param that names a routed modal. */
68
+ const MODAL_SEARCH_PARAM = "modal";
69
+ const MODAL_ROUTES = {
70
+ createDocument: {
71
+ id: "create-document",
72
+ toSearch: ({ documentType, documentModelVersion, driveId }) => ({
73
+ documentType,
74
+ ...documentModelVersion !== void 0 && { documentModelVersion: String(documentModelVersion) },
75
+ ...driveId && { driveId }
76
+ }),
77
+ fromSearch: (search) => ({
78
+ documentType: search.documentType ?? "",
79
+ ...search.documentModelVersion && { documentModelVersion: Number(search.documentModelVersion) },
80
+ ...search.driveId && { driveId: search.driveId }
81
+ })
82
+ },
83
+ login: { id: "login" },
84
+ addDrive: { id: "add-drive" },
85
+ driveSettings: {
86
+ id: "drive-settings",
87
+ toSearch: ({ driveId }) => ({ driveId }),
88
+ fromSearch: (search) => ({ driveId: search.driveId ?? "" })
89
+ },
90
+ debugSettings: { id: "debug-settings" },
91
+ inspector: { id: "inspector" },
92
+ disclaimer: { id: "disclaimer" },
93
+ cookiesPolicy: { id: "cookies-policy" }
94
+ };
95
+ const routeOf = (type) => MODAL_ROUTES[type];
96
+ /** Whether `modal` lives in the URL rather than the store. */
97
+ function isRoutedModal(modal) {
98
+ return !!modal && !!routeOf(modal.type);
99
+ }
100
+ /** The query params that open `modal`; undefined for one the store holds. */
101
+ function modalSearch(modal) {
102
+ const route = routeOf(modal.type);
103
+ if (!route) return void 0;
104
+ return {
105
+ [MODAL_SEARCH_PARAM]: route.id,
106
+ ...route.toSearch?.(modal)
107
+ };
108
+ }
109
+ /** The routed modal `search` opens, if any. */
110
+ function modalFromSearch(search) {
111
+ const id = search[MODAL_SEARCH_PARAM];
112
+ if (typeof id !== "string") return void 0;
113
+ const strings = Object.fromEntries(Object.entries(search).map(([key, value]) => [key, String(value)]));
114
+ for (const [type, route] of Object.entries(MODAL_ROUTES)) {
115
+ if (route.id !== id) continue;
116
+ return {
117
+ type,
118
+ ...route.fromSearch?.(strings)
119
+ };
120
+ }
121
+ }
122
+ /** `search` without a routed modal's params. */
123
+ function withoutModalSearch(search) {
124
+ const modal = modalFromSearch(search);
125
+ const own = modal ? Object.keys(modalSearch(modal) ?? {}) : [];
126
+ return Object.fromEntries(Object.entries(search).filter(([key]) => !own.includes(key)));
127
+ }
128
+ /** Shows a modal. With a host navigation, a routed one opens in the URL, in
129
+ * place of the current entry, and "settings" opens the settings page. */
130
+ function showPHModal(modal) {
131
+ if (modal.type === "settings" && hasHostNavigation()) {
132
+ openTarget({ settings: true });
133
+ return;
134
+ }
135
+ const search = modalSearch(modal);
136
+ if (search && hasHostNavigation()) {
137
+ if (!isRoutedModal(modalEventFunctions.getSnapshot())) setPHModal(void 0);
138
+ getPHNavigation().setSearch((prev) => ({
139
+ ...withoutModalSearch(prev),
140
+ ...search
141
+ }), { replace: true });
142
+ return;
143
+ }
144
+ setPHModal(modal);
145
+ }
146
+ /** Closes the current modal; a routed one leaves the URL in place of the entry,
147
+ * and a confirmation opened over it closes with it. */
148
+ function closePHModal() {
149
+ if (hasHostNavigation()) {
150
+ const navigation = getPHNavigation();
151
+ if (modalFromSearch(searchToRecord(navigation.location().search))) {
152
+ navigation.setSearch((prev) => withoutModalSearch(prev), { replace: true });
153
+ if (!isRoutedModal(modalEventFunctions.getSnapshot())) setPHModal(void 0);
154
+ return;
155
+ }
156
+ }
157
+ setPHModal(void 0);
158
+ }
159
+ /** The href that opens `modal` over the current page. */
160
+ function modalHref(modal) {
161
+ const { pathname, search } = getPHNavigation().location();
162
+ const next = {
163
+ ...withoutModalSearch(searchToRecord(search)),
164
+ ...modalSearch(modal)
165
+ };
166
+ return `${pathname}${recordToSearch(next)}`;
167
+ }
168
+ /** Props for an `<a>` that opens a routed `modal` over the current page on a
169
+ * plain click; new tabs and copied links get its URL. */
170
+ function useModalLinkProps(modal) {
171
+ useSearchParams();
172
+ return {
173
+ href: modalHref(modal),
174
+ onClick: (event) => {
175
+ if (!isPlainClick(event)) return;
176
+ event.preventDefault();
177
+ showPHModal(modal);
178
+ }
179
+ };
180
+ }
181
+ /** Shows the create document modal */
182
+ function showCreateDocumentModal(documentType, documentModelVersion) {
183
+ showPHModal({
184
+ type: "createDocument",
185
+ documentType,
186
+ ...documentModelVersion !== void 0 && { documentModelVersion }
187
+ });
188
+ }
189
+ /** Shows the delete node modal */
190
+ function showDeleteNodeModal(nodeOrId) {
191
+ const id = typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id;
192
+ setPHModal({
193
+ type: "deleteItem",
194
+ id
195
+ });
196
+ }
197
+ //#endregion
198
+ //#region src/utils/documents.ts
199
+ function isDocumentTypeSupported(documentType, supportedDocuments) {
200
+ if (!supportedDocuments?.length) return true;
201
+ return supportedDocuments.some((pattern) => {
202
+ if (pattern.endsWith("/*")) {
203
+ const prefix = pattern.slice(0, -2);
204
+ return documentType.startsWith(prefix + "/");
205
+ }
206
+ if (pattern.endsWith("*") && !pattern.endsWith("/*")) {
207
+ const prefix = pattern.slice(0, -1);
208
+ return documentType.startsWith(prefix);
209
+ }
210
+ return pattern === documentType;
211
+ });
212
+ }
213
+ //#endregion
214
+ //#region src/utils/user.ts
215
+ function getUserPermissions() {
216
+ const user = getPHStore()?.renown?.user;
217
+ const allowList = getPHStore()?.allowList;
218
+ if (!allowList) return {
219
+ isAllowedToCreateDocuments: true,
220
+ isAllowedToEditDocuments: true
221
+ };
222
+ return {
223
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
224
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
225
+ };
226
+ }
227
+ //#endregion
228
+ //#region src/actions/document.ts
229
+ const NON_DOMAIN_SCOPES = /* @__PURE__ */ new Set(["auth", "document"]);
230
+ /** Puts a node this tab just wrote into its drive's cache, so hooks show it
231
+ * before the drive change that follows the write is processed. Best effort:
232
+ * a client without a node reader is left to that change. */
233
+ async function rememberDriveNode(driveId, nodeId) {
234
+ try {
235
+ await getDriveNode(driveId, nodeId, { refresh: true });
236
+ } catch (error) {
237
+ logger.verbose("Caching the written node @id failed: @error", nodeId, error);
238
+ }
239
+ }
240
+ /** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */
241
+ async function isDocumentInLocation(reactorClient, document, driveId, parentFolder) {
242
+ const siblings = await listAllDriveNodes(reactorClient.drives, driveId, { parentFolder: parentFolder ?? null });
243
+ const nodeById = siblings.find((node) => node.id === document.header.id);
244
+ if (nodeById) return {
245
+ isDuplicate: true,
246
+ duplicateType: "id",
247
+ nodeId: nodeById.id
248
+ };
249
+ const nodeByNameAndType = siblings.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType);
250
+ if (nodeByNameAndType) return {
251
+ isDuplicate: true,
252
+ duplicateType: "name",
253
+ nodeId: nodeByNameAndType.id
254
+ };
255
+ return { isDuplicate: false };
256
+ }
257
+ function getDocumentTypeIcon(document) {
258
+ switch (document.header.documentType) {
259
+ case "powerhouse/document-model": return "document-model";
260
+ case "powerhouse/app": return "app";
261
+ case "powerhouse/document-editor": return "editor";
262
+ case "powerhouse/subgraph": return "subgraph";
263
+ case "powerhouse/package": return "package";
264
+ case "powerhouse/processor": {
265
+ const processorType = document.state.global?.type;
266
+ if (processorType === "analytics") return "analytics-processor";
267
+ if (processorType === "relational") return "relational-processor";
268
+ if (processorType === "codegen") return "codegen-processor";
269
+ return;
270
+ }
271
+ default: return;
272
+ }
273
+ }
274
+ async function downloadFile(document, fileName) {
275
+ try {
276
+ const data = await createZip(document);
277
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
278
+ const link = window.document.createElement("a");
279
+ link.style.display = "none";
280
+ link.href = URL.createObjectURL(blob);
281
+ link.download = fileName;
282
+ window.document.body.appendChild(link);
283
+ link.click();
284
+ window.document.body.removeChild(link);
285
+ } catch (e) {
286
+ logger.error(e instanceof Error ? e.message : String(e));
287
+ }
288
+ }
289
+ async function getDocumentExtension(document) {
290
+ const documentType = document.header.documentType;
291
+ let rawExtension;
292
+ if (documentType === documentModelDocumentType) rawExtension = document.state.global?.extension;
293
+ else {
294
+ const reactorClient = getFullReactorClient();
295
+ if (reactorClient) {
296
+ const { results: documentModelModules } = await reactorClient.read.getDocumentModelModules();
297
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
298
+ }
299
+ }
300
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
301
+ }
302
+ /**
303
+ * Fetches all operations for a document using cursor-based pagination.
304
+ * The reactor client handles multi-scope cursors transparently via
305
+ * composite cursors, so all scopes are fetched in a single paginated stream.
306
+ */
307
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
308
+ const scopes = Object.keys(document.state);
309
+ const operations = {};
310
+ for (const scope of scopes) operations[scope] = [];
311
+ let cursor = "";
312
+ do {
313
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
314
+ cursor,
315
+ limit: pageSize
316
+ });
317
+ for (const op of page.results) {
318
+ const scope = op.action.scope ?? "global";
319
+ if (operations[scope]) operations[scope].push(op);
320
+ }
321
+ cursor = page.nextCursor ?? "";
322
+ } while (cursor);
323
+ return operations;
324
+ }
325
+ function extractInitialState(documentScopeOps) {
326
+ const initialState = creationState(documentScopeOps);
327
+ if (initialState) return initialState;
328
+ throw new Error(documentScopeOps.some((op) => op.action.type === "UPGRADE_DOCUMENT") ? "UPGRADE_DOCUMENT operation has no initialState — document is invalid" : "No UPGRADE_DOCUMENT operation found — document is invalid");
329
+ }
330
+ function filterDomainOperations(operations) {
331
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
332
+ }
333
+ function countOperations(operations) {
334
+ let total = 0;
335
+ for (const ops of Object.values(operations)) total += ops?.length ?? 0;
336
+ return total;
337
+ }
338
+ /**
339
+ * Split an imported document's domain operations at its mid-history upgrade
340
+ * boundaries, so the caller can re-dispatch each upgrade between segments.
341
+ *
342
+ * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
343
+ * path and must not be repeated. A later upgrade must be: it is where the
344
+ * reducer version changes, and dropping it replays everything after it through
345
+ * the module the document was created with.
346
+ */
347
+ function splitAtUpgradeBoundaries(operations) {
348
+ const upgrades = (operations.document ?? []).filter((op) => op.action.type === "UPGRADE_DOCUMENT").filter((op) => op.action.input.fromVersion > 0).sort((a, b) => a.index - b.index);
349
+ const domain = filterDomainOperations(operations);
350
+ if (upgrades.length === 0) return [{ operations: domain }];
351
+ const segments = [];
352
+ const consumed = /* @__PURE__ */ new Map();
353
+ const take = (until) => {
354
+ const slice = {};
355
+ for (const [scope, ops] of Object.entries(domain)) {
356
+ if (!ops) continue;
357
+ const from = consumed.get(scope) ?? 0;
358
+ const stop = Math.max(from, until(scope, ops));
359
+ const chunk = ops.slice(from, stop);
360
+ if (chunk.length > 0) slice[scope] = chunk;
361
+ consumed.set(scope, stop);
362
+ }
363
+ return slice;
364
+ };
365
+ for (const upgrade of upgrades) {
366
+ const input = upgrade.action.input;
367
+ const slice = take((scope, ops) => boundary(upgrade, scope, ops));
368
+ segments.push({
369
+ operations: slice,
370
+ upgradeTo: input.toVersion
371
+ });
372
+ }
373
+ const tail = take((_scope, ops) => ops.length);
374
+ if (countOperations(tail) > 0) segments.push({ operations: tail });
375
+ return segments;
376
+ }
377
+ /**
378
+ * How many of a scope's operations precede an upgrade. Must stay identical to
379
+ * the boundary computation in `replayDocumentVersioned` — snapshots compare
380
+ * against operation indices, not array positions, and the timestamp fallback
381
+ * excludes the upgrade's own instant.
382
+ */
383
+ function boundary(upgrade, scope, ops) {
384
+ const snapshot = upgrade.action.input.revision;
385
+ if (snapshot !== void 0) {
386
+ const revision = snapshot[scope] ?? 0;
387
+ let count = 0;
388
+ for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
389
+ return count;
390
+ }
391
+ for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
392
+ return ops.length;
393
+ }
394
+ async function exportFile(document, suggestedName) {
395
+ const reactorClient = getPHStore()?.reactorClient;
396
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
397
+ const operations = await fetchDocumentOperations(reactorClient.read, document);
398
+ const initialState = extractInitialState(operations["document"] ?? []);
399
+ const documentWithOps = {
400
+ ...document,
401
+ operations,
402
+ initialState
403
+ };
404
+ const extension = await getDocumentExtension(documentWithOps);
405
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
406
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
407
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
408
+ try {
409
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
410
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
411
+ return fileHandle;
412
+ } catch (e) {
413
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
414
+ }
415
+ }
416
+ /**
417
+ * Loads a document file and replays it with version-aware reducers from the registry.
418
+ * Falls back to single-version legacy replay when no upgrade manifest is registered for
419
+ * the document type.
420
+ */
421
+ async function loadFile(path) {
422
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
423
+ const reactorClient = getFullReactorClient();
424
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
425
+ const documentType = baseDocument.header.documentType;
426
+ const { results: documentModelModules } = await reactorClient.read.getDocumentModelModules();
427
+ const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
428
+ if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
429
+ const reducers = {};
430
+ for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
431
+ const registry = getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;
432
+ let upgradeManifest;
433
+ if (registry) try {
434
+ upgradeManifest = registry.getUpgradeManifest(documentType);
435
+ } catch {}
436
+ return baseLoadFromInputVersioned(path, {
437
+ reducers,
438
+ upgradeManifest
439
+ });
440
+ }
441
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
442
+ const { isAllowedToCreateDocuments } = getUserPermissions();
443
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
444
+ const reactorClient = getFullReactorClient();
445
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
446
+ const newDocument = document ?? await reactorClient.read.newDocument(documentType, {
447
+ parentIdentifier: driveId,
448
+ documentModelVersion
449
+ });
450
+ newDocument.header.name = name;
451
+ if (preferredEditor) newDocument.header.meta = {
452
+ ...newDocument.header.meta,
453
+ preferredEditor
454
+ };
455
+ markLocalDriveWrite(driveId);
456
+ let newDoc;
457
+ try {
458
+ newDoc = await (await reactorClient.write.drives.addFile(driveId, newDocument, parentFolder)).document();
459
+ } catch (e) {
460
+ logger.error("Error adding document: @error", e);
461
+ throw new Error("There was an error adding document", { cause: e });
462
+ }
463
+ await rememberDriveNode(driveId, newDoc.header.id);
464
+ await getDriveNode(driveId, newDoc.header.id, { refresh: true }).catch(() => void 0);
465
+ return {
466
+ id: newDoc.header.id,
467
+ name: newDoc.header.name,
468
+ documentType,
469
+ parentFolder: parentFolder ?? null,
470
+ kind: "file"
471
+ };
472
+ }
473
+ /**
474
+ * How many ids an import will try before giving up. The check before the create
475
+ * catches an id that is already taken; this bound covers the window between the
476
+ * two, where a create can still lose to a claim made in the meantime.
477
+ */
478
+ const IMPORT_ID_ATTEMPTS = 3;
479
+ /** True when this error, or anything it wraps, is a taken document id. */
480
+ function isDocumentAlreadyExists(error) {
481
+ let current = error;
482
+ while (current instanceof Error) {
483
+ if (current.name === "DocumentAlreadyExistsError") return true;
484
+ current = current.cause;
485
+ }
486
+ return false;
487
+ }
488
+ /**
489
+ * Creates the imported document under an id that is free, retrying on a
490
+ * collision.
491
+ *
492
+ * The check cannot stand on its own: it answers for the moment it ran, and the
493
+ * create that follows can still land on an id claimed in between. The store
494
+ * rejects that create as DocumentAlreadyExistsError, which is not retryable
495
+ * under the same id and is resolved by minting another one. A create that
496
+ * fails leaves the drive untouched, so a retry has nothing to clean up.
497
+ */
498
+ async function createImportedDocument(write, document, driveId, name, parentFolder) {
499
+ const v2Required = signaturePolicyOf(document.header) === "v2-required";
500
+ const keepsId = (!v2Required || hasDerivedDocumentId(document.header)) && !await write.isDocumentIdTaken(document.header.id);
501
+ let documentId = keepsId ? document.header.id : generateId();
502
+ for (let attempt = 1;; attempt++) {
503
+ let header;
504
+ if (!v2Required) header = createPresignedHeader(documentId, document.header.documentType, document.header.protocolVersions);
505
+ else if (keepsId && attempt === 1) {
506
+ header = createPresignedHeader(documentId, document.header.documentType);
507
+ header.createdAtUtcIso = document.header.createdAtUtcIso;
508
+ header.sig = {
509
+ ...header.sig,
510
+ nonce: document.header.sig.nonce
511
+ };
512
+ header.protocolVersions = { ...document.header.protocolVersions };
513
+ } else {
514
+ header = createCopyHeader(document.header);
515
+ documentId = header.id;
516
+ }
517
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
518
+ header.meta = document.header.meta;
519
+ header.name = name || document.header.name;
520
+ const initialDocument = {
521
+ ...document,
522
+ header,
523
+ state: document.initialState,
524
+ operations: Object.keys(document.operations).reduce((acc, key) => {
525
+ acc[key] = [];
526
+ return acc;
527
+ }, {})
528
+ };
529
+ try {
530
+ const fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
531
+ if (!fileNode) throw new Error("There was an error adding file");
532
+ return {
533
+ documentId,
534
+ fileNode
535
+ };
536
+ } catch (error) {
537
+ if (!isDocumentAlreadyExists(error) || attempt === IMPORT_ID_ATTEMPTS) throw error;
538
+ logger.warn(`Document id ${documentId} was taken between the check and the create; importing under a new id`);
539
+ documentId = generateId();
540
+ }
541
+ }
542
+ }
543
+ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
544
+ logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
545
+ const reactor = getFullReactorClient();
546
+ if (!reactor) {
547
+ onProgress?.({
548
+ stage: "failed",
549
+ progress: 100,
550
+ error: "ReactorClient not initialized"
551
+ });
552
+ throw new Error("ReactorClient not initialized");
553
+ }
554
+ const { isAllowedToCreateDocuments } = getUserPermissions();
555
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
556
+ try {
557
+ onProgress?.({
558
+ stage: "loading",
559
+ progress: 0
560
+ });
561
+ let document;
562
+ try {
563
+ document = await loadFile(file);
564
+ } catch (loadError) {
565
+ if (UnsupportedDocumentModelVersionError.isError(loadError)) {
566
+ showPHModal({
567
+ type: "documentVersionUnsupported",
568
+ documentType: loadError.documentType,
569
+ requiredVersion: loadError.requiredVersion,
570
+ availableVersions: loadError.availableVersions
571
+ });
572
+ onProgress?.({
573
+ stage: "failed",
574
+ progress: 100,
575
+ error: loadError.message
576
+ });
577
+ return;
578
+ }
579
+ const discoveryService = getPHStore()?.packageDiscoveryService;
580
+ if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
581
+ retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict).catch((retryError) => {
582
+ logger.error("Import retry after discovery failed: @error", retryError);
583
+ onProgress?.({
584
+ stage: "failed",
585
+ progress: 100,
586
+ error: retryError instanceof Error ? retryError.message : String(retryError)
587
+ });
588
+ });
589
+ return;
590
+ }
591
+ throw loadError;
592
+ }
593
+ const duplicateCheck = await isDocumentInLocation(reactor.read, document, driveId, parentFolder);
594
+ if (duplicateCheck.isDuplicate && !resolveConflict) {
595
+ onProgress?.({
596
+ stage: "conflict",
597
+ progress: 0,
598
+ duplicateType: duplicateCheck.duplicateType
599
+ });
600
+ return;
601
+ }
602
+ const documentType = getDocumentTypeIcon(document);
603
+ if (documentType) onProgress?.({
604
+ stage: "loading",
605
+ progress: 10,
606
+ documentType
607
+ });
608
+ else onProgress?.({
609
+ stage: "loading",
610
+ progress: 10
611
+ });
612
+ if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {
613
+ onProgress?.({
614
+ stage: "unsupported-document-type",
615
+ progress: 100,
616
+ error: `Document type ${document.header.documentType} is not supported`
617
+ });
618
+ throw new UnsupportedDocumentTypeError(document.header.documentType);
619
+ }
620
+ await reactor.read.getDocumentModelModule(document.header.documentType);
621
+ onProgress?.({
622
+ stage: "initializing",
623
+ progress: 10
624
+ });
625
+ markLocalDriveWrite(driveId);
626
+ const created = await createImportedDocument(reactor.write, document, driveId, name, parentFolder);
627
+ const documentId = created.documentId;
628
+ const fileNode = created.fileNode;
629
+ await rememberDriveNode(driveId, documentId);
630
+ onProgress?.({
631
+ stage: "initializing",
632
+ progress: 20
633
+ });
634
+ await reactor.read.get(documentId);
635
+ console.log("Document created, starting upload of operations");
636
+ const segments = splitAtUpgradeBoundaries(document.operations);
637
+ const totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);
638
+ let uploadedBefore = 0;
639
+ for (const segment of segments) {
640
+ await uploadOperations(documentId, segment.operations, queueOperations, { onProgress: (uploadProgress) => {
641
+ if (uploadProgress.uploadedOperations === void 0) return;
642
+ const uploaded = uploadedBefore + uploadProgress.uploadedOperations;
643
+ const uploadPercent = totalOperations > 0 ? uploaded / totalOperations : 0;
644
+ onProgress?.({
645
+ stage: "uploading",
646
+ progress: 20 + Math.round(uploadPercent * 80),
647
+ totalOperations,
648
+ uploadedOperations: uploaded
649
+ });
650
+ } });
651
+ uploadedBefore += countOperations(segment.operations);
652
+ if (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);
653
+ }
654
+ onProgress?.({
655
+ stage: "complete",
656
+ progress: 100,
657
+ fileNode
658
+ });
659
+ return fileNode;
660
+ } catch (error) {
661
+ if (!UnsupportedDocumentTypeError.isError(error)) {
662
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
663
+ onProgress?.({
664
+ stage: "failed",
665
+ progress: 100,
666
+ error: errorMessage
667
+ });
668
+ }
669
+ throw error;
670
+ }
671
+ }
672
+ async function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
673
+ if (!discoveryService) return;
674
+ try {
675
+ await discoveryService.load(documentType);
676
+ } catch {
677
+ onProgress?.({
678
+ stage: "unsupported-document-type",
679
+ progress: 100,
680
+ error: `Document type ${documentType} is not supported`
681
+ });
682
+ return;
683
+ }
684
+ await addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
685
+ }
686
+ async function addFolder$1(driveId, name, parentFolder) {
687
+ const { isAllowedToCreateDocuments } = getUserPermissions();
688
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
689
+ const reactorClient = getPHStore()?.reactorClient;
690
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
691
+ await reactorClient.read.get(driveId);
692
+ const folderId = generateId();
693
+ markLocalDriveWrite(driveId);
694
+ await (await reactorClient.write.execute(driveId, "main", [addFolder({
695
+ id: folderId,
696
+ name,
697
+ parentFolder
698
+ })])).readable;
699
+ const node = await getDriveNode(driveId, folderId, { refresh: true });
700
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
701
+ return node;
702
+ }
703
+ async function deleteNode(driveId, nodeId) {
704
+ const { isAllowedToCreateDocuments } = getUserPermissions();
705
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to delete documents");
706
+ const reactorClient = getFullReactorClient();
707
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
708
+ markLocalDriveWrite(driveId);
709
+ await (await reactorClient.write.drives.removeNode(driveId, nodeId)).readable;
710
+ dropDriveNode(driveId, nodeId);
711
+ }
712
+ async function renameNode(driveId, nodeId, name) {
713
+ const { isAllowedToCreateDocuments } = getUserPermissions();
714
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
715
+ const reactorClient = getPHStore()?.reactorClient;
716
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
717
+ if ((await (await reactorClient.write.execute(nodeId, "main", [setName({ name })])).document()).header.name !== name) throw new Error("There was an error renaming the node");
718
+ markLocalDriveWrite(driveId);
719
+ await (await reactorClient.write.execute(driveId, "main", [updateNode({
720
+ id: nodeId,
721
+ name
722
+ })])).readable;
723
+ const node = await getDriveNode(driveId, nodeId, { refresh: true });
724
+ if (!node) throw new Error("There was an error renaming node in the drive");
725
+ return node;
726
+ }
727
+ async function renameDriveNode(driveId, nodeId, name) {
728
+ const { isAllowedToCreateDocuments } = getUserPermissions();
729
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
730
+ const reactorClient = getPHStore()?.reactorClient;
731
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
732
+ if ((await (await reactorClient.write.execute(nodeId, "main", [setName({ name })])).document()).header.name !== name) throw new Error("There was an error renaming the node");
733
+ markLocalDriveWrite(driveId);
734
+ await (await reactorClient.write.execute(driveId, "main", [updateNode({
735
+ id: nodeId,
736
+ name
737
+ })])).readable;
738
+ return getDriveNode(driveId, nodeId, { refresh: true });
739
+ }
740
+ async function setPreferredEditorOnNode(nodeId, preferredEditor) {
741
+ const { isAllowedToCreateDocuments } = getUserPermissions();
742
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to modify documents");
743
+ const reactorClient = getPHStore()?.reactorClient;
744
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
745
+ return (await reactorClient.write.execute(nodeId, "main", [setPreferredEditor(preferredEditor)])).document();
746
+ }
747
+ async function moveNodeById(args) {
748
+ const { driveId, srcId, targetId } = args;
749
+ if (!driveId || !srcId) return;
750
+ const { isAllowedToCreateDocuments } = getUserPermissions();
751
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
752
+ const reactorClient = getPHStore()?.reactorClient;
753
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
754
+ const targetParentFolder = conditional(targetId, [isNot(isDefined), constant(void 0)], [isStrictEqual(driveId), constant(void 0)], constant(targetId));
755
+ if (isStrictEqual(targetParentFolder, srcId)) return;
756
+ markLocalDriveWrite(driveId);
757
+ const moved = await (await reactorClient.write.execute(driveId, "main", [moveNode({
758
+ srcFolder: srcId,
759
+ targetParentFolder
760
+ })])).document();
761
+ await rememberDriveNode(driveId, srcId);
762
+ return moved;
763
+ }
764
+ async function moveNode$1(driveId, src, target) {
765
+ const { isAllowedToCreateDocuments } = getUserPermissions();
766
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
767
+ const reactorClient = getPHStore()?.reactorClient;
768
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
769
+ markLocalDriveWrite(driveId);
770
+ const moved = await (await reactorClient.write.execute(driveId, "main", [moveNode({
771
+ srcFolder: src.id,
772
+ targetParentFolder: target?.id
773
+ })])).document();
774
+ await rememberDriveNode(driveId, src.id);
775
+ return moved;
776
+ }
777
+ /**
778
+ * Duplicates a document under a new id using version-aware replay.
779
+ * Falls back gracefully when no upgrade manifest is registered for the document type.
780
+ */
781
+ async function _duplicateDocument(reactor, document, newId = generateId(), driveId) {
782
+ const documentType = document.header.documentType;
783
+ const { results: allModules } = await reactor.getDocumentModelModules();
784
+ const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
785
+ const reducers = {};
786
+ for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
787
+ if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
788
+ const registry = getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;
789
+ let upgradeManifest;
790
+ if (registry) try {
791
+ upgradeManifest = registry.getUpgradeManifest(documentType);
792
+ } catch {}
793
+ const config = {
794
+ reducers,
795
+ upgradeManifest
796
+ };
797
+ const selected = await reactor.getCreateProtocolVersions({
798
+ documentType: document.header.documentType,
799
+ parentIdentifier: driveId
800
+ });
801
+ const header = createCopyHeader({
802
+ documentType: document.header.documentType,
803
+ protocolVersions: document.header.protocolVersions ? {
804
+ ...selected,
805
+ ...document.header.protocolVersions
806
+ } : void 0
807
+ }, newId, await reactor.getCreateSignaturePolicy());
808
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
809
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
810
+ return duplicated;
811
+ }
812
+ async function copyNode$1(driveId, src, target) {
813
+ const reactor = getFullReactorClient();
814
+ if (!reactor) return;
815
+ const { isAllowedToCreateDocuments } = getUserPermissions();
816
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
817
+ const drive = await reactor.read.get(driveId);
818
+ const driveNodes = await listAllDriveNodes(reactor.read.drives, driveId);
819
+ const copyNodesInput = generateNodesCopy({
820
+ srcId: src.id,
821
+ targetParentFolder: target?.id,
822
+ targetName: src.name
823
+ }, () => generateId(), driveNodes);
824
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
825
+ for (const copyNodeInput of copyNodesInput) {
826
+ const node = driveNodes.find((n) => n.id === copyNodeInput.srcId);
827
+ if (node) {
828
+ const resolvedName = handleTargetNameCollisions({
829
+ nodes: driveNodes,
830
+ srcName: copyNodeInput.targetName || node.name,
831
+ srcKind: isFileNode(node) ? "file" : "folder",
832
+ targetParentFolder: copyNodeInput.targetParentFolder || null
833
+ });
834
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
835
+ }
836
+ }
837
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
838
+ const node = driveNodes.find((node) => node.id === copyNodeInput.srcId);
839
+ return node !== void 0 && isFileNode(node);
840
+ });
841
+ markLocalDriveWrite(driveId);
842
+ for (const fileNodeToCopy of fileNodesToCopy) try {
843
+ const document = await reactor.read.get(fileNodeToCopy.srcId);
844
+ const duplicatedDocument = await _duplicateDocument(reactor.read, document, fileNodeToCopy.targetId, driveId);
845
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
846
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
847
+ fileNodeToCopy.targetId = duplicatedDocument.header.id;
848
+ await (await reactor.write.drives.addFile(driveId, duplicatedDocument, target?.id)).readable;
849
+ } catch (e) {
850
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
851
+ }
852
+ const copyActions = copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput));
853
+ markLocalDriveWrite(driveId);
854
+ const copied = await queueActions(drive, copyActions);
855
+ invalidateDriveNodes(driveId);
856
+ return copied;
857
+ }
858
+ /**
859
+ * Upgrades a document to a newer document model version. Defaults to the
860
+ * latest registered version for the document's type.
861
+ */
862
+ async function upgradeDocument(documentId, toVersion) {
863
+ const reactorClient = getFullReactorClient();
864
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
865
+ return (await reactorClient.write.upgradeDocument(documentId, toVersion)).document();
866
+ }
867
+ //#endregion
868
+ //#region src/graphql-client/errors.ts
869
+ /** A call the Switchboard GraphQL surface cannot express. */
870
+ var GraphQLOperationNotSupportedError = class extends Error {
871
+ name = "GraphQLOperationNotSupportedError";
872
+ operation;
873
+ constructor(operation, reason) {
874
+ super(`GraphQLReactorClient.${operation} is not supported: ${reason}`);
875
+ this.operation = operation;
876
+ }
877
+ static isError(error) {
878
+ return Error.isError(error) && error.name === "GraphQLOperationNotSupportedError";
879
+ }
880
+ };
881
+ /**
882
+ * The Switchboard refused a request with 421 Misdirected Request: the
883
+ * `Drive-Id` it carried names a drive that Switchboard does not own.
884
+ */
885
+ var GraphQLWrongBackendError = class extends Error {
886
+ name = "GraphQLWrongBackendError";
887
+ status = 421;
888
+ /** The drive the Switchboard refused, or `""` when its answer names none. */
889
+ driveId;
890
+ /** The response body, parsed when it is JSON. */
891
+ payload;
892
+ constructor(driveId, payload, options) {
893
+ super(`The Switchboard does not serve drive ${driveId === "" ? "(unnamed)" : driveId}: 421 Misdirected Request`, options);
894
+ this.driveId = driveId;
895
+ this.payload = payload;
896
+ }
897
+ static isError(error) {
898
+ return Error.isError(error) && error.name === "GraphQLWrongBackendError" && typeof error.driveId === "string";
899
+ }
900
+ };
901
+ /**
902
+ * The reactor's `BatchJobFailedError`, rebuilt from a batch result; this entry
903
+ * imports the reactor for types only. The shared name lets either `isError`
904
+ * recognise it.
905
+ */
906
+ var BatchJobFailedError = class extends Error {
907
+ name = "BatchJobFailedError";
908
+ key;
909
+ jobs;
910
+ constructor(key, jobs) {
911
+ const failure = jobs[key].error;
912
+ const cause = new Error(failure?.message ?? "Job failed");
913
+ cause.name = failure?.name ?? "Error";
914
+ super(failure?.message ?? "Job failed", { cause });
915
+ this.key = key;
916
+ this.jobs = jobs;
917
+ }
918
+ static isError(error) {
919
+ return Error.isError(error) && error.name === "BatchJobFailedError" && typeof error.key === "string" && typeof error.jobs === "object";
920
+ }
921
+ };
922
+ /** A validation error naming root field `field` unknown: a host from before it. */
923
+ function queriesUnknownField(error, field) {
924
+ return hasErrorStarting(error, `Cannot query field "${field}" on type "`);
925
+ }
926
+ /** A validation error naming `argument` unknown: a host from before it. */
927
+ function queriesUnknownArgument(error, argument) {
928
+ return hasErrorStarting(error, `Unknown argument "${argument}" on field "`);
929
+ }
930
+ function hasErrorStarting(error, prefix) {
931
+ const errors = error?.response?.errors;
932
+ if (!Array.isArray(errors)) return false;
933
+ return errors.some((entry) => typeof entry?.message === "string" && entry.message.startsWith(prefix));
934
+ }
935
+ /**
936
+ * The reactor's `JobFailedError`, rebuilt from a job the Switchboard reported
937
+ * FAILED; this entry imports the reactor for types only. A write handle's
938
+ * stage rejects with it. The message is the job error's message, as the
939
+ * reactor's is.
940
+ */
941
+ var JobFailedError = class extends Error {
942
+ name = "JobFailedError";
943
+ job;
944
+ constructor(job) {
945
+ super(job.error?.message);
946
+ this.job = job;
947
+ }
948
+ static isError(error) {
949
+ return Error.isError(error) && error.name === "JobFailedError" && typeof error.job === "object";
950
+ }
951
+ };
952
+ //#endregion
953
+ //#region src/constants.ts
954
+ const DEFAULT_DRIVE_EDITOR_ID = "powerhouse/generic-drive-explorer";
955
+ const COMMON_PACKAGE_ID = "powerhouse/common";
956
+ /** Document types that represent a "drive": a container of nodes. */
957
+ const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
958
+ //#endregion
959
+ //#region src/remote-controller/utils.ts
960
+ /** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. "SET_MODEL_NAME" → "setModelName"). */
961
+ function screamingSnakeToCamel(s) {
962
+ return s.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase());
963
+ }
964
+ /** Error thrown when a push conflict is detected with the "reject" strategy. */
965
+ var ConflictError = class extends Error {
966
+ conflict;
967
+ constructor(conflict) {
968
+ super("Push conflict: remote has new operations since last pull");
969
+ this.conflict = conflict;
970
+ this.name = "ConflictError";
971
+ }
972
+ };
973
+ /** Convert a remote operation to the local Operation type. */
974
+ function remoteOperationToLocal(remote) {
975
+ return {
976
+ id: remote.id ?? "",
977
+ index: remote.index,
978
+ skip: remote.skip,
979
+ timestampUtcMs: remote.timestampUtcMs,
980
+ hash: remote.hash,
981
+ error: remote.error ?? void 0,
982
+ deniedReason: remote.deniedReason ?? void 0,
983
+ action: {
984
+ id: remote.action.id,
985
+ type: remote.action.type,
986
+ timestampUtcMs: remote.action.timestampUtcMs,
987
+ input: remote.action.input,
988
+ scope: remote.action.scope,
989
+ context: remote.action.context?.signer ? { signer: {
990
+ user: remote.action.context.signer.user ?? {
991
+ address: "",
992
+ networkId: "",
993
+ chainId: 0
994
+ },
995
+ app: remote.action.context.signer.app ?? {
996
+ name: "",
997
+ key: ""
998
+ },
999
+ signatures: remote.action.context.signer.signatures.map((s) => deserializeSignature(s))
1000
+ } } : void 0
1001
+ }
1002
+ };
1003
+ }
1004
+ /** Convert remote operations to local DocumentOperations format. */
1005
+ function convertRemoteOperations(operationsByScope) {
1006
+ const operations = {};
1007
+ for (const [scope, remoteOps] of Object.entries(operationsByScope)) operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));
1008
+ return operations;
1009
+ }
1010
+ /**
1011
+ * Reconstruct a PHDocument from remote document data and operations; the
1012
+ * header carries the remote protocol versions. `initialDoc` supplies the rest
1013
+ * of the header, and the initial state when the operations do not record one.
1014
+ */
1015
+ function buildPulledDocument(remoteDoc, operations, initialDoc, branch) {
1016
+ return {
1017
+ header: {
1018
+ ...initialDoc.header,
1019
+ id: remoteDoc.id,
1020
+ name: remoteDoc.name,
1021
+ slug: remoteDoc.slug ?? "",
1022
+ documentType: remoteDoc.documentType,
1023
+ createdAtUtcIso: typeof remoteDoc.createdAtUtcIso === "string" ? remoteDoc.createdAtUtcIso : remoteDoc.createdAtUtcIso.toISOString(),
1024
+ lastModifiedAtUtcIso: typeof remoteDoc.lastModifiedAtUtcIso === "string" ? remoteDoc.lastModifiedAtUtcIso : remoteDoc.lastModifiedAtUtcIso.toISOString(),
1025
+ revision: Object.fromEntries(remoteDoc.revisionsList.map((r) => [r.scope, r.revision])),
1026
+ branch,
1027
+ ...remoteDoc.protocolVersions != null ? { protocolVersions: remoteDoc.protocolVersions } : {}
1028
+ },
1029
+ state: remoteDoc.state,
1030
+ initialState: creationState(operations.document ?? []) ?? initialDoc.initialState,
1031
+ operations,
1032
+ clipboard: []
1033
+ };
1034
+ }
1035
+ /** `document` as created: its header and initial state, without scope operations. */
1036
+ function uncreatedDocument(document) {
1037
+ const { header, initialState } = structuredClone({
1038
+ header: document.header,
1039
+ initialState: document.initialState
1040
+ });
1041
+ return {
1042
+ header,
1043
+ state: initialState,
1044
+ initialState,
1045
+ operations: {},
1046
+ clipboard: []
1047
+ };
1048
+ }
1049
+ /** An uncreated `document` under `policy`; a legacy one keeps its id. */
1050
+ function underSignaturePolicy(document, policy) {
1051
+ if (signaturePolicyOf(document.header) === policy) return document;
1052
+ return withSignaturePolicy(document, policy, { id: document.header.id });
1053
+ }
1054
+ /** Extract revision map from a remote document's revisionsList. */
1055
+ function extractRevisionMap(revisionsList) {
1056
+ return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
1057
+ }
1058
+ /**
1059
+ * Check if any scope in currentRevision is ahead of knownRevision.
1060
+ * When `scopes` is provided, only those scopes are checked.
1061
+ */
1062
+ function hasRevisionConflict(currentRevision, knownRevision, scopes) {
1063
+ for (const scope in currentRevision) {
1064
+ if (scopes && !scopes.has(scope)) continue;
1065
+ if ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) return true;
1066
+ }
1067
+ return false;
1068
+ }
1069
+ //#endregion
1070
+ //#region src/graphql-client/adapter.ts
1071
+ /**
1072
+ * Converts a `GetDocument` result into a `PHDocument`.
1073
+ *
1074
+ * Unlike the legacy `src/graphql/adapters.ts` this preserves the per-scope
1075
+ * revision map, which the write path needs to compute the `prevOpIndex` of a
1076
+ * signed action. `sig` is filled with the empty shape used by
1077
+ * `createPresignedHeader`: the creation signature is not fetchable over
1078
+ * GraphQL and is not part of the operation signing payload.
1079
+ *
1080
+ * The read path never fetches operation history, so `operations` maps each
1081
+ * scope of the document's state and revisions to an empty array.
1082
+ *
1083
+ * `branch` is the branch the document was read from. The GraphQL type does not
1084
+ * carry it, so it has to be passed back in by the caller; it defaults to the
1085
+ * server's own default branch.
1086
+ */
1087
+ function phDocumentFromGetDocument(document, branch) {
1088
+ const state = document.state;
1089
+ return {
1090
+ header: phDocumentHeaderFromGetDocument(document, branch),
1091
+ state,
1092
+ initialState: state,
1093
+ operations: emptyOperationsForScopes(state, document.revisionsList),
1094
+ clipboard: []
1095
+ };
1096
+ }
1097
+ /**
1098
+ * Converts a mutation result into a `PHDocument`, carrying the operations the
1099
+ * mutation produced.
1100
+ *
1101
+ * `dispatchActions` reads per-action failures out of `operations[scope]`, so
1102
+ * unlike the read path this one must not return empty operation lists.
1103
+ */
1104
+ function phDocumentFromMutation(document, operations, branch) {
1105
+ const phDocument = phDocumentFromGetDocument(document, branch);
1106
+ const operationsByScope = { ...phDocument.operations };
1107
+ for (const remote of operations) {
1108
+ const operation = remoteOperationToLocal(remote);
1109
+ const scope = operation.action.scope;
1110
+ const scopeOperations = operationsByScope[scope] ?? [];
1111
+ scopeOperations.push(operation);
1112
+ operationsByScope[scope] = scopeOperations;
1113
+ }
1114
+ phDocument.operations = operationsByScope;
1115
+ return phDocument;
1116
+ }
1117
+ /** Turns a `revisionsList` selection into the header's per-scope revision map. */
1118
+ function revisionMapFromRevisionsList(revisionsList) {
1119
+ return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
1120
+ }
1121
+ /** The branch the server reads and writes when none is asked for. */
1122
+ const defaultBranch = "main";
1123
+ function phDocumentHeaderFromGetDocument(document, branch) {
1124
+ return {
1125
+ id: document.id,
1126
+ sig: {
1127
+ publicKey: {},
1128
+ nonce: ""
1129
+ },
1130
+ documentType: document.documentType,
1131
+ createdAtUtcIso: isoStringFromDateTime(document.createdAtUtcIso),
1132
+ slug: document.slug ?? "",
1133
+ name: document.name,
1134
+ branch: branch ?? defaultBranch,
1135
+ revision: revisionMapFromRevisionsList(document.revisionsList),
1136
+ lastModifiedAtUtcIso: isoStringFromDateTime(document.lastModifiedAtUtcIso),
1137
+ ...document.meta != null ? { meta: document.meta } : {},
1138
+ ...document.protocolVersions != null ? { protocolVersions: document.protocolVersions } : {}
1139
+ };
1140
+ }
1141
+ function emptyOperationsForScopes(state, revisionsList) {
1142
+ const scopes = /* @__PURE__ */ new Set([...Object.keys(state), ...revisionsList.map((r) => r.scope)]);
1143
+ return Object.fromEntries([...scopes].map((scope) => [scope, []]));
1144
+ }
1145
+ /** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */
1146
+ function isoStringFromDateTime(value) {
1147
+ return value instanceof Date ? value.toISOString() : value;
1148
+ }
1149
+ //#endregion
1150
+ //#region src/graphql-client/drive-nodes.ts
1151
+ /** Page size {@link GraphQLDriveNodeSource.listAll} reads a drive in. */
1152
+ const LIST_ALL_PAGE_LIMIT = 1e3;
1153
+ const DEFAULT_LIMIT$1 = 100;
1154
+ /**
1155
+ * The reactor subgraph's type-neutral node queries (`driveNodes`, `driveNode`,
1156
+ * `driveDescendants`) as an {@link IDriveNodeSource}, so a browser reads a
1157
+ * legacy drive and a reactor-drive alike. The Switchboard serves only the
1158
+ * nodes the caller may read. Drive ids must be canonical ids, not slugs.
1159
+ */
1160
+ var GraphQLDriveNodeSource = class {
1161
+ queries;
1162
+ headersFor;
1163
+ constructor(queries, headersFor = () => void 0) {
1164
+ this.queries = queries;
1165
+ this.headersFor = headersFor;
1166
+ }
1167
+ async getNode(driveId, nodeId, signal) {
1168
+ const result = await this.queries.GetDriveNode({
1169
+ driveId,
1170
+ id: nodeId
1171
+ }, this.headersFor(driveId), signal);
1172
+ return result.driveNode ? toRecord(result.driveNode) : void 0;
1173
+ }
1174
+ async listChildren(driveId, parentFolder, paging, signal, kind) {
1175
+ const cursor = startCursor(paging?.cursor);
1176
+ const page = (await this.queries.GetDriveNodes({
1177
+ driveId,
1178
+ ...parentFolder === void 0 ? {} : { parentFolder },
1179
+ paging: paging ? {
1180
+ cursor,
1181
+ limit: paging.limit
1182
+ } : void 0,
1183
+ kind: kind === void 0 ? void 0 : kind === "file" ? "FILE" : "FOLDER"
1184
+ }, this.headersFor(driveId), signal)).driveNodes;
1185
+ const nextCursor = page.hasMore ? page.nextCursor ?? void 0 : void 0;
1186
+ return {
1187
+ results: page.results.map(toRecord),
1188
+ options: {
1189
+ cursor,
1190
+ limit: paging?.limit ?? DEFAULT_LIMIT$1
1191
+ },
1192
+ ...nextCursor !== void 0 ? { nextCursor } : {}
1193
+ };
1194
+ }
1195
+ async getDescendants(driveId, root, signal) {
1196
+ return (await this.queries.GetDriveDescendants({
1197
+ driveId,
1198
+ root
1199
+ }, this.headersFor(driveId), signal)).driveDescendants.map(toRecord);
1200
+ }
1201
+ async listAll(driveId, signal) {
1202
+ const nodes = [];
1203
+ let cursor = "";
1204
+ for (;;) {
1205
+ const page = await this.listChildren(driveId, void 0, {
1206
+ cursor,
1207
+ limit: LIST_ALL_PAGE_LIMIT
1208
+ }, signal);
1209
+ nodes.push(...page.results);
1210
+ if (page.nextCursor === void 0 || page.nextCursor === cursor) return nodes;
1211
+ cursor = page.nextCursor;
1212
+ }
1213
+ }
1214
+ };
1215
+ /**
1216
+ * `read.drives` over a node source: the reactor's {@link IDriveReadClient},
1217
+ * answering in the legacy `Node` shape for every drive type.
1218
+ */
1219
+ var GraphQLDriveReadClient = class {
1220
+ nodes;
1221
+ constructor(nodes) {
1222
+ this.nodes = nodes;
1223
+ }
1224
+ async getNode(driveIdentifier, nodeId, signal) {
1225
+ const record = await this.nodes.getNode(driveIdentifier, nodeId, signal);
1226
+ if (!record) throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);
1227
+ return toLegacyNode(record);
1228
+ }
1229
+ async listNodes(driveIdentifier, parentFolder, paging, signal) {
1230
+ const page = await this.nodes.listChildren(driveIdentifier, parentFolder, paging, signal);
1231
+ const nextCursor = page.nextCursor;
1232
+ return {
1233
+ results: page.results.map(toLegacyNode),
1234
+ options: page.options,
1235
+ ...nextCursor !== void 0 ? {
1236
+ nextCursor,
1237
+ next: () => this.listNodes(driveIdentifier, parentFolder, {
1238
+ cursor: nextCursor,
1239
+ limit: page.options.limit
1240
+ }, signal)
1241
+ } : {}
1242
+ };
1243
+ }
1244
+ };
1245
+ /** A node record in the legacy `Node` shape. */
1246
+ function toLegacyNode(node) {
1247
+ if (node.kind === "file") return {
1248
+ id: node.id,
1249
+ kind: "file",
1250
+ name: node.name,
1251
+ parentFolder: node.parentFolder,
1252
+ documentType: node.documentType ?? ""
1253
+ };
1254
+ return {
1255
+ id: node.id,
1256
+ kind: "folder",
1257
+ name: node.name,
1258
+ parentFolder: node.parentFolder
1259
+ };
1260
+ }
1261
+ function toRecord(node) {
1262
+ const base = {
1263
+ id: node.id,
1264
+ driveId: node.driveId,
1265
+ name: node.name,
1266
+ parentFolder: node.parentFolder ?? null
1267
+ };
1268
+ return "documentType" in node ? {
1269
+ ...base,
1270
+ kind: "file",
1271
+ documentType: node.documentType
1272
+ } : {
1273
+ ...base,
1274
+ kind: "folder"
1275
+ };
1276
+ }
1277
+ /** The offset-style "0" other listings start from means the first page here too. */
1278
+ function startCursor(cursor) {
1279
+ return cursor === void 0 || cursor === "0" ? "" : cursor;
1280
+ }
1281
+ //#endregion
1282
+ //#region src/graphql-client/transport.ts
1283
+ /** The global `fetch`, read per call so a later replacement is honoured. */
1284
+ const globalFetch = (input, init) => globalThis.fetch(input, init);
1285
+ /**
1286
+ * Whether `fetch` here is Node's (undici), which resends a request answered
1287
+ * 421 and can fail the resend of a buffered body. A page, Electron's renderer
1288
+ * included, has a `document`.
1289
+ */
1290
+ function isNodeFetch() {
1291
+ const scope = globalThis;
1292
+ return typeof scope.process?.versions?.node === "string" && scope.document === void 0;
1293
+ }
1294
+ /**
1295
+ * Sends a string body as a stream, which fetch never resends, so a 421 comes
1296
+ * back as itself. Browsers keep buffered bodies: Chrome streams an upload only
1297
+ * over HTTP/2.
1298
+ */
1299
+ function withStreamedBodies(inner = globalFetch) {
1300
+ return (input, init) => {
1301
+ const body = init?.body;
1302
+ if (typeof body !== "string") return inner(input, init);
1303
+ const bytes = new TextEncoder().encode(body);
1304
+ return inner(input, {
1305
+ ...init,
1306
+ body: new ReadableStream({ start(controller) {
1307
+ controller.enqueue(bytes);
1308
+ controller.close();
1309
+ } }),
1310
+ duplex: "half"
1311
+ });
1312
+ };
1313
+ }
1314
+ const streamedGlobalFetch = withStreamedBodies(globalFetch);
1315
+ /** A Switchboard backend's default transport: streamed bodies under Node only. */
1316
+ const switchboardFetch = (input, init) => isNodeFetch() ? streamedGlobalFetch(input, init) : globalFetch(input, init);
1317
+ /** Bounds each request, headers through body; rejects with a `TimeoutError`. */
1318
+ function withRequestDeadline(timeoutMs, inner = globalFetch) {
1319
+ return (input, init) => {
1320
+ const deadline = AbortSignal.timeout(timeoutMs);
1321
+ const signal = init?.signal ? AbortSignal.any([init.signal, deadline]) : deadline;
1322
+ return inner(input, {
1323
+ ...init,
1324
+ signal
1325
+ });
1326
+ };
1327
+ }
1328
+ /**
1329
+ * Whether a request failed at a deadline rather than by its caller's abort:
1330
+ * this transport's own (`TimeoutError`, a DOMException) or the router's probe
1331
+ * deadline (`ProbeTimeoutError`, reactor-router's dispatcher.ts).
1332
+ */
1333
+ function isDeadlineError(error) {
1334
+ const name = error?.name;
1335
+ return name === "TimeoutError" || name === "ProbeTimeoutError";
1336
+ }
1337
+ //#endregion
1338
+ //#region src/graphql-client/create-defaults.ts
1339
+ /** The host's policy for a new document; a host without `createDefaults` is refused, as a guess could under-sign. */
1340
+ async function readCreateSignaturePolicy(sdk, signal) {
1341
+ const defaults = await readCreateDefaults(sdk, void 0, signal);
1342
+ if (defaults === void 0) throw new GraphQLOperationNotSupportedError("getCreateSignaturePolicy", "the Switchboard predates the createDefaults query");
1343
+ const { signaturePolicy } = defaults;
1344
+ if (!isSignaturePolicy(signaturePolicy)) throw new Error(`The Switchboard answered an unknown create signature policy: ${signaturePolicy}`);
1345
+ return signaturePolicy;
1346
+ }
1347
+ /** The host's per-type selection, capped at what this build runs and fitted to `modules`; baseline from an old host. */
1348
+ async function readCreateProtocolVersions(sdk, { documentType, parentIdentifier }, modules, signal) {
1349
+ const host = await hostCreateProtocolVersions(sdk, documentType, parentIdentifier, signal);
1350
+ const selected = capSelection(host, PEER_CAPABILITIES, localSupports(PEER_CAPABILITIES, FLAGS_FOR_EVERY_VERSION));
1351
+ return fitCreateBaseReducer(selected, documentType, modules, logger);
1352
+ }
1353
+ /** The Switchboard's selection; undefined from a host without `createDefaults`. */
1354
+ async function hostCreateProtocolVersions(sdk, documentType, parentIdentifier, signal) {
1355
+ if (documentType !== void 0) try {
1356
+ return protocolVersionsFrom((await sdk.GetCreateProtocolVersions({
1357
+ documentType,
1358
+ parentIdOrSlug: parentIdentifier
1359
+ }, void 0, signal)).createDefaults.protocolVersions);
1360
+ } catch (error) {
1361
+ if (queriesUnknownField(error, "createDefaults")) return void 0;
1362
+ if (!queriesUnknownArgument(error, "documentType")) throw error;
1363
+ }
1364
+ const defaults = await readCreateDefaults(sdk, parentIdentifier, signal);
1365
+ return defaults && protocolVersionsFrom(defaults.protocolVersions);
1366
+ }
1367
+ /** The reactor-wide `createDefaults`; undefined from a host without the query. */
1368
+ async function readCreateDefaults(sdk, parentIdentifier, signal) {
1369
+ try {
1370
+ return (await sdk.GetCreateDefaults({ parentIdOrSlug: parentIdentifier }, void 0, signal)).createDefaults;
1371
+ } catch (error) {
1372
+ if (queriesUnknownField(error, "createDefaults")) return;
1373
+ throw error;
1374
+ }
1375
+ }
1376
+ function protocolVersionsFrom(value) {
1377
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("The Switchboard answered malformed create protocol versions");
1378
+ const versions = {};
1379
+ for (const [protocol, version] of Object.entries(value)) {
1380
+ if (typeof version !== "number" || !Number.isInteger(version)) throw new Error(`The Switchboard answered a malformed version for protocol ${protocol}`);
1381
+ versions[protocol] = version;
1382
+ }
1383
+ return versions;
1384
+ }
1385
+ //#endregion
1386
+ //#region src/graphql-client/operations.ts
1387
+ /**
1388
+ * The operation selection of `GetDocumentOperations`, lifted into a fragment so
1389
+ * the write path can reuse `remoteOperationToLocal` on the items it selects.
1390
+ */
1391
+ const ReactorOperationFieldsFragmentDoc = gql`
1392
+ fragment ReactorOperationFields on ReactorOperation {
1393
+ index
1394
+ timestampUtcMs
1395
+ hash
1396
+ skip
1397
+ error
1398
+ deniedReason
1399
+ id
1400
+ action {
1401
+ id
1402
+ type
1403
+ timestampUtcMs
1404
+ input
1405
+ scope
1406
+ context {
1407
+ signer {
1408
+ user {
1409
+ address
1410
+ networkId
1411
+ chainId
1412
+ }
1413
+ app {
1414
+ name
1415
+ key
1416
+ }
1417
+ signatures
1418
+ }
1419
+ }
1420
+ }
1421
+ }
1422
+ `;
1423
+ /**
1424
+ * `mutateDocument` plus the operations the mutation produced.
1425
+ *
1426
+ * The generated `MutateDocument` only selects the document fields, but
1427
+ * `dispatchActions` reads per-action failures out of `result.operations[scope]`
1428
+ * (`src/actions/dispatch.ts`), so the reducer-level errors would be lost.
1429
+ *
1430
+ * The operations filter keeps the extra selection to the operations this call
1431
+ * could have appended rather than the whole history. All three of its fields
1432
+ * matter:
1433
+ * - `sinceRevision` is the lowest head revision across the targeted scopes, so
1434
+ * it is only a safe window when the selection is scope-limited as well;
1435
+ * - `scopes` limits the response to the scopes the pushed actions target,
1436
+ * without it the server walks every scope of the document
1437
+ * (`packages/reactor/src/core/reactor.ts` `getOperations`);
1438
+ * - `branch` selects the branch the operations are read from, and is the same
1439
+ * variable the mutation writes to. It used to be two - the write went through
1440
+ * a `view`, the filter took its own `branch` - and they had to be kept equal
1441
+ * by hand or the operations came from `main` while the actions were applied
1442
+ * elsewhere. One variable cannot disagree with itself.
1443
+ */
1444
+ const MutateDocumentWithOperationsDocument = gql`
1445
+ mutation MutateDocumentWithOperations(
1446
+ $documentIdentifier: String!
1447
+ $actions: [ActionInput!]!
1448
+ $sinceRevision: Int
1449
+ $scopes: [String!]
1450
+ $branch: String
1451
+ ) {
1452
+ mutateDocument: execute(
1453
+ documentIdentifier: $documentIdentifier
1454
+ actions: $actions
1455
+ branch: $branch
1456
+ ) {
1457
+ ...PHDocumentFields
1458
+ operations(
1459
+ filter: {
1460
+ sinceRevision: $sinceRevision
1461
+ scopes: $scopes
1462
+ branch: $branch
1463
+ }
1464
+ ) {
1465
+ items {
1466
+ ...ReactorOperationFields
1467
+ }
1468
+ }
1469
+ }
1470
+ }
1471
+ ${PhDocumentFieldsFragmentDoc}
1472
+ ${ReactorOperationFieldsFragmentDoc}
1473
+ `;
1474
+ /**
1475
+ * `document`, bounded by a consistency token: the read waits until the
1476
+ * Switchboard's read models hold every operation the token names. The
1477
+ * `consistency` argument is additive on the Switchboard; one without it refuses
1478
+ * this document, and the client falls back to the plain `GetDocument`.
1479
+ */
1480
+ const GetDocumentAtConsistencyDocument = gql`
1481
+ query GetDocumentAtConsistency(
1482
+ $identifier: String!
1483
+ $view: ViewFilterInput
1484
+ $consistency: ConsistencyTokenInput
1485
+ ) {
1486
+ document(identifier: $identifier, view: $view, consistency: $consistency) {
1487
+ document {
1488
+ ...PHDocumentFields
1489
+ }
1490
+ childIds
1491
+ }
1492
+ }
1493
+ ${PhDocumentFieldsFragmentDoc}
1494
+ `;
1495
+ //#endregion
1496
+ //#region src/graphql-client/signing.ts
1497
+ /**
1498
+ * Stamps an action with the head of the scope it targets.
1499
+ *
1500
+ * `prevOpHash` is the hash of the scope state the action is meant to apply to;
1501
+ * for a document at head that is the hash of the last operation in the scope,
1502
+ * which the read path cannot fetch, so it is recomputed from the state.
1503
+ * `prevOpIndex` is the index of that last operation: revisions count
1504
+ * operations and indices are zero based, so an empty scope stamps `-1`, which
1505
+ * matches what the remote controller records.
1506
+ *
1507
+ * `revision` overrides the scope revision the index is derived from. Only a
1508
+ * batch needs it - {@link prepareSignedActions} stamps action N at the revision
1509
+ * the N actions before it will have produced, which the document itself does
1510
+ * not know yet. `prevOpHash` always comes from the supplied document's state.
1511
+ */
1512
+ function stampAction(action, document, revision = document.header.revision[action.scope] ?? 0) {
1513
+ return {
1514
+ ...action,
1515
+ context: {
1516
+ ...action.context,
1517
+ prevOpHash: hashDocumentStateForScope(document, action.scope),
1518
+ prevOpIndex: revision - 1
1519
+ }
1520
+ };
1521
+ }
1522
+ /**
1523
+ * Signs a stamped action for `target`, keeping any signatures it already
1524
+ * carries. The signer reads `context.prevOpHash`, so this runs after
1525
+ * {@link stampAction}. A v2 tuple covers the signer's identity, so the context
1526
+ * takes the signer's user and app even when the action named others.
1527
+ */
1528
+ async function signStampedAction(action, signer, target, signal) {
1529
+ if (!signer.user || !signer.app) throw new Error("cannot sign an action: the signer has no user or app identity");
1530
+ const signature = await signer.signAction(action, target, signal);
1531
+ return {
1532
+ ...action,
1533
+ context: {
1534
+ ...action.context,
1535
+ signer: {
1536
+ ...actionSignerIdentity(signer),
1537
+ signatures: [...action.context?.signer?.signatures ?? [], signature]
1538
+ }
1539
+ }
1540
+ };
1541
+ }
1542
+ /** The log a snapshot's action is written to; the snapshot names the branch read. */
1543
+ function snapshotTarget(action, snapshot) {
1544
+ return actionSigningTarget(action, snapshot.header.id, snapshot.header.branch || "main");
1545
+ }
1546
+ /**
1547
+ * Actions a snapshot batch cannot predict the next state for.
1548
+ *
1549
+ * `UNDO` and `REDO` rewrite history the light read path never fetched (and
1550
+ * the reducer appends no operation for them); `NOOP` is only ever produced
1551
+ * by an undo chain; a `RETRACT` names a target in that unfetched history; the
1552
+ * document-scope actions run through the reactor's
1553
+ * document-action handler rather than a document-model reducer
1554
+ * (`DOCUMENT_SCOPE_ACTIONS` in packages/reactor/src/executor/util.ts) and
1555
+ * `UPGRADE_DOCUMENT` changes which reducer applies mid-batch.
1556
+ */
1557
+ const unsupportedBatchActions = /* @__PURE__ */ new Set([
1558
+ "UNDO",
1559
+ "REDO",
1560
+ "NOOP",
1561
+ "RETRACT",
1562
+ "CREATE_DOCUMENT",
1563
+ "DELETE_DOCUMENT",
1564
+ "UPGRADE_DOCUMENT",
1565
+ "ADD_RELATIONSHIP",
1566
+ "REMOVE_RELATIONSHIP",
1567
+ "UPDATE_RELATIONSHIP"
1568
+ ]);
1569
+ /**
1570
+ * The base-reducer protocol version to predict with when the snapshot's header
1571
+ * carries none.
1572
+ *
1573
+ * `baseReducer` reads `baseReducerVersion(document.header)` for every action and
1574
+ * throws when the header has no `protocolVersions`, which a header built by
1575
+ * {@link phDocumentFromGetDocument} lacks when the server sends none. The
1576
+ * version only selects how UNDO, REDO and RETRACT apply, and every action
1577
+ * reaching the prediction loop is an
1578
+ * ordinary append-only one, so it cannot change the predicted state here; it is
1579
+ * passed purely so the lookup does not throw.
1580
+ */
1581
+ const predictionProtocolVersion = 2;
1582
+ /**
1583
+ * Stamps and signs a batch of actions against one document snapshot, so every
1584
+ * action carries the head its predecessor will leave behind.
1585
+ *
1586
+ * The server executes the array in order, each action against the state the one
1587
+ * before it produced. The snapshot the light client reads has correct state and
1588
+ * per-scope revisions but NO operation history (see `adapter.ts`), so the chain
1589
+ * is predicted here: reduce action N over the working document to get the state
1590
+ * action N+1 hashes, and carry a virtual revision alongside it. The revision has
1591
+ * to be tracked separately because the reducer derives operation indices from
1592
+ * the last stored operation, and with an empty history that counts from zero
1593
+ * rather than from the document's real revision.
1594
+ *
1595
+ * A single action needs no prediction and therefore no `module`, which keeps
1596
+ * today's callers working unchanged. Two or more require the document's exact
1597
+ * reducer, one shared scope (the reactor rejects mixed-scope jobs) and only
1598
+ * append-only actions. Anything else rejects: a batch that cannot be predicted
1599
+ * must fail before the mutation, never be downgraded to unsigned.
1600
+ */
1601
+ async function prepareSignedActions(actions, snapshot, signer, module, signal) {
1602
+ if (actions.length === 0) return [];
1603
+ if (actions.length === 1) return [await signStampedAction(stampAction(actions[0], snapshot), signer, snapshotTarget(actions[0], snapshot), signal)];
1604
+ const scope = sharedScope(actions);
1605
+ assertSupportedBatch(actions);
1606
+ if (!module) throw new Error(`cannot sign ${actions.length} actions: no document model module for ${snapshot.header.documentType} was supplied, so the batch state cannot be predicted`);
1607
+ let working = {
1608
+ ...snapshot,
1609
+ operations: {
1610
+ ...snapshot.operations,
1611
+ [scope]: [...snapshot.operations[scope] ?? []]
1612
+ }
1613
+ };
1614
+ let revision = snapshot.header.revision[scope] ?? 0;
1615
+ const signed = [];
1616
+ for (const [index, action] of actions.entries()) {
1617
+ throwIfAborted(signal, index);
1618
+ const stamped = stampAction(action, working, revision);
1619
+ const signedAction = await signStampedAction(stamped, signer, snapshotTarget(stamped, snapshot), signal);
1620
+ signed.push(signedAction);
1621
+ const before = scopeOperationCount(working, scope);
1622
+ let next;
1623
+ try {
1624
+ next = module.reducer(working, signedAction, void 0, { protocolVersion: resolveBaseReducerVersion(working.header.protocolVersions) ?? predictionProtocolVersion });
1625
+ } catch (error) {
1626
+ throw new Error(`cannot sign action ${index} (${action.type}): the ${snapshot.header.documentType} reducer rejected it, so the rest of the batch cannot be predicted`, { cause: error });
1627
+ }
1628
+ const after = scopeOperationCount(next, scope);
1629
+ if (after !== before + 1) throw new Error(`cannot sign action ${index} (${action.type}): the reducer appended ${after - before} operations to ${scope}, expected exactly 1`);
1630
+ working = next;
1631
+ revision += 1;
1632
+ }
1633
+ return signed;
1634
+ }
1635
+ /**
1636
+ * How many operations a scope holds.
1637
+ *
1638
+ * The index signature types the array as always present, but a module's reducer
1639
+ * is arbitrary code: one that hands back a document without the scope should
1640
+ * produce the actionable error above, not a `TypeError` on `.length`.
1641
+ */
1642
+ function scopeOperationCount(document, scope) {
1643
+ return document.operations[scope]?.length ?? 0;
1644
+ }
1645
+ /** The one scope a reactor job may span (`getSharedActionScope`). */
1646
+ function sharedScope(actions) {
1647
+ const scope = actions[0].scope;
1648
+ const mixed = actions.find((action) => action.scope !== scope);
1649
+ if (mixed) throw new Error(`cannot sign a batch spanning scopes "${scope}" and "${mixed.scope}": every action in one request must share a scope`);
1650
+ return scope;
1651
+ }
1652
+ function assertSupportedBatch(actions) {
1653
+ const unsupported = actions.find((action) => unsupportedBatchActions.has(action.type));
1654
+ if (unsupported) throw new Error(`cannot sign a batch containing ${unsupported.type}: it needs operation history or an alternate executor path, so send it as a single action`);
1655
+ }
1656
+ function throwIfAborted(signal, index) {
1657
+ if (signal?.aborted) throw new Error(`signing aborted before action ${index}`, { cause: signal.reason });
1658
+ }
1659
+ //#endregion
1660
+ //#region src/graphql-client/static-package-manager.ts
1661
+ /**
1662
+ * A fixed set of packages presented through the `IPackageManager` interface,
1663
+ * so the package-derived hooks - `useDocumentModelModules`,
1664
+ * `useDocumentModelModuleById`, `useEditorModules`, `useVetraPackages` - work
1665
+ * below `GraphQLReactorProvider` exactly as they do below Connect.
1666
+ *
1667
+ * Connect's package manager installs, updates and removes packages at runtime.
1668
+ * A light app instead declares its packages once, as code it imports itself
1669
+ * (every generated package root exports `manifest`, `documentModels`, `editors`
1670
+ * and `upgradeManifests` by name), so every mutating member throws and
1671
+ * `subscribe` never emits. For hand-picked modules without package artifacts,
1672
+ * {@link packageFromDocumentModels} wraps them in one synthetic package.
1673
+ */
1674
+ var StaticPackageManager = class {
1675
+ registryUrl = null;
1676
+ packages;
1677
+ constructor(packages) {
1678
+ this.packages = [...packages];
1679
+ }
1680
+ /**
1681
+ * Resolves a module by document type across all packages. Mirrors the
1682
+ * registry's semantics (`IDocumentModelRegistry.getModule`): the LATEST
1683
+ * version wins, with `version ?? 1` as each module's default.
1684
+ */
1685
+ load(documentType) {
1686
+ const modules = this.packages.flatMap((pkg) => pkg.documentModels);
1687
+ try {
1688
+ return Promise.resolve(resolveDocumentModelModule(modules, documentType));
1689
+ } catch (error) {
1690
+ return Promise.reject(error);
1691
+ }
1692
+ }
1693
+ subscribe(_handler) {
1694
+ return () => {};
1695
+ }
1696
+ getPackageSource(_packageName) {
1697
+ return null;
1698
+ }
1699
+ getPackageVersion(_packageName) {}
1700
+ getPackageSpec(_packageName) {}
1701
+ getRegistryPackages() {
1702
+ return [];
1703
+ }
1704
+ addPackage(_packageName) {
1705
+ throw staticPackageManagerError("addPackage");
1706
+ }
1707
+ addPackages(_packageNames) {
1708
+ throw staticPackageManagerError("addPackages");
1709
+ }
1710
+ removePackage(_name) {
1711
+ throw staticPackageManagerError("removePackage");
1712
+ }
1713
+ updateLocalPackage(_pkg, _version) {
1714
+ throw staticPackageManagerError("updateLocalPackage");
1715
+ }
1716
+ addLocalPackage(_name, _loadedPackage, _version) {
1717
+ throw staticPackageManagerError("addLocalPackage");
1718
+ }
1719
+ };
1720
+ /**
1721
+ * Resolves one document-model module out of a flat module list, with the same
1722
+ * rule the reactor registry uses (`IDocumentModelRegistry.getModule`, at
1723
+ * packages/reactor/src/registry/implementation.ts): with a `version`, only an
1724
+ * EXACT `version ?? 1` match resolves; without one, the LATEST version wins.
1725
+ *
1726
+ * Signing an existing document needs the exact rule. A document carries the
1727
+ * model version it was written with in `state.document.version`, and its
1728
+ * reducer is the only one whose operations that document's history can accept -
1729
+ * so "latest" is correct only when no version is asked for.
1730
+ *
1731
+ * Pure and dependency-free on purpose: this is reachable from the browser
1732
+ * entry, so it must not pull the reactor registry in as a value.
1733
+ */
1734
+ function resolveDocumentModelModule(modules, documentType, version) {
1735
+ let latestModule;
1736
+ let latestVersion = -1;
1737
+ for (const module of modules) {
1738
+ if (module.documentModel.global.id !== documentType) continue;
1739
+ const moduleVersion = module.version ?? 1;
1740
+ if (version !== void 0 && moduleVersion === version) return module;
1741
+ if (moduleVersion > latestVersion) {
1742
+ latestVersion = moduleVersion;
1743
+ latestModule = module;
1744
+ }
1745
+ }
1746
+ if (version === void 0 && latestModule) return latestModule;
1747
+ throw new Error(version === void 0 ? `Unknown document type: ${documentType}` : `Unknown document model version: ${documentType} v${version}` + (latestModule ? ` (available: ${availableVersions(modules, documentType).join(", ")})` : " (no module for this document type)"));
1748
+ }
1749
+ function availableVersions(modules, documentType) {
1750
+ return modules.filter((module) => module.documentModel.global.id === documentType).map((module) => module.version ?? 1).sort((a, b) => a - b);
1751
+ }
1752
+ function staticPackageManagerError(member) {
1753
+ return /* @__PURE__ */ new Error(`${member} is not supported: StaticPackageManager holds a fixed set of packages`);
1754
+ }
1755
+ /**
1756
+ * Wraps hand-picked modules in one synthetic `DocumentModelLib`, for apps that
1757
+ * assemble their model list from mixed sources instead of passing whole
1758
+ * packages. The manifest is fabricated - loose modules carry none - so prefer
1759
+ * the `packages` prop with the real package exports when you have them: a real
1760
+ * package also carries `editors`, which makes the editor hooks work.
1761
+ */
1762
+ function packageFromDocumentModels(documentModels) {
1763
+ return {
1764
+ manifest: {
1765
+ name: "graphql-reactor-provider",
1766
+ description: "Document models passed to GraphQLReactorProvider"
1767
+ },
1768
+ documentModels,
1769
+ editors: []
1770
+ };
1771
+ }
1772
+ //#endregion
1773
+ //#region src/graphql-client/subgraph.ts
1774
+ /** What {@link describeGraphQLDocument} could not read off a document. */
1775
+ const unnamedOperation = "AnonymousOperation";
1776
+ const defaultOperationType = "query";
1777
+ /**
1778
+ * Derives a subgraph's endpoint from the Switchboard's GraphQL endpoint.
1779
+ *
1780
+ * Subgraphs are served next to the supergraph, at `<graphql base>/<name>`, so
1781
+ * `http://localhost:4001/graphql` plus `statements` is
1782
+ * `http://localhost:4001/graphql/statements`.
1783
+ */
1784
+ function subgraphUrlFromGraphqlUrl(url, name) {
1785
+ const trimmed = name.trim();
1786
+ if (trimmed === "") throw new Error("a subgraph name is required");
1787
+ return `${url.replace(/\/+$/, "")}/${trimmed}`;
1788
+ }
1789
+ /**
1790
+ * Reads the operation name and type off a document, for the middleware.
1791
+ *
1792
+ * Nothing depends on getting this right - it is reported to the middleware, not
1793
+ * sent to the server - so an unreadable document falls back to an anonymous
1794
+ * query rather than throwing.
1795
+ */
1796
+ function describeGraphQLDocument(document) {
1797
+ if (typeof document !== "string") {
1798
+ const operation = document.definitions.find((definition) => definition.kind === Kind.OPERATION_DEFINITION);
1799
+ if (!operation || operation.kind !== Kind.OPERATION_DEFINITION) return {
1800
+ operationName: unnamedOperation,
1801
+ operationType: defaultOperationType
1802
+ };
1803
+ return {
1804
+ operationName: operation.name?.value ?? unnamedOperation,
1805
+ operationType: operation.operation
1806
+ };
1807
+ }
1808
+ const match = /\b(query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/.exec(document);
1809
+ if (!match) return {
1810
+ operationName: unnamedOperation,
1811
+ operationType: /\bmutation\b/.test(document) ? "mutation" : defaultOperationType
1812
+ };
1813
+ return {
1814
+ operationName: match[2],
1815
+ operationType: match[1]
1816
+ };
1817
+ }
1818
+ /**
1819
+ * Binds typed subgraph SDKs to one Switchboard's transport and auth.
1820
+ *
1821
+ * Every capability a Switchboard exposes lives behind the same base URL, so an
1822
+ * app should not have to build a second client - with a second copy of the auth
1823
+ * configuration - to reach a project's own subgraph. The registry derives the
1824
+ * endpoint, reuses one transport per subgraph and hands the code generator's
1825
+ * `getSdk` the very middleware the reactor operations already go through.
1826
+ *
1827
+ * Transport and typing only: subgraph results are not cached and produce no
1828
+ * change events.
1829
+ */
1830
+ var SubgraphSdkRegistry = class {
1831
+ url;
1832
+ middleware;
1833
+ fetch;
1834
+ bindings = /* @__PURE__ */ new Map();
1835
+ constructor(url, middleware, fetch) {
1836
+ this.url = url;
1837
+ this.middleware = middleware;
1838
+ this.fetch = fetch;
1839
+ }
1840
+ /**
1841
+ * Returns the subgraph's SDK, building it on first use.
1842
+ *
1843
+ * The transport is kept per subgraph name, so repeated calls do not rebuild
1844
+ * it. The SDK itself is only reused when the same factory is passed again -
1845
+ * two different generated SDKs over one subgraph each get their own, rather
1846
+ * than the second call being handed the first one's methods.
1847
+ */
1848
+ get(name, getSdk) {
1849
+ const binding = this.binding(name);
1850
+ if (binding.factory === getSdk) return binding.sdk;
1851
+ const sdk = getSdk(binding.transport, this.middleware);
1852
+ binding.factory = getSdk;
1853
+ binding.sdk = sdk;
1854
+ return sdk;
1855
+ }
1856
+ /** Returns the subgraph's endpoint, for diagnostics and tests. */
1857
+ urlFor(name) {
1858
+ return subgraphUrlFromGraphqlUrl(this.url, name);
1859
+ }
1860
+ binding(name) {
1861
+ const existing = this.bindings.get(name);
1862
+ if (existing) return existing;
1863
+ const binding = { transport: new GraphQLClient(this.urlFor(name), { fetch: this.fetch }) };
1864
+ this.bindings.set(name, binding);
1865
+ return binding;
1866
+ }
1867
+ };
1868
+ //#endregion
1869
+ //#region src/graphql-client/subscriptions.ts
1870
+ /**
1871
+ * The 4403 close reasons a Switchboard refuses a handshake with.
1872
+ *
1873
+ * Mirrors `WS_AUTH_CLOSE_REASONS` in `@powerhousedao/reactor-api`
1874
+ * (`src/graphql/gateway/types.ts`). This package does not depend on that one,
1875
+ * so the strings are duplicated and are a wire contract: change them on both
1876
+ * sides or not at all.
1877
+ */
1878
+ const authCloseReasons = ["authentication-required", "bearer-rejected"];
1879
+ /** graphql-ws's own `isLikeCloseEvent`, which it does not export. */
1880
+ function isLikeCloseEvent(value) {
1881
+ return typeof value === "object" && value !== null && "code" in value && "reason" in value;
1882
+ }
1883
+ /**
1884
+ * Whether a socket failure is the Switchboard refusing the credentials sent.
1885
+ *
1886
+ * Keyed on the close reason, not the code: both refusals close 4403, because
1887
+ * `connectionParams` is resolved per connect and a reconnect carrying a fresh
1888
+ * token genuinely succeeds. What the reason adds is that *this* attempt cannot
1889
+ * be fixed by repeating it.
1890
+ */
1891
+ function isAuthRefusalClose(error) {
1892
+ return isLikeCloseEvent(error) && authCloseReasons.includes(error.reason);
1893
+ }
1894
+ /**
1895
+ * Opens one `documentChanges` subscription and feeds every event to `onEvent`.
1896
+ *
1897
+ * The subscription is a firehose: no `search` argument, so the server sends
1898
+ * every change the connection is allowed to see and the caller filters. This is
1899
+ * the only module that knows about `graphql-ws`.
1900
+ *
1901
+ * Returns the stop function, which cancels the subscription and closes the
1902
+ * socket. It is safe to call more than once.
1903
+ */
1904
+ function startDocumentChangesSubscription(options) {
1905
+ const client = createClient({
1906
+ url: options.wsUrl,
1907
+ connectionParams: options.connectionParams,
1908
+ shouldRetry: (errOrCloseEvent) => isLikeCloseEvent(errOrCloseEvent) && !isAuthRefusalClose(errOrCloseEvent)
1909
+ });
1910
+ const unsubscribe = client.subscribe({
1911
+ operationName: "DocumentChanges",
1912
+ query: print(DocumentChangesDocument)
1913
+ }, {
1914
+ next: (result) => {
1915
+ const event = result.data?.documentChanges;
1916
+ if (event) options.onEvent(event);
1917
+ },
1918
+ error: (error) => options.onError(error),
1919
+ complete: () => void 0
1920
+ });
1921
+ let stopped = false;
1922
+ return () => {
1923
+ if (stopped) return;
1924
+ stopped = true;
1925
+ unsubscribe();
1926
+ client.dispose();
1927
+ };
1928
+ }
1929
+ /**
1930
+ * Opens the socket write handles wait on. `graphql-ws` multiplexes every
1931
+ * watched job over it and closes it once the last watch stops.
1932
+ */
1933
+ function createJobChangesSocket(options) {
1934
+ let client;
1935
+ const clientOf = () => client ??= createClient({
1936
+ url: options.wsUrl,
1937
+ connectionParams: options.connectionParams,
1938
+ shouldRetry: (errOrCloseEvent) => isLikeCloseEvent(errOrCloseEvent) && !isAuthRefusalClose(errOrCloseEvent)
1939
+ });
1940
+ return {
1941
+ watch(jobId, onEvent, onError) {
1942
+ const unsubscribe = clientOf().subscribe({
1943
+ operationName: "JobChanges",
1944
+ query: print(JobChangesDocument),
1945
+ variables: { jobId }
1946
+ }, {
1947
+ next: (result) => {
1948
+ const event = result.data?.jobChanges;
1949
+ if (event) onEvent(event);
1950
+ },
1951
+ error: (error) => onError(error),
1952
+ complete: () => void 0
1953
+ });
1954
+ let stopped = false;
1955
+ return () => {
1956
+ if (stopped) return;
1957
+ stopped = true;
1958
+ unsubscribe();
1959
+ };
1960
+ },
1961
+ dispose() {
1962
+ const current = client;
1963
+ client = void 0;
1964
+ current?.dispose();
1965
+ }
1966
+ };
1967
+ }
1968
+ /**
1969
+ * Derives the websocket endpoint from the GraphQL http endpoint.
1970
+ *
1971
+ * `http://host/graphql` becomes `ws://host/graphql/subscriptions`, which is
1972
+ * where the Switchboard mounts its websocket server (`packages/reactor-api`
1973
+ * `startServer`). A URL that already speaks `ws`/`wss` only gets the path.
1974
+ */
1975
+ function subscriptionsUrlFromGraphqlUrl(url) {
1976
+ const trimmed = url.replace(/\/+$/, "");
1977
+ return `${trimmed.startsWith("https://") ? `wss://${trimmed.slice(8)}` : trimmed.startsWith("http://") ? `ws://${trimmed.slice(7)}` : trimmed}/subscriptions`;
1978
+ }
1979
+ /**
1980
+ * Turns a bearer token provider into `connectionParams`.
1981
+ *
1982
+ * The header key is the lowercase `authorization` the Switchboard's websocket
1983
+ * context factory reads. Without a token the payload is empty: an open
1984
+ * Switchboard serves anonymous subscribers.
1985
+ */
1986
+ function makeAuthConnectionParams(tokenProvider) {
1987
+ return async () => {
1988
+ const token = await tokenProvider();
1989
+ if (!token) return {};
1990
+ return { authorization: `Bearer ${token}` };
1991
+ };
1992
+ }
1993
+ //#endregion
1994
+ //#region src/graphql-client/write-handles.ts
1995
+ /** Whether a job status has reached a stage, FAILED counting as settled. */
1996
+ function settlesGraphQLJobStage(status, stage) {
1997
+ const value = status;
1998
+ if (value === "FAILED" || value === "READ_READY") return true;
1999
+ return stage === "written" && value === "WRITE_READY";
2000
+ }
2001
+ function emptyToken() {
2002
+ return {
2003
+ version: 1,
2004
+ createdAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),
2005
+ coordinates: []
2006
+ };
2007
+ }
2008
+ function abortError(signal) {
2009
+ const reason = signal.reason;
2010
+ return reason instanceof Error ? reason : new Error(String(reason));
2011
+ }
2012
+ /** `promise`, rejected early when `signal` aborts. */
2013
+ function bounded(promise, signal) {
2014
+ if (!signal) return promise;
2015
+ if (signal.aborted) return Promise.reject(abortError(signal));
2016
+ return new Promise((resolve, reject) => {
2017
+ const onAbort = () => reject(abortError(signal));
2018
+ signal.addEventListener("abort", onAbort, { once: true });
2019
+ promise.then((value) => {
2020
+ signal.removeEventListener("abort", onAbort);
2021
+ resolve(value);
2022
+ }, (error) => {
2023
+ signal.removeEventListener("abort", onAbort);
2024
+ reject(error instanceof Error ? error : new Error(String(error)));
2025
+ });
2026
+ });
2027
+ }
2028
+ /**
2029
+ * A write handle over a job the Switchboard accepted (`executeAsync`).
2030
+ *
2031
+ * Each stage is the waiter's: `jobStatus`, woken early by the `jobChanges`
2032
+ * subscription when the client has realtime. Stage promises are created on
2033
+ * first access, so a fire-and-forget caller never owns a rejection. A FAILED
2034
+ * job rejects a stage with {@link JobFailedError}.
2035
+ *
2036
+ * `document()` with no view is read once and shared, so the client's own
2037
+ * change announcement and the caller's read-back cost one request.
2038
+ */
2039
+ var GraphQLJobWriteHandle = class {
2040
+ job;
2041
+ jobId;
2042
+ documentId;
2043
+ branch;
2044
+ wait;
2045
+ reader;
2046
+ signal;
2047
+ writtenReceipt;
2048
+ readableReceipt;
2049
+ defaultDocument;
2050
+ constructor(job, documentId, branch, wait, reader, signal) {
2051
+ this.job = job;
2052
+ this.jobId = job.id;
2053
+ this.documentId = documentId;
2054
+ this.branch = branch;
2055
+ this.wait = wait;
2056
+ this.reader = reader;
2057
+ this.signal = signal;
2058
+ }
2059
+ get written() {
2060
+ this.writtenReceipt ??= this.receiptAt("written");
2061
+ return this.writtenReceipt;
2062
+ }
2063
+ get readable() {
2064
+ this.readableReceipt ??= this.receiptAt("readable");
2065
+ return this.readableReceipt;
2066
+ }
2067
+ async document(view, signal) {
2068
+ if (view !== void 0) {
2069
+ const receipt = await bounded(this.readable, signal);
2070
+ return this.reader(receipt, view, signal);
2071
+ }
2072
+ this.defaultDocument ??= this.readable.then((receipt) => this.reader(receipt, void 0, void 0));
2073
+ return bounded(this.defaultDocument, signal);
2074
+ }
2075
+ async receiptAt(stage) {
2076
+ const job = await this.wait(this.jobId, stage, this.signal);
2077
+ if (job.status === "FAILED") throw new JobFailedError(job);
2078
+ return {
2079
+ job,
2080
+ token: job.consistencyToken,
2081
+ documentId: this.documentId,
2082
+ branch: this.branch
2083
+ };
2084
+ }
2085
+ };
2086
+ /**
2087
+ * A write handle for a write the Switchboard applied before answering: the
2088
+ * synchronous `createDocument` and `deleteDocument` mutations name no job. Both
2089
+ * stages are settled; `jobId` is empty and the receipt's job is a READ_READY
2090
+ * placeholder with an empty token, as the reactor's own settled handle has.
2091
+ */
2092
+ var GraphQLSettledWriteHandle = class {
2093
+ jobId = "";
2094
+ documentId;
2095
+ branch;
2096
+ receipt;
2097
+ reader;
2098
+ constructor(documentId, branch, reader) {
2099
+ this.documentId = documentId;
2100
+ this.branch = branch;
2101
+ this.reader = reader;
2102
+ const token = emptyToken();
2103
+ this.receipt = {
2104
+ job: {
2105
+ id: "",
2106
+ documentId,
2107
+ status: "READ_READY",
2108
+ createdAtUtcIso: token.createdAtUtcIso,
2109
+ consistencyToken: token,
2110
+ meta: {
2111
+ batchId: "",
2112
+ batchJobIds: []
2113
+ }
2114
+ },
2115
+ token,
2116
+ documentId,
2117
+ branch
2118
+ };
2119
+ }
2120
+ get written() {
2121
+ return Promise.resolve(this.receipt);
2122
+ }
2123
+ get readable() {
2124
+ return Promise.resolve(this.receipt);
2125
+ }
2126
+ document(view, signal) {
2127
+ return this.reader(this.receipt, view, signal);
2128
+ }
2129
+ };
2130
+ //#endregion
2131
+ //#region src/graphql-client/graphql-reactor-client.ts
2132
+ const BUILT_IN_MODELS = [driveDocumentModelModule];
2133
+ /** Paging defaults, matching the reactor's own client. */
2134
+ const defaultPaging = {
2135
+ cursor: "0",
2136
+ limit: 100
2137
+ };
2138
+ const JOB_POLL_INTERVAL_MS = 250;
2139
+ /** The first `jobStatus` poll of a write handle's stage wait, doubling from here. */
2140
+ const STAGE_POLL_START_MS = 25;
2141
+ /**
2142
+ * The longest a stage wait sleeps between `jobStatus` polls while the
2143
+ * `jobChanges` subscription is up: the subscription wakes it early, and the
2144
+ * poll is the safety net for an event that raced the subscription.
2145
+ */
2146
+ const STAGE_POLL_REALTIME_MAX_MS = 1e3;
2147
+ /**
2148
+ * The marker {@link isGraphQLReactorClient} looks for.
2149
+ *
2150
+ * A page can end up with two copies of this module - an app that bundles a
2151
+ * package carrying its own copy, or a dev server that hot-replaced it - and
2152
+ * then `instanceof` compares an instance against the other copy's class object
2153
+ * and answers `false`. A branded property survives both.
2154
+ */
2155
+ const graphQLReactorClientBrand = "__powerhouseGraphQLReactorClient";
2156
+ /**
2157
+ * A light implementation of {@link IReactorBrowserClient} that talks plain
2158
+ * GraphQL to a Switchboard, with no reactor in the bundle.
2159
+ *
2160
+ * It fills the same `window.ph` slots the full in-browser reactor client fills,
2161
+ * so the reactor-browser hooks cannot tell the two apart.
2162
+ */
2163
+ var GraphQLReactorClient = class {
2164
+ /** See {@link isGraphQLReactorClient}. */
2165
+ [graphQLReactorClientBrand] = true;
2166
+ sdk;
2167
+ /** For `executeBatch`, the one write a request waits for: see {@link batchRequestTimeoutMs}. */
2168
+ batchSdk;
2169
+ subgraphs;
2170
+ listeners = [];
2171
+ tokenProvider;
2172
+ subscriptionsUrl;
2173
+ documentModels;
2174
+ resolveSigner;
2175
+ driveIdFor;
2176
+ undoRedoChains = /* @__PURE__ */ new Map();
2177
+ stopRealtime;
2178
+ realtimeStarted = false;
2179
+ realtimeGeneration = 0;
2180
+ realtimeErrorLogged = false;
2181
+ /** Whether the last socket died because the Switchboard refused its credentials. */
2182
+ realtimeRefusedCredentials = false;
2183
+ /** The socket write handles wait on; opened by the first stage wait. */
2184
+ jobSocket;
2185
+ /** Set once the `jobChanges` subscription failed; stage waits then only poll. */
2186
+ jobRealtimeBroken = false;
2187
+ /** Set once the Switchboard refused the `document` query's `consistency` argument. */
2188
+ consistencyUnsupported = false;
2189
+ driveNodes;
2190
+ /**
2191
+ * The read half: the reads the hooks make. Every method is this client's
2192
+ * own; nothing that writes is reachable from it.
2193
+ */
2194
+ read;
2195
+ /**
2196
+ * The write half. `execute` submits through `executeAsync` and hands back a
2197
+ * handle whose `written` and `readable` resolve from `jobStatus`, woken by
2198
+ * the `jobChanges` subscription when realtime is on, and whose `document()`
2199
+ * runs the `document` query bounded by the receipt's token. `create` and
2200
+ * `deleteDocument` have no asynchronous mutation: they run the synchronous
2201
+ * ones and hand back a settled handle.
2202
+ */
2203
+ write;
2204
+ constructor(options) {
2205
+ this.tokenProvider = options.tokenProvider ?? ambientRenownTokenProvider;
2206
+ const models = options.documentModels;
2207
+ if (typeof models === "function") this.documentModels = models;
2208
+ else {
2209
+ const copied = [...models ?? []];
2210
+ this.documentModels = () => copied;
2211
+ }
2212
+ const signer = options.signer;
2213
+ this.resolveSigner = typeof signer === "function" ? signer : signer ? () => signer : ambientRenownSigner;
2214
+ this.driveIdFor = options.driveIdFor;
2215
+ this.subscriptionsUrl = options.realtime === false ? void 0 : options.subscriptionsUrl ?? subscriptionsUrlFromGraphqlUrl(options.url);
2216
+ const middleware = withWrongBackendErrors(makeAuthMiddleware(this.tokenProvider));
2217
+ const fetch = options.requestTimeoutMs === void 0 ? options.fetch : withRequestDeadline(options.requestTimeoutMs, options.fetch);
2218
+ this.sdk = options.graphqlClient ?? createClient$1(new GraphQLClient(options.url, { fetch }), middleware);
2219
+ this.batchSdk = options.graphqlClient !== void 0 || options.batchRequestTimeoutMs === void 0 ? this.sdk : createClient$1(new GraphQLClient(options.url, { fetch: withRequestDeadline(options.batchRequestTimeoutMs, options.fetch) }), middleware);
2220
+ this.subgraphs = new SubgraphSdkRegistry(options.url, middleware, fetch);
2221
+ this.driveNodes = new GraphQLDriveNodeSource(this.sdk, driveIdHeaders);
2222
+ this.read = new GraphQLReadHalf(this, this.driveNodes);
2223
+ this.write = {
2224
+ execute: (documentIdentifier, branch, actions, signal) => this.submitExecute(documentIdentifier, branch, actions, signal),
2225
+ create: (document, parentIdentifier, signal) => this.submitCreate(document, parentIdentifier, signal),
2226
+ deleteDocument: (identifier, propagate, signal) => this.submitDeleteDocument(identifier, propagate, signal)
2227
+ };
2228
+ }
2229
+ /**
2230
+ * The Switchboard's drive node queries as a node source, for every drive
2231
+ * type. `read.drives` answers from it.
2232
+ */
2233
+ nodeSource() {
2234
+ return this.driveNodes;
2235
+ }
2236
+ /**
2237
+ * Reads a document. With a consistency token that names any coordinate, the
2238
+ * Switchboard waits until its read models hold them; one without the
2239
+ * `document` query's `consistency` argument is read without it, which after
2240
+ * a write's `readable` stage still sees the write on a single node.
2241
+ */
2242
+ async get(identifier, view, signal, consistencyToken) {
2243
+ const viewInput = viewFilterInputFromViewFilter(view);
2244
+ const document = (consistencyToken && consistencyToken.coordinates.length > 0 ? await this.getDocumentAtConsistency(identifier, viewInput, consistencyToken, signal) : await this.sdk.GetDocument({
2245
+ identifier,
2246
+ view: viewInput
2247
+ }, void 0, signal)).document;
2248
+ if (!document) throw new Error(`Document not found: ${identifier}`);
2249
+ return phDocumentFromGetDocument(document.document, view?.branch);
2250
+ }
2251
+ /**
2252
+ * Reads documents by id, in the order given; throws if any is missing. Each
2253
+ * chunk of {@link GET_MANY_CHUNK_SIZE} ids is one request holding an aliased
2254
+ * `document` field per id, with the selection and arguments `get` sends.
2255
+ */
2256
+ async getMany(documentIds, view, signal, consistencyToken) {
2257
+ const viewInput = viewFilterInputFromViewFilter(view);
2258
+ const token = consistencyToken && consistencyToken.coordinates.length > 0 ? consistencyToken : void 0;
2259
+ const chunks = [];
2260
+ for (let i = 0; i < documentIds.length; i += GET_MANY_CHUNK_SIZE) chunks.push(documentIds.slice(i, i + GET_MANY_CHUNK_SIZE));
2261
+ return (await Promise.all(chunks.map((chunk) => this.getDocumentChunk(chunk, viewInput, token, signal)))).flat().map((document) => phDocumentFromGetDocument(document, view?.branch));
2262
+ }
2263
+ /** One chunk of `getMany`, with the `consistency` argument while the Switchboard accepts it. */
2264
+ async getDocumentChunk(identifiers, view, token, signal) {
2265
+ if (token && !this.consistencyUnsupported) try {
2266
+ return await this.runGetDocuments(identifiers, view, consistencyInputFromToken(token), signal);
2267
+ } catch (error) {
2268
+ if (!refusesConsistencyArgument(error)) throw error;
2269
+ this.consistencyUnsupported = true;
2270
+ }
2271
+ return this.runGetDocuments(identifiers, view, void 0, signal);
2272
+ }
2273
+ async runGetDocuments(identifiers, view, consistency, signal) {
2274
+ const variables = { view };
2275
+ const definitions = ["$view: ViewFilterInput"];
2276
+ let consistencyArgument = "";
2277
+ if (consistency) {
2278
+ variables.consistency = consistency;
2279
+ definitions.push("$consistency: ConsistencyTokenInput");
2280
+ consistencyArgument = ", consistency: $consistency";
2281
+ }
2282
+ const fields = identifiers.map((identifier, i) => {
2283
+ variables[`id${i}`] = identifier;
2284
+ definitions.push(`$id${i}: String!`);
2285
+ return `d${i}: document(identifier: $id${i}, view: $view${consistencyArgument}) { document { ...PHDocumentFields } childIds }`;
2286
+ });
2287
+ const query = [
2288
+ `query GetDocuments(${definitions.join(", ")}) {`,
2289
+ ...fields,
2290
+ "}",
2291
+ PH_DOCUMENT_FIELDS_SOURCE
2292
+ ].join("\n");
2293
+ const data = await this.sdk.RunDocument({
2294
+ operationName: "GetDocuments",
2295
+ operationType: "query",
2296
+ document: query,
2297
+ variables,
2298
+ signal
2299
+ });
2300
+ return identifiers.map((identifier, i) => {
2301
+ const result = data[`d${i}`];
2302
+ if (!result) throw new Error(`Document not found: ${identifier}`);
2303
+ return result.document;
2304
+ });
2305
+ }
2306
+ /**
2307
+ * Whether the Switchboard would serve the document to this client's caller,
2308
+ * from its `documentServed` query: the same read gate `find` passes. Absent
2309
+ * or withheld is `false`; a failure to decide throws.
2310
+ *
2311
+ * A point-in-time view throws {@link GraphQLOperationNotSupportedError}, as
2312
+ * does a Switchboard without the query.
2313
+ */
2314
+ async isServed(identifier, view, signal) {
2315
+ const viewInput = viewFilterInputFromViewFilter(view);
2316
+ try {
2317
+ return (await this.sdk.GetDocumentServed({
2318
+ idOrSlug: identifier,
2319
+ view: viewInput
2320
+ }, void 0, signal)).documentServed;
2321
+ } catch (error) {
2322
+ if (queriesUnknownField(error, "documentServed")) throw new GraphQLOperationNotSupportedError("isServed", "the Switchboard predates the documentServed query");
2323
+ throw error;
2324
+ }
2325
+ }
2326
+ async getOperations(documentIdentifier, view, filter, paging, signal) {
2327
+ const viewInput = viewFilterInputFromViewFilter(view);
2328
+ const operationsFilter = {
2329
+ documentId: documentIdentifier,
2330
+ branch: viewInput?.branch,
2331
+ scopes: viewInput?.scopes,
2332
+ actionTypes: filter?.actionTypes,
2333
+ timestampFrom: filter?.timestampFrom,
2334
+ timestampTo: filter?.timestampTo,
2335
+ sinceRevision: filter?.sinceRevision
2336
+ };
2337
+ const page = (await this.sdk.GetDocumentOperations({
2338
+ filter: operationsFilter,
2339
+ paging: pagingInputFromPaging(paging)
2340
+ }, void 0, signal)).documentOperations;
2341
+ const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
2342
+ const effectivePaging = paging ?? defaultPaging;
2343
+ return {
2344
+ results: page.items.map((item) => remoteOperationToLocal(item)),
2345
+ options: effectivePaging,
2346
+ nextCursor,
2347
+ next: nextCursor ? () => this.getOperations(documentIdentifier, view, filter, {
2348
+ cursor: nextCursor,
2349
+ limit: effectivePaging.limit
2350
+ }, signal) : void 0
2351
+ };
2352
+ }
2353
+ /**
2354
+ * Filters documents by criteria over the Switchboard's `findDocuments` query.
2355
+ *
2356
+ * The query filters by `type` and `parentId` only, at head. A search naming
2357
+ * `ids` or `slugs` (present, whatever its length) and a point-in-time view are
2358
+ * each by-contract limitations the query cannot express -- running it anyway
2359
+ * would return every document instead of the named ones, or head instead of
2360
+ * the asked-for revision, a silently wrong answer. {@link findIsServableOverGraphQL}
2361
+ * is the single predicate that decides this, and an unservable `find` throws
2362
+ * {@link GraphQLOperationNotSupportedError}. Drive enumeration itself filters
2363
+ * by `type` at head, which is served.
2364
+ */
2365
+ async find(search, view, paging, signal) {
2366
+ if (!findIsServableOverGraphQL(search, view)) throw new GraphQLOperationNotSupportedError("find", searchNamesIdentifiers(search) ? "it cannot filter by ids or slugs: the Switchboard findDocuments query filters only by type and parentId" : "point-in-time views are not supported by GraphQLReactorClient");
2367
+ const viewInput = viewFilterInputFromViewFilter(view);
2368
+ const effectivePaging = paging ?? defaultPaging;
2369
+ const result = await this.sdk.FindDocuments({
2370
+ search: {
2371
+ type: search.type,
2372
+ parentId: search.parentId
2373
+ },
2374
+ view: viewInput,
2375
+ paging: pagingInputFromPaging(effectivePaging)
2376
+ }, search.parentId === void 0 ? void 0 : this.driveIdHeaders({
2377
+ method: "find",
2378
+ parentId: search.parentId
2379
+ }), signal);
2380
+ return this.toDocumentResults(result.findDocuments, effectivePaging, view?.branch, (cursor, limit) => this.find(search, view, {
2381
+ cursor,
2382
+ limit
2383
+ }, signal));
2384
+ }
2385
+ async getOutgoingRelationships(sourceIdentifier, relationshipType, view, paging, signal) {
2386
+ const viewInput = viewFilterInputFromViewFilter(view);
2387
+ const result = await this.sdk.GetDocumentOutgoingRelationships({
2388
+ sourceIdentifier,
2389
+ relationshipType,
2390
+ view: viewInput,
2391
+ paging: pagingInputFromPaging(paging)
2392
+ }, void 0, signal);
2393
+ return this.toDocumentResults(result.documentOutgoingRelationships, paging ?? defaultPaging, view?.branch, (cursor, limit) => this.getOutgoingRelationships(sourceIdentifier, relationshipType, view, {
2394
+ cursor,
2395
+ limit
2396
+ }, signal));
2397
+ }
2398
+ async getIncomingRelationships(targetIdentifier, relationshipType, view, paging, signal) {
2399
+ const viewInput = viewFilterInputFromViewFilter(view);
2400
+ const result = await this.sdk.GetDocumentIncomingRelationships({
2401
+ targetIdentifier,
2402
+ relationshipType,
2403
+ view: viewInput,
2404
+ paging: pagingInputFromPaging(paging)
2405
+ }, void 0, signal);
2406
+ return this.toDocumentResults(result.documentIncomingRelationships, paging ?? defaultPaging, view?.branch, (cursor, limit) => this.getIncomingRelationships(targetIdentifier, relationshipType, view, {
2407
+ cursor,
2408
+ limit
2409
+ }, signal));
2410
+ }
2411
+ async getOutgoingRelationshipEdges(sourceIdentifier, relationshipType, view, paging, signal) {
2412
+ const viewInput = viewFilterInputFromViewFilter(view);
2413
+ const result = await this.sdk.GetDocumentOutgoingRelationshipEdges({
2414
+ sourceIdentifier,
2415
+ relationshipType,
2416
+ view: viewInput,
2417
+ paging: pagingInputFromPaging(paging)
2418
+ }, void 0, signal);
2419
+ return this.toRelationshipResults(result.documentOutgoingRelationshipEdges, paging ?? defaultPaging, (cursor, limit) => this.getOutgoingRelationshipEdges(sourceIdentifier, relationshipType, view, {
2420
+ cursor,
2421
+ limit
2422
+ }, signal));
2423
+ }
2424
+ async getIncomingRelationshipEdges(targetIdentifier, relationshipType, view, paging, signal) {
2425
+ const viewInput = viewFilterInputFromViewFilter(view);
2426
+ const result = await this.sdk.GetDocumentIncomingRelationshipEdges({
2427
+ targetIdentifier,
2428
+ relationshipType,
2429
+ view: viewInput,
2430
+ paging: pagingInputFromPaging(paging)
2431
+ }, void 0, signal);
2432
+ return this.toRelationshipResults(result.documentIncomingRelationshipEdges, paging ?? defaultPaging, (cursor, limit) => this.getIncomingRelationshipEdges(targetIdentifier, relationshipType, view, {
2433
+ cursor,
2434
+ limit
2435
+ }, signal));
2436
+ }
2437
+ async create(document, parentIdentifier, signal) {
2438
+ const created = phDocumentFromGetDocument((await this.sdk.CreateDocument({
2439
+ document,
2440
+ parentIdentifier
2441
+ }, this.driveIdHeaders({
2442
+ method: "create",
2443
+ documentId: document.header.id || void 0,
2444
+ parentId: parentIdentifier
2445
+ }, isDrive(document) && parentIdentifier === void 0 ? document.header.id : void 0), signal)).createDocument);
2446
+ this.emitChange({
2447
+ type: DOCUMENT_CHANGE_TYPE.Created,
2448
+ documents: [created]
2449
+ });
2450
+ return created;
2451
+ }
2452
+ /**
2453
+ * Pushes actions to the Switchboard and returns the updated document.
2454
+ *
2455
+ * The document is fetched first: the response is the baseline for the
2456
+ * `sinceRevision` filter that narrows the returned operations to the ones
2457
+ * this call appended, and it carries the state hash a signed action is
2458
+ * stamped with.
2459
+ *
2460
+ * The emitted `Updated` event carries the document's id, never the
2461
+ * identifier this was called with: subscribers - including `DocumentCache` -
2462
+ * work in id space.
2463
+ *
2464
+ * `IReactorClient.execute`'s trailing `subject` is deliberately not accepted
2465
+ * here. It names the subject a local read gate answers as, and this client
2466
+ * runs no gate: the Switchboard decides what to serve from the bearer on the
2467
+ * request. Declaring it would suggest a per-call choice that does not exist.
2468
+ */
2469
+ async execute(documentIdentifier, branch, actions, signal) {
2470
+ const document = await this.get(documentIdentifier, { branch }, signal);
2471
+ const variables = {
2472
+ documentIdentifier,
2473
+ actions: (await prepareActionsForPush(actions, document, this.documentModels(), this.resolveSigner(), signal)).map(toTransportAction),
2474
+ sinceRevision: sinceRevisionForActions(document, actions),
2475
+ scopes: scopesForActions(actions),
2476
+ branch
2477
+ };
2478
+ const mutated = (await this.sdk.RunDocument({
2479
+ operationName: "MutateDocumentWithOperations",
2480
+ operationType: "mutation",
2481
+ document: MutateDocumentWithOperationsDocument,
2482
+ variables,
2483
+ requestHeaders: this.driveIdHeaders({
2484
+ method: "execute",
2485
+ documentId: documentIdentifier
2486
+ }, isDrive(document) ? document.header.id : void 0),
2487
+ signal
2488
+ })).mutateDocument;
2489
+ const updated = phDocumentFromMutation(mutated, mutated.operations?.items ?? [], branch);
2490
+ this.emitChange({
2491
+ type: DOCUMENT_CHANGE_TYPE.Updated,
2492
+ documents: [updated]
2493
+ });
2494
+ return updated;
2495
+ }
2496
+ /**
2497
+ * What `execute` writes, without waiting: returns the job once the Switchboard
2498
+ * holds it, so a write slower than one request's deadline still lands and is
2499
+ * reported. It is announced as the write half's `execute` announces it.
2500
+ */
2501
+ async executeAsync(documentIdentifier, branch, actions, signal) {
2502
+ return (await this.submitExecute(documentIdentifier, branch, actions, signal)).job;
2503
+ }
2504
+ /**
2505
+ * Undoes the last applied operation of `scope` under this client's own
2506
+ * signature: UNDO below base-reducer 3; on it, a RETRACT of the target the
2507
+ * Switchboard resolves with {@link undoRedoTargets}. One at a time per
2508
+ * document, scope and branch. A stale target is refused, not re-resolved.
2509
+ */
2510
+ undo(documentIdentifier, scope = "global", branch = "main", signal) {
2511
+ return this.undoOrRedo("UNDO", documentIdentifier, scope, branch, signal);
2512
+ }
2513
+ /** Redoes the last undo of `scope`; see {@link undo}. */
2514
+ redo(documentIdentifier, scope = "global", branch = "main", signal) {
2515
+ return this.undoOrRedo("REDO", documentIdentifier, scope, branch, signal);
2516
+ }
2517
+ /** Exact on base-reducer 3, from the targets the Switchboard resolves. */
2518
+ async undoRedoAvailability(documentIdentifier, scope = "global", branch = "main", signal) {
2519
+ const { caps, document } = await this.undoCapabilities(documentIdentifier, branch, signal);
2520
+ const targets = undoNeedsTargets(caps) ? await this.undoRedoTargets(documentIdentifier, scope, { branch }, signal) : void 0;
2521
+ return undoRedoAvailabilityOf(caps, targets, document.header.revision[scope] ?? 0, scope in document.state);
2522
+ }
2523
+ /**
2524
+ * The rows a base-reducer 3 undo and redo would retract, resolved by the
2525
+ * Switchboard as the caller. A Switchboard without the query is refused
2526
+ * with {@link GraphQLOperationNotSupportedError}. `view.subject` is not
2527
+ * sent: the Switchboard reads the caller from the bearer.
2528
+ */
2529
+ async undoRedoTargets(documentIdentifier, scope = "global", view, signal) {
2530
+ try {
2531
+ const { undoRedoTargets } = await this.sdk.GetUndoRedoTargets({
2532
+ documentIdOrSlug: documentIdentifier,
2533
+ scope,
2534
+ branch: view?.branch
2535
+ }, void 0, signal);
2536
+ return {
2537
+ ...undoRedoTargets.undoTarget ? { undoTarget: undoRedoTargets.undoTarget } : {},
2538
+ ...undoRedoTargets.redoTarget ? { redoTarget: undoRedoTargets.redoTarget } : {}
2539
+ };
2540
+ } catch (error) {
2541
+ if (queriesUnknownField(error, "undoRedoTargets")) throw new GraphQLOperationNotSupportedError("undoRedoTargets", "the Switchboard predates the undoRedoTargets query");
2542
+ throw error;
2543
+ }
2544
+ }
2545
+ undoOrRedo(type, documentIdentifier, scope, branch, signal) {
2546
+ return serializeByKey(this.undoRedoChains, JSON.stringify([
2547
+ documentIdentifier,
2548
+ scope,
2549
+ branch
2550
+ ]), async () => {
2551
+ const { caps } = await this.undoCapabilities(documentIdentifier, branch, signal);
2552
+ const targets = undoNeedsTargets(caps) ? await this.undoRedoTargets(documentIdentifier, scope, { branch }, signal) : void 0;
2553
+ return this.execute(documentIdentifier, branch, undoRedoActions(caps, type, scope, targets), signal);
2554
+ }, signal);
2555
+ }
2556
+ /** An older Switchboard serves no header versions; then CREATE_DOCUMENT names them, else it is 1. */
2557
+ async undoCapabilities(documentIdentifier, branch, signal) {
2558
+ const document = await this.get(documentIdentifier, { branch }, signal);
2559
+ const { header } = document;
2560
+ const fromHeader = undoCapabilitiesOf(header);
2561
+ if (fromHeader) return {
2562
+ caps: fromHeader,
2563
+ document
2564
+ };
2565
+ const create = (await this.getOperations(documentIdentifier, {
2566
+ branch,
2567
+ scopes: ["document"]
2568
+ }, void 0, {
2569
+ cursor: "0",
2570
+ limit: 1
2571
+ }, signal)).results.at(0)?.action;
2572
+ const input = create?.type === "CREATE_DOCUMENT" ? create.input : void 0;
2573
+ return {
2574
+ caps: undoCapabilitiesOf(header, input) ?? capabilitiesOf(1),
2575
+ document
2576
+ };
2577
+ }
2578
+ /**
2579
+ * Runs multiple mutation jobs in dependency order over the Switchboard's
2580
+ * `executeBatch` mutation and waits for all to settle, returning the result
2581
+ * shaped like `IReactor.executeBatch`'s so the reference `DriveClient`
2582
+ * consumes it unchanged.
2583
+ *
2584
+ * Not atomic: each job commits on its own and a failed job still releases
2585
+ * its dependents. A FAILED job throws {@link BatchJobFailedError}, naming the
2586
+ * first failed plan key and carrying every job's final state.
2587
+ *
2588
+ * Each job's actions are signed independently for the job's own
2589
+ * `(documentId, branch)` target -- the per-action signing the reactor's own
2590
+ * `signActions` does, not the batch state-prediction `execute` uses for a
2591
+ * multi-action push. A drive job such as `addFile`'s is `CREATE_DOCUMENT` +
2592
+ * `UPGRADE_DOCUMENT` + `ADD_RELATIONSHIP`, which the prediction path rejects
2593
+ * outright and which has no fetchable baseline to stamp against. The reactor
2594
+ * records but does not verify the stamped previous-state head, so signing
2595
+ * each action bare is exactly what the in-process `DriveClient` relies on.
2596
+ *
2597
+ * The mutation is synchronous server-side: a job it returns is already
2598
+ * settled, so {@link waitForJob} resolves from it without polling.
2599
+ */
2600
+ async executeBatch(request, signal) {
2601
+ const signer = this.resolveSigner();
2602
+ const jobInputs = await Promise.all(request.jobs.map(async (job, index) => {
2603
+ const documentId = await this.batchWriteTarget(job, request.jobs.slice(0, index), signer, signal);
2604
+ const actions = await this.signBatchJobActions({
2605
+ ...job,
2606
+ documentId
2607
+ }, signer, signal);
2608
+ return {
2609
+ key: job.key,
2610
+ documentIdOrSlug: documentId,
2611
+ scope: job.scope,
2612
+ branch: job.branch,
2613
+ actions: actions.map(toTransportAction),
2614
+ dependsOn: job.dependsOn
2615
+ };
2616
+ }));
2617
+ const result = await this.batchSdk.ExecuteBatch({ jobs: jobInputs }, this.driveIdHeaders({
2618
+ method: "executeBatch",
2619
+ jobs: jobInputs.map((job) => ({ documentId: job.documentIdOrSlug }))
2620
+ }), signal);
2621
+ const jobs = {};
2622
+ for (const entry of result.executeBatch.jobs) jobs[entry.key] = jobInfoFromGql(entry.job);
2623
+ await this.announceBatch(request, jobs, signal);
2624
+ const failed = request.jobs.find((job) => jobs[job.key]?.status === "FAILED");
2625
+ if (failed) throw new BatchJobFailedError(failed.key, jobs);
2626
+ return { jobs };
2627
+ }
2628
+ /** The job as `jobStatus` reports it now; `undefined` when it reports none. */
2629
+ async getJob(jobId, signal) {
2630
+ const result = await this.sdk.GetJobStatus({ jobId }, void 0, signal);
2631
+ return result.jobStatus ? jobInfoFromGql(result.jobStatus) : void 0;
2632
+ }
2633
+ /** The job as `jobStatus` reports it now; throws when it reports none. */
2634
+ async getJobStatus(jobId, signal) {
2635
+ const job = await this.getJob(jobId, signal);
2636
+ if (!job) throw new Error(`Job not found: ${jobId}`);
2637
+ return job;
2638
+ }
2639
+ /** Polls `jobStatus` until the job is READ_READY or FAILED. */
2640
+ async waitForJob(jobOrId, signal) {
2641
+ if (typeof jobOrId !== "string" && isSettled(jobOrId)) return jobOrId;
2642
+ const jobId = typeof jobOrId === "string" ? jobOrId : jobOrId.id;
2643
+ for (;;) {
2644
+ const result = await this.sdk.GetJobStatus({ jobId }, void 0, signal);
2645
+ if (!result.jobStatus) throw new Error(`Job not found: ${jobId}`);
2646
+ const job = jobInfoFromGql(result.jobStatus);
2647
+ if (isSettled(job)) return job;
2648
+ await delay(JOB_POLL_INTERVAL_MS, signal);
2649
+ }
2650
+ }
2651
+ /** See {@link readCreateSignaturePolicy}. */
2652
+ getCreateSignaturePolicy() {
2653
+ return readCreateSignaturePolicy(this.sdk);
2654
+ }
2655
+ /** See {@link readCreateProtocolVersions}; fitted to `documentModels`. */
2656
+ getCreateProtocolVersions(options, signal) {
2657
+ return readCreateProtocolVersions(this.sdk, options, this.documentModels(), signal);
2658
+ }
2659
+ /** See {@link IReactorClient.newDocument}; the module comes from `documentModels`. */
2660
+ async newDocument(documentType, options, signal) {
2661
+ const module = selectDocumentModelModule([...this.documentModels(), ...BUILT_IN_MODELS], documentType, options?.documentModelVersion);
2662
+ const [policy, versions] = await Promise.all([options?.signaturePolicy ?? this.getCreateSignaturePolicy(), this.getCreateProtocolVersions({
2663
+ documentType,
2664
+ parentIdentifier: options?.parentIdentifier
2665
+ }, signal)]);
2666
+ return headNewDocument(module, options, policy, versions);
2667
+ }
2668
+ /**
2669
+ * Sets or, with `null`, clears the preferred editor as a client-signed
2670
+ * action, as the in-process client does.
2671
+ */
2672
+ setPreferredEditor(documentIdentifier, preferredEditor, branch = "main", signal) {
2673
+ return this.execute(documentIdentifier, branch, [actions.setPreferredEditor(preferredEditor)], signal);
2674
+ }
2675
+ /** The `Drive-Id` header for a call: the client's own proof, else the hook's. */
2676
+ driveIdHeaders(call, proven) {
2677
+ const hinted = this.driveIdFor?.(call);
2678
+ if (proven) {
2679
+ if (hinted && hinted !== proven) logger.warn("GraphQLReactorClient: driveIdFor named @hinted for @method, which belongs to drive @proven; sending the proven drive", hinted, call.method, proven);
2680
+ return driveIdHeaders(proven);
2681
+ }
2682
+ return hinted ? driveIdHeaders(hinted) : void 0;
2683
+ }
2684
+ /**
2685
+ * Emits the changes the batch's settled jobs made, as `create` and `execute`
2686
+ * do, so a cache is invalidated without a realtime socket. The documents a
2687
+ * job wrote to are its own and those its consistency token names.
2688
+ */
2689
+ async announceBatch(request, jobs, signal) {
2690
+ if (this.listeners.length === 0) return;
2691
+ const deleted = /* @__PURE__ */ new Set();
2692
+ const created = /* @__PURE__ */ new Map();
2693
+ const touched = /* @__PURE__ */ new Map();
2694
+ const keyOf = (written) => `${written.branch}\u0000${written.documentId}`;
2695
+ for (const job of request.jobs) {
2696
+ const info = jobs[job.key];
2697
+ if (!info || info.status !== "READ_READY") continue;
2698
+ const types = new Set(job.actions.map((action) => action.type));
2699
+ if (types.has("DELETE_DOCUMENT")) {
2700
+ deleted.add(info.documentId);
2701
+ continue;
2702
+ }
2703
+ const own = {
2704
+ documentId: info.documentId,
2705
+ branch: job.branch
2706
+ };
2707
+ if (types.has("CREATE_DOCUMENT")) created.set(keyOf(own), own);
2708
+ touched.set(keyOf(own), own);
2709
+ for (const { documentId, branch } of info.consistencyToken.coordinates) touched.set(keyOf({
2710
+ documentId,
2711
+ branch
2712
+ }), {
2713
+ documentId,
2714
+ branch
2715
+ });
2716
+ }
2717
+ for (const documentId of deleted) this.emitChange({
2718
+ type: DOCUMENT_CHANGE_TYPE.Deleted,
2719
+ documents: [],
2720
+ context: { childId: documentId }
2721
+ });
2722
+ const read = async ({ documentId, branch }) => {
2723
+ try {
2724
+ return await this.get(documentId, { branch }, signal);
2725
+ } catch (error) {
2726
+ logger.warn("GraphQLReactorClient: could not read @documentId on @branch to announce a batch change: @error", documentId, branch, error);
2727
+ return;
2728
+ }
2729
+ };
2730
+ const readAll = async (written) => (await Promise.all(written.map(read))).filter((document) => document !== void 0);
2731
+ const [createdDocuments, updatedDocuments] = await Promise.all([readAll([...created.values()].filter((w) => !deleted.has(w.documentId))), readAll([...touched.entries()].filter(([key, w]) => !deleted.has(w.documentId) && !created.has(key)).map(([, w]) => w))]);
2732
+ if (createdDocuments.length > 0) this.emitChange({
2733
+ type: DOCUMENT_CHANGE_TYPE.Created,
2734
+ documents: createdDocuments
2735
+ });
2736
+ if (updatedDocuments.length > 0) this.emitChange({
2737
+ type: DOCUMENT_CHANGE_TYPE.Updated,
2738
+ documents: updatedDocuments
2739
+ });
2740
+ }
2741
+ /**
2742
+ * The id a job's actions are signed for: a signature covers the document id,
2743
+ * and the server resolves a slug before verifying. A document created by this
2744
+ * job or an earlier one is named by its id. When the server has no such
2745
+ * document the identifier is used as given, and the server decides; any
2746
+ * other failure to read it throws, so nothing is signed for a slug.
2747
+ */
2748
+ async batchWriteTarget(job, earlier, signer, signal) {
2749
+ const creates = (plan) => plan.documentId === job.documentId && plan.actions.some((action) => action.type === "CREATE_DOCUMENT");
2750
+ if (!signer || job.actions.every(isActionSigned) || creates(job) || earlier.some(creates)) return job.documentId;
2751
+ return (await this.sdk.GetDocument({
2752
+ identifier: job.documentId,
2753
+ view: viewFilterInputFromViewFilter({ branch: job.branch })
2754
+ }, void 0, signal)).document?.document.id ?? job.documentId;
2755
+ }
2756
+ /**
2757
+ * Signs one batch job's actions for the job's own log.
2758
+ *
2759
+ * Each action is signed on its own for `(documentId, branch)`, the same
2760
+ * per-action signing the reactor's `signActions` does: no state prediction
2761
+ * across the job, so a job carrying a `CREATE_DOCUMENT` the push-prediction
2762
+ * path rejects still signs. An action already signed under a key is left
2763
+ * as it is: the reference `DriveClient` signs its jobs before handing them
2764
+ * here. With no signer the actions pass through unsigned, matching
2765
+ * {@link execute}.
2766
+ */
2767
+ async signBatchJobActions(job, signer, signal) {
2768
+ if (!signer) return job.actions;
2769
+ return Promise.all(job.actions.map((action) => isActionSigned(action) ? Promise.resolve(action) : signStampedAction(action, signer, actionSigningTarget(action, job.documentId, job.branch), signal)));
2770
+ }
2771
+ /**
2772
+ * Deletes a document and announces it as a `Deleted` event.
2773
+ *
2774
+ * Pass a document id. The server resolves a slug just as happily, but
2775
+ * `deleteDocument` returns a boolean - there is no document left to read an
2776
+ * id off - so the identifier is announced verbatim on `context.childId`. A
2777
+ * subscriber keyed by id, `DocumentCache` included, therefore only reacts to
2778
+ * a delete by id.
2779
+ */
2780
+ async deleteDocument(identifier, propagate, signal) {
2781
+ await this.sdk.DeleteDocument({
2782
+ identifier,
2783
+ propagate: propagationModeInput(propagate)
2784
+ }, this.driveIdHeaders({
2785
+ method: "deleteDocument",
2786
+ documentId: identifier
2787
+ }), signal);
2788
+ this.emitChange({
2789
+ type: DOCUMENT_CHANGE_TYPE.Deleted,
2790
+ documents: [],
2791
+ context: { childId: identifier }
2792
+ });
2793
+ }
2794
+ /**
2795
+ * Registers a change subscriber and returns its unsubscribe function.
2796
+ *
2797
+ * Two things produce the events delivered here. Every successful `create`,
2798
+ * `execute` and `deleteDocument` emits one, which is what makes a
2799
+ * `DocumentCache` built on this client invalidate after a dispatch. And,
2800
+ * unless realtime is switched off, the first call to this method opens a
2801
+ * websocket to the Switchboard and every change it reports - from another
2802
+ * user, another tab or a server-side processor - is emitted too. A write of
2803
+ * this client's own is therefore announced twice, once locally and once by
2804
+ * the server; the cache refetches twice, which is harmless.
2805
+ *
2806
+ * A websocket that cannot be opened or is refused is logged once and then
2807
+ * ignored: realtime is an enhancement, never a dependency. The failed socket
2808
+ * is closed, so the next subscriber to arrive tries again.
2809
+ *
2810
+ * `view` is accepted for interface compatibility and ignored: the emitted
2811
+ * documents are whatever the write returned, so there is nothing to re-scope.
2812
+ *
2813
+ * Events live in id space: `search.ids` is matched against the resolved
2814
+ * document id, never against the identifier the write was issued with. The
2815
+ * one exception is `deleteDocument`, which has no document to resolve an id
2816
+ * from - see its own note. A `DocumentCache` on this client must therefore
2817
+ * be read by id: a slug-keyed entry is never invalidated.
2818
+ */
2819
+ subscribe(search, callback, view) {
2820
+ const listener = {
2821
+ search,
2822
+ callback
2823
+ };
2824
+ this.listeners.push(listener);
2825
+ this.startRealtime();
2826
+ return () => {
2827
+ const index = this.listeners.indexOf(listener);
2828
+ if (index !== -1) this.listeners.splice(index, 1);
2829
+ };
2830
+ }
2831
+ /**
2832
+ * Closes the realtime socket, if one was opened.
2833
+ *
2834
+ * Registered subscribers are left in place: they still receive the events
2835
+ * this client produces itself.
2836
+ *
2837
+ * Disposing is NOT final - a later `subscribe` opens a new socket. React
2838
+ * remounts a tree by running an effect's cleanup and then the effect again,
2839
+ * on the same client, and `StrictMode` does exactly that on every mount; a
2840
+ * terminal flag here would leave those pages without realtime for good, with
2841
+ * nothing logged.
2842
+ */
2843
+ dispose() {
2844
+ this.teardownRealtime();
2845
+ this.jobSocket?.dispose();
2846
+ this.jobSocket = void 0;
2847
+ }
2848
+ /**
2849
+ * Binds a project's generated SDK to this client's transport and auth.
2850
+ *
2851
+ * Subgraphs are served next to the reactor's own supergraph, so the endpoint
2852
+ * is derived from the client's `url` by appending the name, and the SDK is
2853
+ * handed the same auth middleware every reactor call goes through. An app
2854
+ * therefore configures one URL and one token provider, and reaches every
2855
+ * capability of its Switchboard through this one client.
2856
+ *
2857
+ * `getSdk` is the function a GraphQL code generator emits for the subgraph's
2858
+ * schema - see the README in this folder for the codegen recipe.
2859
+ *
2860
+ * Transport and typing only. Subgraph results are not cached, produce no
2861
+ * change events and never reach `useDocument`.
2862
+ */
2863
+ subgraph(name, getSdk) {
2864
+ return this.subgraphs.get(name, getSdk);
2865
+ }
2866
+ /**
2867
+ * Runs a one-off GraphQL document against the Switchboard's own endpoint,
2868
+ * through the same transport and auth as everything else.
2869
+ *
2870
+ * The escape hatch for an operation not worth generating an SDK for. Pass a
2871
+ * document a code generator typed and the result type follows; pass a plain
2872
+ * `gql` document or a string and name the result type at the call site.
2873
+ */
2874
+ async request(document, variables, options) {
2875
+ const described = describeGraphQLDocument(document);
2876
+ return this.sdk.RunDocument({
2877
+ operationName: options?.operationName ?? described.operationName,
2878
+ operationType: options?.operationType ?? described.operationType,
2879
+ document,
2880
+ variables,
2881
+ signal: options?.signal
2882
+ });
2883
+ }
2884
+ /**
2885
+ * Shapes a document result page into the reactor's {@link PagedResults}.
2886
+ *
2887
+ * The items carry the same `PHDocumentFields` fragment as `get`, so the same
2888
+ * adapter rebuilds each one. `hasNextPage` gates the cursor exactly as
2889
+ * `getOperations` does: no cursor means no `next`.
2890
+ */
2891
+ toDocumentResults(page, effectivePaging, branch, next) {
2892
+ const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
2893
+ return {
2894
+ results: page.items.map((item) => phDocumentFromGetDocument(item, branch)),
2895
+ options: effectivePaging,
2896
+ nextCursor,
2897
+ next: nextCursor ? () => next(nextCursor, effectivePaging.limit) : void 0
2898
+ };
2899
+ }
2900
+ /**
2901
+ * Shapes a relationship-edge result page into the reactor's
2902
+ * {@link PagedResults}, restoring each edge's `Date` fields.
2903
+ */
2904
+ toRelationshipResults(page, effectivePaging, next) {
2905
+ const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
2906
+ return {
2907
+ results: page.items.map((edge) => documentRelationshipFromEdge(edge)),
2908
+ options: effectivePaging,
2909
+ nextCursor,
2910
+ next: nextCursor ? () => next(nextCursor, effectivePaging.limit) : void 0
2911
+ };
2912
+ }
2913
+ /**
2914
+ * The write half's `execute`: signs as the facade's `execute` does, submits
2915
+ * through `executeAsync` and returns once the job is accepted. When anyone
2916
+ * subscribes, the document is read back once the job is readable and
2917
+ * announced as `Updated`, as the facade's `execute` announces it; the handle
2918
+ * shares that read with its own `document()`.
2919
+ */
2920
+ async submitExecute(documentIdentifier, branch, actions, signal) {
2921
+ const document = await this.get(documentIdentifier, { branch }, signal);
2922
+ const preparedActions = await prepareActionsForPush(actions, document, this.documentModels(), this.resolveSigner(), signal);
2923
+ const handle = new GraphQLJobWriteHandle(jobInfoFromGql((await this.sdk.MutateDocumentAsync({
2924
+ documentIdentifier,
2925
+ actions: preparedActions.map(toTransportAction),
2926
+ branch
2927
+ }, this.driveIdHeaders({
2928
+ method: "execute",
2929
+ documentId: documentIdentifier
2930
+ }, isDrive(document) ? document.header.id : void 0), signal)).mutateDocumentAsync), document.header.id, branch, (jobId, stage, stageSignal) => this.waitForStage(jobId, stage, stageSignal), this.handleReader(document.header.id), signal);
2931
+ if (this.listeners.length > 0) this.announceWrite(handle);
2932
+ return handle;
2933
+ }
2934
+ /** The write half's `create`: the synchronous mutation, a settled handle. */
2935
+ async submitCreate(document, parentIdentifier, signal) {
2936
+ const created = await this.create(document, parentIdentifier, signal);
2937
+ return new GraphQLSettledWriteHandle(created.header.id, created.header.branch || "main", this.handleReader(created.header.id));
2938
+ }
2939
+ /** The write half's `deleteDocument`: the synchronous mutation, a settled handle. */
2940
+ async submitDeleteDocument(identifier, propagate, signal) {
2941
+ await this.deleteDocument(identifier, propagate, signal);
2942
+ return new GraphQLSettledWriteHandle(identifier, "main", this.handleReader(identifier));
2943
+ }
2944
+ /** Reads a write's document back, bounded by its receipt's token. */
2945
+ handleReader(documentId) {
2946
+ return (receipt, view, signal) => this.get(documentId, {
2947
+ ...view,
2948
+ branch: receipt.branch
2949
+ }, signal, receipt.token);
2950
+ }
2951
+ /** Announces a write's document as `Updated` once it is readable. */
2952
+ async announceWrite(handle) {
2953
+ let document;
2954
+ try {
2955
+ document = await handle.document();
2956
+ } catch (error) {
2957
+ logger.warn("GraphQLReactorClient: could not read @documentId back to announce a write: @error", handle.documentId, error);
2958
+ return;
2959
+ }
2960
+ this.emitChange({
2961
+ type: DOCUMENT_CHANGE_TYPE.Updated,
2962
+ documents: [document]
2963
+ });
2964
+ }
2965
+ /**
2966
+ * Waits for a job to settle a stage, resolving with a FAILED job too. Polls
2967
+ * `jobStatus` with a doubling interval; with realtime on, a `jobChanges`
2968
+ * event for the job wakes the wait early and the interval is only a safety
2969
+ * net. A failed subscription is logged once and the wait keeps polling.
2970
+ */
2971
+ async waitForStage(jobId, stage, signal) {
2972
+ const wakers = /* @__PURE__ */ new Set();
2973
+ const stopWatching = this.watchJob(jobId, () => {
2974
+ for (const wake of [...wakers]) wake();
2975
+ });
2976
+ try {
2977
+ let interval = STAGE_POLL_START_MS;
2978
+ for (;;) {
2979
+ const job = await this.getJobStatus(jobId, signal);
2980
+ if (settlesGraphQLJobStage(job.status, stage)) return job;
2981
+ await sleepUntilWoken(interval, wakers, signal);
2982
+ const max = stopWatching && !this.jobRealtimeBroken ? STAGE_POLL_REALTIME_MAX_MS : JOB_POLL_INTERVAL_MS;
2983
+ interval = Math.min(interval * 2, max);
2984
+ }
2985
+ } finally {
2986
+ stopWatching?.();
2987
+ }
2988
+ }
2989
+ /**
2990
+ * Subscribes to one job's `jobChanges` when realtime is on and the
2991
+ * subscription has not failed before. Returns the stop function, or
2992
+ * undefined when nothing was subscribed.
2993
+ */
2994
+ watchJob(jobId, onChange) {
2995
+ if (!this.subscriptionsUrl || this.jobRealtimeBroken) return;
2996
+ this.jobSocket ??= createJobChangesSocket({
2997
+ wsUrl: this.subscriptionsUrl,
2998
+ connectionParams: makeAuthConnectionParams(this.tokenProvider)
2999
+ });
3000
+ return this.jobSocket.watch(jobId, () => onChange(), (error) => {
3001
+ if (this.jobRealtimeBroken) return;
3002
+ this.jobRealtimeBroken = true;
3003
+ logger.warn("GraphQLReactorClient: realtime job changes are unavailable, write handles fall back to polling jobStatus", error);
3004
+ });
3005
+ }
3006
+ /**
3007
+ * The `document` query with the `consistency` argument, or without it once
3008
+ * the Switchboard has refused the argument.
3009
+ */
3010
+ async getDocumentAtConsistency(identifier, view, token, signal) {
3011
+ if (!this.consistencyUnsupported) {
3012
+ const variables = {
3013
+ identifier,
3014
+ view,
3015
+ consistency: consistencyInputFromToken(token)
3016
+ };
3017
+ try {
3018
+ return await this.sdk.RunDocument({
3019
+ operationName: "GetDocumentAtConsistency",
3020
+ operationType: "query",
3021
+ document: GetDocumentAtConsistencyDocument,
3022
+ variables,
3023
+ signal
3024
+ });
3025
+ } catch (error) {
3026
+ if (!refusesConsistencyArgument(error)) throw error;
3027
+ this.consistencyUnsupported = true;
3028
+ }
3029
+ }
3030
+ return this.sdk.GetDocument({
3031
+ identifier,
3032
+ view
3033
+ }, void 0, signal);
3034
+ }
3035
+ /**
3036
+ * Opens the realtime socket on the first subscriber.
3037
+ *
3038
+ * The subscription is a firehose - no `search` argument - and this client
3039
+ * applies each subscriber's own filter on the way out, exactly as it does for
3040
+ * its own emissions.
3041
+ */
3042
+ startRealtime() {
3043
+ if (!this.subscriptionsUrl || this.realtimeStarted) return;
3044
+ this.realtimeStarted = true;
3045
+ const generation = this.realtimeGeneration;
3046
+ const stop = startDocumentChangesSubscription({
3047
+ wsUrl: this.subscriptionsUrl,
3048
+ connectionParams: makeAuthConnectionParams(this.tokenProvider),
3049
+ onEvent: (event) => this.emitServerEvent(event),
3050
+ onError: (error) => this.handleRealtimeFailure(generation, error)
3051
+ });
3052
+ if (this.realtimeGeneration !== generation) {
3053
+ stop();
3054
+ return;
3055
+ }
3056
+ this.stopRealtime = stop;
3057
+ }
3058
+ /**
3059
+ * Gives up on a failed socket so that a later subscriber can try again.
3060
+ *
3061
+ * `graphql-ws` retries on its own and only reports here once it has given up,
3062
+ * or once the Switchboard refused the credentials the socket carried - which
3063
+ * `shouldRetry` declines to retry at all. Keeping the dead stop function
3064
+ * would make every later `subscribe` a no-op, so realtime would stay off for
3065
+ * the life of the page even after the user signs in.
3066
+ *
3067
+ * Why it died is recorded: a refusal is undone by a credential change and
3068
+ * nothing else, and {@link notifyCredentialsChanged} acts only on that.
3069
+ *
3070
+ * The generation stamp discards a report from a socket that has already been
3071
+ * replaced or disposed.
3072
+ */
3073
+ handleRealtimeFailure(generation, error) {
3074
+ if (generation !== this.realtimeGeneration) return;
3075
+ this.teardownRealtime();
3076
+ this.realtimeRefusedCredentials = isAuthRefusalClose(error);
3077
+ this.logRealtimeError(error);
3078
+ }
3079
+ /**
3080
+ * Reopens realtime after a sign-in, a sign-out or a token swap.
3081
+ *
3082
+ * Call it whenever the credentials this client authenticates with change.
3083
+ *
3084
+ * A live socket is replaced. `connectionParams` are resolved once, when the
3085
+ * socket opens, so a socket keeps presenting the credentials it was opened
3086
+ * with until something closes it - and a sign-out closes nothing. That left
3087
+ * a signed-out tab still receiving the previous identity's document changes,
3088
+ * on a shared machine, for as long as the socket happened to survive.
3089
+ *
3090
+ * A refused socket is reopened, for the same reason from the other side:
3091
+ * otherwise it stays closed until an unrelated component happens to
3092
+ * `subscribe`, so signing in leaves realtime off with nothing said - the
3093
+ * state `handleRealtimeFailure` resets to avoid.
3094
+ *
3095
+ * A socket that died for any other reason is left alone: a network failure
3096
+ * is not something a new token fixes, and reopening one here would turn a
3097
+ * credential change into a reconnect loop.
3098
+ */
3099
+ notifyCredentialsChanged() {
3100
+ if (!this.realtimeStarted && !this.realtimeRefusedCredentials) return;
3101
+ this.teardownRealtime();
3102
+ if (this.listeners.length === 0) return;
3103
+ this.startRealtime();
3104
+ }
3105
+ /** Closes the socket and lets a later subscriber open a new one. */
3106
+ teardownRealtime() {
3107
+ this.realtimeGeneration += 1;
3108
+ this.realtimeStarted = false;
3109
+ this.realtimeRefusedCredentials = false;
3110
+ this.stopRealtime?.();
3111
+ this.stopRealtime = void 0;
3112
+ }
3113
+ /** Maps a server event onto the client-side event and emits it. */
3114
+ emitServerEvent(event) {
3115
+ this.emitChange({
3116
+ type: documentChangeTypes[event.type],
3117
+ documents: event.documents.map((document) => phDocumentFromGetDocument(document)),
3118
+ context: event.context ? {
3119
+ parentId: event.context.parentId ?? void 0,
3120
+ childId: event.context.childId ?? void 0
3121
+ } : void 0
3122
+ });
3123
+ }
3124
+ /**
3125
+ * Reports a broken realtime socket once per client, however many sockets it
3126
+ * goes through.
3127
+ *
3128
+ * `graphql-ws` retries on its own, and a Switchboard without a websocket
3129
+ * endpoint would otherwise fill the console for as long as the page is open.
3130
+ */
3131
+ logRealtimeError(error) {
3132
+ if (this.realtimeErrorLogged) return;
3133
+ this.realtimeErrorLogged = true;
3134
+ logger.warn("GraphQLReactorClient: realtime document changes are unavailable, falling back to local change events", error);
3135
+ }
3136
+ /**
3137
+ * Delivers an event to every matching subscriber.
3138
+ *
3139
+ * A subscriber that throws is logged and skipped so one bad listener cannot
3140
+ * stop the others from being notified.
3141
+ */
3142
+ emitChange(event) {
3143
+ for (const listener of [...this.listeners]) {
3144
+ if (!eventMatchesSearch(event, listener.search)) continue;
3145
+ try {
3146
+ listener.callback(event);
3147
+ } catch (error) {
3148
+ logger.error("GraphQLReactorClient: a document change subscriber threw", error);
3149
+ }
3150
+ }
3151
+ }
3152
+ };
3153
+ /**
3154
+ * The read half of {@link GraphQLReactorClient}: every read is the client's
3155
+ * own, and nothing that writes is reachable from it.
3156
+ */
3157
+ var GraphQLReadHalf = class {
3158
+ client;
3159
+ drives;
3160
+ constructor(client, nodes) {
3161
+ this.client = client;
3162
+ this.drives = new GraphQLDriveReadClient(nodes);
3163
+ }
3164
+ get(identifier, view, signal, consistencyToken) {
3165
+ return this.client.get(identifier, view, signal, consistencyToken);
3166
+ }
3167
+ getMany(documentIds, view, signal, consistencyToken) {
3168
+ return this.client.getMany(documentIds, view, signal, consistencyToken);
3169
+ }
3170
+ find(search, view, paging, signal) {
3171
+ return this.client.find(search, view, paging, signal);
3172
+ }
3173
+ getOperations(documentIdentifier, view, filter, paging, signal) {
3174
+ return this.client.getOperations(documentIdentifier, view, filter, paging, signal);
3175
+ }
3176
+ subscribe(search, callback, view) {
3177
+ return this.client.subscribe(search, callback, view);
3178
+ }
3179
+ waitForJob(jobId, signal) {
3180
+ return this.client.waitForJob(jobId, signal);
3181
+ }
3182
+ getJobStatus(jobId, signal) {
3183
+ return this.client.getJobStatus(jobId, signal);
3184
+ }
3185
+ };
3186
+ /**
3187
+ * Sleeps for `ms`, or less when a waker in `wakers` fires first. Each sleep
3188
+ * adds its own waker and removes it when it ends.
3189
+ */
3190
+ function sleepUntilWoken(ms, wakers, signal) {
3191
+ return new Promise((resolve, reject) => {
3192
+ if (signal?.aborted) {
3193
+ reject(abortReason(signal));
3194
+ return;
3195
+ }
3196
+ const finish = () => {
3197
+ clearTimeout(timer);
3198
+ wakers.delete(finish);
3199
+ signal?.removeEventListener("abort", onAbort);
3200
+ };
3201
+ const wake = () => {
3202
+ finish();
3203
+ resolve();
3204
+ };
3205
+ const onAbort = () => {
3206
+ finish();
3207
+ if (signal) reject(abortReason(signal));
3208
+ };
3209
+ const timer = setTimeout(wake, ms);
3210
+ wakers.add(wake);
3211
+ signal?.addEventListener("abort", onAbort, { once: true });
3212
+ });
3213
+ }
3214
+ /**
3215
+ * Whether a request failed because the Switchboard's `document` query has no
3216
+ * `consistency` argument, or its schema no `ConsistencyTokenInput`.
3217
+ */
3218
+ /** The most ids one `getMany` request reads. */
3219
+ const GET_MANY_CHUNK_SIZE = 50;
3220
+ const PH_DOCUMENT_FIELDS_SOURCE = print(PhDocumentFieldsFragmentDoc);
3221
+ function consistencyInputFromToken(token) {
3222
+ return {
3223
+ version: token.version,
3224
+ createdAtUtcIso: token.createdAtUtcIso,
3225
+ coordinates: token.coordinates.map((coordinate) => ({
3226
+ documentId: coordinate.documentId,
3227
+ scope: coordinate.scope,
3228
+ branch: coordinate.branch,
3229
+ operationIndex: coordinate.operationIndex
3230
+ }))
3231
+ };
3232
+ }
3233
+ function refusesConsistencyArgument(error) {
3234
+ const errors = error?.response?.errors;
3235
+ if (!Array.isArray(errors)) return false;
3236
+ return errors.some((entry) => {
3237
+ const message = entry?.message;
3238
+ return typeof message === "string" && (message.includes("\"consistency\"") || message.includes("\"ConsistencyTokenInput\""));
3239
+ });
3240
+ }
3241
+ /** {@link GraphQLReactorClient.nodeSource}, as a function. */
3242
+ function createGraphQLDriveNodeSource(client) {
3243
+ return client.nodeSource();
3244
+ }
3245
+ /**
3246
+ * Whether a value is a {@link GraphQLReactorClient}, including one built by
3247
+ * another copy of this module.
3248
+ *
3249
+ * Use this rather than `instanceof`: the brand it tests for is shared by every
3250
+ * copy of the class, so a client built by a hot-replaced module or by a package
3251
+ * that bundled its own copy is still recognised.
3252
+ */
3253
+ function isGraphQLReactorClient(client) {
3254
+ return client?.[graphQLReactorClientBrand] === true;
3255
+ }
3256
+ /** The schema's change types, mapped onto the reactor's. */
3257
+ const documentChangeTypes = {
3258
+ ["CREATED"]: DOCUMENT_CHANGE_TYPE.Created,
3259
+ ["DELETED"]: DOCUMENT_CHANGE_TYPE.Deleted,
3260
+ ["UPDATED"]: DOCUMENT_CHANGE_TYPE.Updated,
3261
+ ["PARENT_ADDED"]: DOCUMENT_CHANGE_TYPE.ParentAdded,
3262
+ ["PARENT_REMOVED"]: DOCUMENT_CHANGE_TYPE.ParentRemoved,
3263
+ ["CHILD_ADDED"]: DOCUMENT_CHANGE_TYPE.ChildAdded,
3264
+ ["CHILD_REMOVED"]: DOCUMENT_CHANGE_TYPE.ChildRemoved
3265
+ };
3266
+ /**
3267
+ * Decides whether an event reaches a subscriber.
3268
+ *
3269
+ * Every populated field of the search filter is an AND condition, matching the
3270
+ * reactor's own subscription manager - which also treats an empty array as a
3271
+ * filter that nothing satisfies. `parentId` is a drive concept and is ignored.
3272
+ *
3273
+ * A `Deleted` event carries no documents, so it is matched on its
3274
+ * `context.childId` for identifier filters and delivered unconditionally to
3275
+ * type and slug filters: there is no document left to check them against.
3276
+ */
3277
+ function eventMatchesSearch(event, search) {
3278
+ const deleted = event.type === DOCUMENT_CHANGE_TYPE.Deleted;
3279
+ const { ids, slugs, type } = search;
3280
+ if (ids) {
3281
+ if (!(deleted ? [event.context?.childId] : event.documents.map((document) => document.header.id)).some((id) => id !== void 0 && ids.includes(id))) return false;
3282
+ }
3283
+ if (slugs && !deleted) {
3284
+ if (!event.documents.map((document) => document.header.slug).some((slug) => slugs.includes(slug))) return false;
3285
+ }
3286
+ if (type && !deleted) {
3287
+ if (!event.documents.map((document) => document.header.documentType).includes(type)) return false;
3288
+ }
3289
+ return true;
3290
+ }
3291
+ /**
3292
+ * Maps a reactor `ViewFilter` onto the GraphQL `ViewFilterInput`.
3293
+ *
3294
+ * Point-in-time reads are rejected: the Switchboard read API has no revision
3295
+ * argument, so silently returning the head state would be wrong.
3296
+ */
3297
+ function viewFilterInputFromViewFilter(view) {
3298
+ if (!view) return;
3299
+ if (viewIsPointInTime(view)) throw new GraphQLOperationNotSupportedError("view", "point-in-time views are not supported by GraphQLReactorClient");
3300
+ if (view.branch === void 0 && view.scopes === void 0) return;
3301
+ return {
3302
+ branch: view.branch,
3303
+ scopes: view.scopes
3304
+ };
3305
+ }
3306
+ function pagingInputFromPaging(paging) {
3307
+ if (!paging) return;
3308
+ return {
3309
+ cursor: paging.cursor,
3310
+ limit: paging.limit
3311
+ };
3312
+ }
3313
+ /**
3314
+ * Whether a search names `ids` or `slugs`, which the Switchboard `findDocuments`
3315
+ * query cannot honour (it filters by `type` and `parentId`).
3316
+ *
3317
+ * The test is PRESENCE, not length: the reactor `find` contract
3318
+ * (`packages/reactor/src/core/reactor.ts`) dispatches on `search.ids` /
3319
+ * `search.slugs` being present, so `find({ ids: [] })` is an identifier search
3320
+ * that must yield the empty set -- not a plain type query over every document.
3321
+ * The GraphQL surface cannot express an identifier search at all, so a present
3322
+ * (even empty) `ids`/`slugs` is refused rather than served as the wrong query.
3323
+ */
3324
+ function searchNamesIdentifiers(search) {
3325
+ return search.ids !== void 0 || search.slugs !== void 0;
3326
+ }
3327
+ /** Whether a view asks for a point-in-time read the GraphQL surface cannot express. */
3328
+ function viewIsPointInTime(view) {
3329
+ return view?.revision !== void 0;
3330
+ }
3331
+ /**
3332
+ * The single source of truth for whether the Switchboard `findDocuments` query
3333
+ * can serve a `find`. It is servable iff the search names neither `ids` nor
3334
+ * `slugs` (present, regardless of length) AND the view is not point-in-time:
3335
+ * each is a by-contract limitation of a surface that filters only by
3336
+ * `type`/`parentId` at head. Exported so a caller can route around an
3337
+ * unservable search instead of catching the error `find` throws for it.
3338
+ */
3339
+ function findIsServableOverGraphQL(search, view) {
3340
+ return !searchNamesIdentifiers(search) && !viewIsPointInTime(view);
3341
+ }
3342
+ /** Rebuilds a relationship edge from its GraphQL fields. */
3343
+ function documentRelationshipFromEdge(edge) {
3344
+ const relationship = {
3345
+ sourceId: edge.sourceId,
3346
+ targetId: edge.targetId,
3347
+ relationshipType: edge.relationshipType,
3348
+ createdAt: dateFromDateTime(edge.createdAt),
3349
+ updatedAt: dateFromDateTime(edge.updatedAt)
3350
+ };
3351
+ const metadata = edge.metadata;
3352
+ if (isPlainObject(metadata)) relationship.metadata = metadata;
3353
+ return relationship;
3354
+ }
3355
+ /**
3356
+ * Restores a `Date` from the `DateTime` scalar, which deserializes as either an
3357
+ * ISO string or a `Date`, reusing the get-path's {@link isoStringFromDateTime}.
3358
+ *
3359
+ * A null, absent or unparseable value is a malformed timestamp from the server,
3360
+ * not something to coerce to the epoch or an `Invalid Date`: it throws, so the
3361
+ * malformed edge surfaces as a genuine failure rather than a silently-wrong
3362
+ * `DocumentRelationship`.
3363
+ */
3364
+ function dateFromDateTime(value) {
3365
+ if (value === null || value === void 0) throw new Error("relationship edge is missing a required DateTime timestamp");
3366
+ const date = new Date(isoStringFromDateTime(value));
3367
+ if (Number.isNaN(date.getTime())) throw new Error(`relationship edge carries an unparseable DateTime timestamp: ${String(value)}`);
3368
+ return date;
3369
+ }
3370
+ /**
3371
+ * Whether a JSON value is a plain object, so relationship `metadata` is assigned
3372
+ * only when it is one. A non-object JSON scalar (string, number, array, null)
3373
+ * is dropped exactly as a null is, rather than cast to `Record` and trusted.
3374
+ */
3375
+ function isPlainObject(value) {
3376
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3377
+ }
3378
+ /**
3379
+ * The reactor and the GraphQL schema disagree on the enum: the reactor's
3380
+ * `None` is the schema's `ORPHAN`. This is the inverse of the server's
3381
+ * `toReactorPropagationMode`.
3382
+ */
3383
+ const propagationModeInputs = {
3384
+ cascade: "CASCADE",
3385
+ none: "ORPHAN"
3386
+ };
3387
+ function propagationModeInput(propagate) {
3388
+ return propagate === void 0 ? void 0 : propagationModeInputs[propagate];
3389
+ }
3390
+ /**
3391
+ * Stamps and signs the actions about to be pushed.
3392
+ *
3393
+ * With no signer the actions go out exactly as given, batch or not - this
3394
+ * client does not require signatures. With one, every action is signed:
3395
+ * {@link prepareSignedActions} predicts the chain a batch will produce by
3396
+ * running the document's own reducer between signatures, which is why a batch
3397
+ * needs the module matching the document's type and exact version.
3398
+ *
3399
+ * A batch that cannot be predicted - no matching module, mixed scopes, an
3400
+ * action needing history - throws here, before the mutation. Sending it
3401
+ * unsigned instead would silently drop the signatures the caller asked for.
3402
+ */
3403
+ async function prepareActionsForPush(actions, document, documentModels, signer, signal) {
3404
+ if (!signer || actions.length === 0) return actions;
3405
+ return prepareSignedActions(actions, document, signer, actions.length > 1 ? resolveDocumentModelModule(documentModels, document.header.documentType, documentModelVersion(document)) : void 0, signal);
3406
+ }
3407
+ /**
3408
+ * The document-model version the document's actions must be reduced with.
3409
+ *
3410
+ * `state` arrives as JSON over GraphQL, so its `document` scope is only as
3411
+ * reliable as the server that sent it - one written before that scope existed
3412
+ * carries no version at all. `normalizeDocumentModelVersion` maps that, and 0,
3413
+ * to 1: the same rule `SimpleJobExecutor` applies before asking the registry
3414
+ * for a module, so client and server cannot resolve different reducers.
3415
+ */
3416
+ function documentModelVersion(document) {
3417
+ const documentScope = document.state.document;
3418
+ return normalizeDocumentModelVersion(documentScope?.version);
3419
+ }
3420
+ /**
3421
+ * Rebuilds a reactor {@link JobInfo} from what the server reported. An unknown
3422
+ * job arrives as the reactor's own: FAILED with an empty `documentId`.
3423
+ */
3424
+ function jobInfoFromGql(job) {
3425
+ const token = job.consistencyToken;
3426
+ if (token.version !== 1) throw new Error(`Job ${job.id} carries consistency token version ${token.version}, which this client cannot read`);
3427
+ const info = {
3428
+ id: job.id,
3429
+ documentId: job.documentId,
3430
+ status: job.status,
3431
+ createdAtUtcIso: isoStringFromDateTime(job.createdAt),
3432
+ consistencyToken: {
3433
+ version: 1,
3434
+ createdAtUtcIso: token.createdAtUtcIso,
3435
+ coordinates: token.coordinates.map((coordinate) => ({ ...coordinate }))
3436
+ },
3437
+ meta: {
3438
+ batchId: job.meta.batchId,
3439
+ batchJobIds: [...job.meta.batchJobIds]
3440
+ }
3441
+ };
3442
+ if (job.completedAt != null) info.completedAtUtcIso = isoStringFromDateTime(job.completedAt);
3443
+ if (job.result != null) info.result = job.result;
3444
+ if (job.error != null) info.error = {
3445
+ name: job.errorName ?? "Error",
3446
+ message: job.error,
3447
+ stack: ""
3448
+ };
3449
+ return info;
3450
+ }
3451
+ /**
3452
+ * The header a Switchboard's drive middleware and load balancer key on. A
3453
+ * request carries it only when it is known to belong to that one drive: the
3454
+ * server answers any drive it does not own with 421.
3455
+ */
3456
+ const DRIVE_ID_HEADER = "Drive-Id";
3457
+ function driveIdHeaders(driveId) {
3458
+ return driveId === "" ? void 0 : { [DRIVE_ID_HEADER]: driveId };
3459
+ }
3460
+ function isDrive(document) {
3461
+ return DRIVE_DOCUMENT_TYPES.includes(document.header.documentType);
3462
+ }
3463
+ /**
3464
+ * Surfaces a 421 from the Switchboard's drive middleware, which graphql-request
3465
+ * reports as a `ClientError`, as {@link GraphQLWrongBackendError}.
3466
+ */
3467
+ function withWrongBackendErrors(middleware) {
3468
+ return async (action, ...rest) => {
3469
+ try {
3470
+ return await middleware(action, ...rest);
3471
+ } catch (error) {
3472
+ throw wrongBackendErrorOf(error) ?? error;
3473
+ }
3474
+ };
3475
+ }
3476
+ function wrongBackendErrorOf(error) {
3477
+ const response = error?.response;
3478
+ if (response?.status !== 421) return;
3479
+ let payload = response.body;
3480
+ if (typeof payload === "string") try {
3481
+ payload = JSON.parse(payload);
3482
+ } catch {}
3483
+ const driveId = payload?.driveId;
3484
+ return new GraphQLWrongBackendError(typeof driveId === "string" ? driveId : "", payload, { cause: error });
3485
+ }
3486
+ function isSettled(job) {
3487
+ const status = job.status;
3488
+ return status === "READ_READY" || status === "FAILED";
3489
+ }
3490
+ function abortReason(signal) {
3491
+ const reason = signal.reason;
3492
+ return reason instanceof Error ? reason : new Error(String(reason));
3493
+ }
3494
+ function delay(ms, signal) {
3495
+ return new Promise((resolve, reject) => {
3496
+ if (signal?.aborted) {
3497
+ reject(abortReason(signal));
3498
+ return;
3499
+ }
3500
+ const onAbort = () => {
3501
+ clearTimeout(timer);
3502
+ if (signal) reject(abortReason(signal));
3503
+ };
3504
+ const timer = setTimeout(() => {
3505
+ signal?.removeEventListener("abort", onAbort);
3506
+ resolve();
3507
+ }, ms);
3508
+ signal?.addEventListener("abort", onAbort, { once: true });
3509
+ });
3510
+ }
3511
+ /** As the reactor's `signAction` reads it: the last tuple names a key. */
3512
+ function isActionSigned(action) {
3513
+ const signer = action.context?.signer;
3514
+ return Boolean(signer?.app?.key && signer.signatures.at(-1)?.[1]);
3515
+ }
3516
+ /** Resolves the signer of the logged-in user, if there is one. */
3517
+ /** The logged-in Renown user's signer, read per call; none when nobody is. */
3518
+ function ambientRenownSigner() {
3519
+ if (typeof window === "undefined") return;
3520
+ const renown = getPHStore()?.renown;
3521
+ return renown?.user ? renown.signer : void 0;
3522
+ }
3523
+ /**
3524
+ * The revision the pushed operations start from: the lowest head revision
3525
+ * across the scopes the actions target.
3526
+ *
3527
+ * The baseline is only meaningful together with {@link scopesForActions}: a
3528
+ * batch that touches a scope at revision 1 and one at revision 5000 would
3529
+ * otherwise re-download the whole history of every scope of the document.
3530
+ */
3531
+ function sinceRevisionForActions(document, actions) {
3532
+ const revisions = actions.map((action) => document.header.revision[action.scope] ?? 0);
3533
+ return revisions.length > 0 ? Math.min(...revisions) : 0;
3534
+ }
3535
+ /** The distinct scopes the pushed actions target, in first-seen order. */
3536
+ function scopesForActions(actions) {
3537
+ if (actions.length === 0) return;
3538
+ return [...new Set(actions.map((action) => action.scope))];
3539
+ }
3540
+ //#endregion
3541
+ //#region src/hooks/backend-auth.ts
3542
+ const backendAuthEventFunctions = makePHEventFunctions("backendAuth");
3543
+ /** Whether the app's backend refused this tab's caller, and how. */
3544
+ const useBackendAuth = backendAuthEventFunctions.useValue;
3545
+ /** Records (or clears, with `undefined`) a backend's refusal of the caller. */
3546
+ const setBackendAuth = backendAuthEventFunctions.setValue;
3547
+ const addBackendAuthEventHandler = backendAuthEventFunctions.addEventHandler;
3548
+ const STATUS_IN_MESSAGE = /\(Code: (401|403)\)/;
3549
+ /**
3550
+ * The messages a Switchboard's GraphQL layer refuses with, without an HTTP
3551
+ * status (the sync layer's `DRIVE_AUTH_ERROR_MESSAGES`). Inlined: this file
3552
+ * is reachable from the browser entry, which must not import the reactor
3553
+ * package as a value.
3554
+ */
3555
+ const GRAPHQL_REFUSALS = [
3556
+ "Forbidden: insufficient permissions",
3557
+ "Forbidden: authentication required",
3558
+ "Authentication required"
3559
+ ];
3560
+ /**
3561
+ * The HTTP status with which a backend refused the caller, or null when the
3562
+ * error is something else.
3563
+ *
3564
+ * Covers every shape a refusal reaches the browser in: the sync layer's
3565
+ * errors (`isDriveAuthError`), graphql-request's `ClientError` from the
3566
+ * remote GraphQL client (`response.status`, and "(Code: 401)" in its
3567
+ * message), and the router's partial-failure error that wraps one such
3568
+ * failure per backend.
3569
+ */
3570
+ function backendAuthStatusOf(error) {
3571
+ if (!error || typeof error !== "object") return null;
3572
+ const e = error;
3573
+ const direct = [e.response?.status, e.statusCode].find((s) => s === 401 || s === 403);
3574
+ if (direct === 401 || direct === 403) return direct;
3575
+ if (typeof e.message === "string") {
3576
+ const m = STATUS_IN_MESSAGE.exec(e.message);
3577
+ if (m) return m[1] === "401" ? 401 : 403;
3578
+ }
3579
+ if (Array.isArray(e.failures)) for (const failure of e.failures) {
3580
+ const status = backendAuthStatusOf(failure.error);
3581
+ if (status) return status;
3582
+ }
3583
+ if (typeof e.message === "string" && GRAPHQL_REFUSALS.some((m) => e.message.includes(m))) return /authentication required/i.test(e.message) ? 401 : 403;
3584
+ return null;
3585
+ }
3586
+ /** True when a backend refused the caller as unauthenticated or unauthorized. */
3587
+ function isBackendAuthError(error) {
3588
+ return backendAuthStatusOf(error) !== null;
3589
+ }
3590
+ /** Records the refusal `error` carries, if it is one; returns whether it was. */
3591
+ function recordBackendAuthError(error, backend) {
3592
+ const status = backendAuthStatusOf(error);
3593
+ if (status === null) return false;
3594
+ setBackendAuth({
3595
+ requiresAuth: true,
3596
+ status,
3597
+ backend,
3598
+ at: (/* @__PURE__ */ new Date()).toISOString()
3599
+ });
3600
+ return true;
3601
+ }
3602
+ //#endregion
3603
+ //#region src/hooks/config/editor.ts
3604
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
3605
+ /** Sets whether external controls are enabled for a given editor. */
3606
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
3607
+ /** Gets whether external controls are enabled for a given editor. */
3608
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
3609
+ /** Adds an event handler for when the external controls enabled state changes. */
3610
+ const addIsExternalControlsEnabledEventHandler = isExternalControlsEnabledEventFunctions.addEventHandler;
3611
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
3612
+ /** Sets whether drag and drop is enabled for a given app. */
3613
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
3614
+ /** Gets whether drag and drop is enabled for a given app. */
3615
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
3616
+ /** Adds an event handler for when the drag and drop enabled state changes. */
3617
+ const addIsDragAndDropEnabledEventHandler = isDragAndDropEnabledEventFunctions.addEventHandler;
3618
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
3619
+ /** Sets the allowed document types for a given app. */
3620
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
3621
+ /** Defines the document types a drive supports.
3622
+ *
3623
+ * Unset or empty, it means every document type registered in the reactor.
3624
+ */
3625
+ function useAllowedDocumentTypes() {
3626
+ return allowedDocumentTypesEventFunctions.useValue();
3627
+ }
3628
+ /** Adds an event handler for when the allowed document types for a given app changes. */
3629
+ const addAllowedDocumentTypesEventHandler = allowedDocumentTypesEventFunctions.addEventHandler;
3630
+ const phAppConfigSetters = {
3631
+ allowedDocumentTypes: setAllowedDocumentTypes,
3632
+ isDragAndDropEnabled: setIsDragAndDropEnabled
3633
+ };
3634
+ const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
3635
+ const phAppConfigHooks = {
3636
+ allowedDocumentTypes: useAllowedDocumentTypes,
3637
+ isDragAndDropEnabled: useIsDragAndDropEnabled
3638
+ };
3639
+ const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
3640
+ //#endregion
3641
+ //#region src/hooks/config/connect.ts
3642
+ const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
3643
+ const { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions("version");
3644
+ const { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions("requiresHardRefresh");
3645
+ const { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions("warnOutdatedApp");
3646
+ const { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions("studioMode");
3647
+ const { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions("basePath");
3648
+ const { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions("versionCheckInterval");
3649
+ const { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions("cliVersion");
3650
+ const { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions("fileUploadOperationsChunkSize");
3651
+ const { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions("isDocumentModelSelectionSettingsEnabled");
3652
+ const { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions("gaTrackingId");
3653
+ const { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions("defaultDrivesUrl");
3654
+ const { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions("drivesPreserveStrategy");
3655
+ const { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
3656
+ const { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions("isAddDriveEnabled");
3657
+ const { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions("isPublicDrivesEnabled");
3658
+ const { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions("isAddPublicDrivesEnabled");
3659
+ const { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions("isDeletePublicDrivesEnabled");
3660
+ const { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions("isCloudDrivesEnabled");
3661
+ const { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions("isAddCloudDrivesEnabled");
3662
+ const { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteCloudDrivesEnabled");
3663
+ const { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
3664
+ const { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions("isAddLocalDrivesEnabled");
3665
+ const { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteLocalDrivesEnabled");
3666
+ const { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions("isEditorDebugModeEnabled");
3667
+ const { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions("isEditorReadModeEnabled");
3668
+ const { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled");
3669
+ const { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions("isDiffAnalyticsEnabled");
3670
+ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions("isDriveAnalyticsEnabled");
3671
+ const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
3672
+ const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
3673
+ const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
3674
+ const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
3675
+ const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
3676
+ const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
3677
+ const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
3678
+ const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
3679
+ const { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions("isSentryTracingEnabled");
3680
+ const { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions("isExternalProcessorsEnabled");
3681
+ const { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions("isExternalPackagesEnabled");
3682
+ const enabledEditorsEventFunctions = makePHEventFunctions("enabledEditors");
3683
+ /** Sets the enabled editors for Connect. */
3684
+ const setEnabledEditors = enabledEditorsEventFunctions.setValue;
3685
+ /** Gets the enabled editors for Connect. */
3686
+ const useEnabledEditors = enabledEditorsEventFunctions.useValue;
3687
+ /** Adds an event handler for when the enabled editors for Connect changes. */
3688
+ const addEnabledEditorsEventHandler = enabledEditorsEventFunctions.addEventHandler;
3689
+ const disabledEditorsEventFunctions = makePHEventFunctions("disabledEditors");
3690
+ /** Sets the disabled editors for Connect. */
3691
+ const setDisabledEditors = disabledEditorsEventFunctions.setValue;
3692
+ /** Gets the disabled editors for Connect. */
3693
+ const useDisabledEditors = disabledEditorsEventFunctions.useValue;
3694
+ /** Adds an event handler for when the disabled editors for Connect changes. */
3695
+ const addDisabledEditorsEventHandler = disabledEditorsEventFunctions.addEventHandler;
3696
+ const isRelationalProcessorsEnabled = makePHEventFunctions("isRelationalProcessorsEnabled");
3697
+ /** Sets the isRelationalProcessorsEnabled for Connect. */
3698
+ const setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;
3699
+ /** Gets the isRelationalProcessorsEnabled for Connect. */
3700
+ const useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;
3701
+ /** Adds an event handler for when the isRelationalProcessorsEnabled for Connect changes. */
3702
+ const addIsRelationalProcessorsEnabledEventHandler = isRelationalProcessorsEnabled.addEventHandler;
3703
+ const isExternalRelationalProcessorsEnabled = makePHEventFunctions("isExternalRelationalProcessorsEnabled");
3704
+ /** Sets the isExternalRelationalProcessorsEnabled for Connect. */
3705
+ const setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;
3706
+ /** Gets the isExternalRelationalProcessorsEnabled for Connect. */
3707
+ const useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;
3708
+ /** Adds an event handler for when the isExternalRelationalProcessorsEnabled for Connect changes. */
3709
+ const addIsExternalRelationalProcessorsEnabledEventHandler = isExternalRelationalProcessorsEnabled.addEventHandler;
3710
+ const isAnalyticsEnabledEventFunctions = makePHEventFunctions("isAnalyticsEnabled");
3711
+ /** Sets the isAnalyticsEnabled for Connect. */
3712
+ const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;
3713
+ /** Gets the isAnalyticsEnabled for Connect. */
3714
+ const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;
3715
+ /** Adds an event handler for when the isAnalyticsEnabled for Connect changes. */
3716
+ const addIsAnalyticsEnabledEventHandler = isAnalyticsEnabledEventFunctions.addEventHandler;
3717
+ const isAnalyticsExternalProcessorsEnabled = makePHEventFunctions("isAnalyticsExternalProcessorsEnabled");
3718
+ /** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */
3719
+ const setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;
3720
+ /** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */
3721
+ const useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;
3722
+ /** Adds an event handler for when the isAnalyticsExternalProcessorsEnabled for Connect changes. */
3723
+ const addIsAnalyticsExternalProcessorsEnabledEventHandler = isAnalyticsExternalProcessorsEnabled.addEventHandler;
3724
+ const analyticsDatabaseNameEventFunctions = makePHEventFunctions("analyticsDatabaseName");
3725
+ /** Sets the analytics database name for Connect. */
3726
+ const setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;
3727
+ /** Gets the analytics database name for Connect. */
3728
+ const useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;
3729
+ /** Adds an event handler for when the analytics database name for Connect changes. */
3730
+ const addAnalyticsDatabaseNameEventHandler = analyticsDatabaseNameEventFunctions.addEventHandler;
3731
+ const logLevelEventFunctions = makePHEventFunctions("logLevel");
3732
+ /** Sets the log level for Connect. */
3733
+ const setLogLevel = logLevelEventFunctions.setValue;
3734
+ /** Gets the log level for Connect. */
3735
+ const useLogLevel = logLevelEventFunctions.useValue;
3736
+ /** Adds an event handler for when the log level for Connect changes. */
3737
+ const addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;
3738
+ const allowListEventFunctions = makePHEventFunctions("allowList");
3739
+ /** Sets the allow list for Connect. */
3740
+ const setAllowList = allowListEventFunctions.setValue;
3741
+ /** Gets the allow list for Connect. */
3742
+ const useAllowList = allowListEventFunctions.useValue;
3743
+ /** Adds an event handler for when the allow list for Connect changes. */
3744
+ const addAllowListEventHandler = allowListEventFunctions.addEventHandler;
3745
+ const nonUserConfigSetters = {
3746
+ routerBasename: setRouterBasename,
3747
+ version: setVersion,
3748
+ requiresHardRefresh: setRequiresHardRefresh,
3749
+ warnOutdatedApp: setWarnOutdatedApp,
3750
+ studioMode: setStudioMode,
3751
+ basePath: setBasePath,
3752
+ versionCheckInterval: setVersionCheckInterval,
3753
+ cliVersion: setCliVersion,
3754
+ fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,
3755
+ isDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,
3756
+ gaTrackingId: setGaTrackingId,
3757
+ defaultDrivesUrl: setDefaultDrivesUrl,
3758
+ drivesPreserveStrategy: setDrivesPreserveStrategy,
3759
+ isLocalDrivesEnabled: setIsLocalDrivesEnabled,
3760
+ isAddDriveEnabled: setIsAddDriveEnabled,
3761
+ isPublicDrivesEnabled: setIsPublicDrivesEnabled,
3762
+ isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,
3763
+ isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,
3764
+ isCloudDrivesEnabled: setIsCloudDrivesEnabled,
3765
+ isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,
3766
+ isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,
3767
+ isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,
3768
+ isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,
3769
+ isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,
3770
+ isEditorReadModeEnabled: setIsEditorReadModeEnabled,
3771
+ isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,
3772
+ isExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,
3773
+ isAnalyticsEnabled: setIsAnalyticsEnabled,
3774
+ analyticsDatabaseName: setAnalyticsDatabaseName,
3775
+ isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,
3776
+ isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,
3777
+ isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,
3778
+ isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,
3779
+ renownUrl: setRenownUrl,
3780
+ renownNetworkId: setRenownNetworkId,
3781
+ renownChainId: setRenownChainId,
3782
+ switchboardUrl: setSwitchboardUrl,
3783
+ renownAdapters: setRenownAdapters,
3784
+ sentryRelease: setSentryRelease,
3785
+ sentryDsn: setSentryDsn,
3786
+ sentryEnv: setSentryEnv,
3787
+ isSentryTracingEnabled: setIsSentryTracingEnabled,
3788
+ isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,
3789
+ isExternalPackagesEnabled: setIsExternalPackagesEnabled,
3790
+ allowList: setAllowList,
3791
+ logLevel: setLogLevel,
3792
+ disabledEditors: setDisabledEditors,
3793
+ enabledEditors: setEnabledEditors
3794
+ };
3795
+ const phGlobalConfigSetters = {
3796
+ ...phAppConfigSetters,
3797
+ ...phDocumentEditorConfigSetters,
3798
+ ...nonUserConfigSetters
3799
+ };
3800
+ const nonUserConfigHooks = {
3801
+ routerBasename: useRouterBasename,
3802
+ version: useVersion,
3803
+ requiresHardRefresh: useRequiresHardRefresh,
3804
+ warnOutdatedApp: useWarnOutdatedApp,
3805
+ studioMode: useStudioMode,
3806
+ basePath: useBasePath,
3807
+ versionCheckInterval: useVersionCheckInterval,
3808
+ cliVersion: useCliVersion,
3809
+ fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,
3810
+ isDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,
3811
+ gaTrackingId: useGaTrackingId,
3812
+ defaultDrivesUrl: useDefaultDrivesUrl,
3813
+ drivesPreserveStrategy: useDrivesPreserveStrategy,
3814
+ isAddDriveEnabled: useIsAddDriveEnabled,
3815
+ isPublicDrivesEnabled: useIsPublicDrivesEnabled,
3816
+ isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,
3817
+ isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,
3818
+ isCloudDrivesEnabled: useIsCloudDrivesEnabled,
3819
+ isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,
3820
+ isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,
3821
+ isLocalDrivesEnabled: useIsLocalDrivesEnabled,
3822
+ isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,
3823
+ isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,
3824
+ isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,
3825
+ isEditorReadModeEnabled: useIsEditorReadModeEnabled,
3826
+ isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,
3827
+ isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,
3828
+ isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,
3829
+ renownUrl: useRenownUrl,
3830
+ renownNetworkId: useRenownNetworkId,
3831
+ renownChainId: useRenownChainId,
3832
+ switchboardUrl: useSwitchboardUrl,
3833
+ renownAdapters: useRenownAdapters,
3834
+ sentryRelease: useSentryRelease,
3835
+ sentryDsn: useSentryDsn,
3836
+ sentryEnv: useSentryEnv,
3837
+ isSentryTracingEnabled: useIsSentryTracingEnabled,
3838
+ isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,
3839
+ isExternalPackagesEnabled: useIsExternalPackagesEnabled,
3840
+ allowList: useAllowList,
3841
+ isAnalyticsEnabled: useIsAnalyticsEnabled,
3842
+ isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,
3843
+ isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,
3844
+ isExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,
3845
+ analyticsDatabaseName: useAnalyticsDatabaseName,
3846
+ logLevel: useLogLevel,
3847
+ disabledEditors: useDisabledEditors,
3848
+ enabledEditors: useEnabledEditors
3849
+ };
3850
+ const phGlobalConfigHooks = {
3851
+ ...phAppConfigHooks,
3852
+ ...phDocumentEditorConfigHooks,
3853
+ ...nonUserConfigHooks
3854
+ };
3855
+ //#endregion
3856
+ //#region src/hooks/attachment-service.ts
3857
+ const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
3858
+ /** Returns the attachment service from window.ph */
3859
+ const useAttachmentService = attachmentServiceEventFunctions.useValue;
3860
+ /** Sets the attachment service on window.ph */
3861
+ const setAttachmentService = attachmentServiceEventFunctions.setValue;
3862
+ /** Registers the attachmentService window event handler */
3863
+ const addAttachmentServiceEventHandler = attachmentServiceEventFunctions.addEventHandler;
3864
+ //#endregion
3865
+ //#region src/hooks/features.ts
3866
+ const featuresEventFunctions = makePHEventFunctions("features");
3867
+ const useFeatures = featuresEventFunctions.useValue;
3868
+ const setFeatures = featuresEventFunctions.setValue;
3869
+ const addFeaturesEventHandler = featuresEventFunctions.addEventHandler;
3870
+ //#endregion
3871
+ //#region src/hooks/use-drop-target.ts
3872
+ function useDropTarget() {
3873
+ const [isDropTarget, setIsDropTarget] = useState(false);
3874
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
3875
+ const targetSetter = funnel(() => setIsDropTarget(true), {
3876
+ triggerAt: "start",
3877
+ minQuietPeriodMs: 100
3878
+ });
3879
+ const targetUnsetter = funnel(() => setIsDropTarget(false), {
3880
+ triggerAt: "start",
3881
+ minQuietPeriodMs: 100
3882
+ });
3883
+ function setTarget() {
3884
+ if (!isDragAndDropEnabled) return;
3885
+ targetUnsetter.cancel();
3886
+ targetSetter.call();
3887
+ }
3888
+ function unsetTarget() {
3889
+ if (!isDragAndDropEnabled) return;
3890
+ targetSetter.cancel();
3891
+ targetUnsetter.call();
3892
+ }
3893
+ return {
3894
+ isDropTarget,
3895
+ setTarget,
3896
+ unsetTarget
3897
+ };
3898
+ }
3899
+ //#endregion
3900
+ //#region src/hooks/node-drag-and-drop.ts
3901
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3902
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
3903
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
3904
+ const addDraggingNodeEventHandler = draggingNodeEventFunctions.addEventHandler;
3905
+ const draggingNodeSetter = funnel((node) => setDraggingNode(node), {
3906
+ reducer: (_, newNode) => newNode,
3907
+ triggerAt: "start",
3908
+ minQuietPeriodMs: 100
3909
+ });
3910
+ const draggingNodeUnsetter = funnel(() => setDraggingNode(void 0), {
3911
+ triggerAt: "start",
3912
+ minQuietPeriodMs: 100
3913
+ });
3914
+ function setDragging(node) {
3915
+ draggingNodeUnsetter.cancel();
3916
+ draggingNodeSetter.call(node);
3917
+ }
3918
+ function unsetDragging() {
3919
+ draggingNodeSetter.cancel();
3920
+ draggingNodeUnsetter.call();
3921
+ }
3922
+ const isNodeDrag = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isTruthy)(driveId), constant(false)], [({ driveId, srcId }) => isStrictEqual(driveId, srcId), constant(false)], constant(true));
3923
+ function useDragNode(args) {
3924
+ const { srcId, parentId } = args;
3925
+ const driveId = useSelectedDriveId();
3926
+ const draggingNodeId = useDraggingNode()?.srcId;
3927
+ const params = {
3928
+ driveId,
3929
+ srcId,
3930
+ parentId
3931
+ };
3932
+ const draggable = isNodeDrag(params);
3933
+ const isDragging = allPass({
3934
+ srcId,
3935
+ draggingNodeId
3936
+ }, [
3937
+ () => draggable,
3938
+ ({ srcId }) => isString(srcId),
3939
+ ({ draggingNodeId }) => isString(draggingNodeId),
3940
+ ({ srcId, draggingNodeId }) => isStrictEqual(srcId, draggingNodeId)
3941
+ ]);
3942
+ const onDragStart = () => {
3943
+ if (!draggable) return;
3944
+ setDragging(params);
3945
+ };
3946
+ const onDragEnd = () => {
3947
+ if (!draggable) return;
3948
+ unsetDragging();
3949
+ };
3950
+ return {
3951
+ isDragging,
3952
+ draggable,
3953
+ onDragStart,
3954
+ onDragEnd
3955
+ };
3956
+ }
3957
+ const isNodeDrop = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isDefined)(driveId), constant(false)], [({ srcId, targetId }) => isStrictEqual(srcId, targetId), constant(false)], [({ driveId, parentId, targetId }) => isNot(isTruthy)(parentId) && isStrictEqual(targetId, driveId), constant(false)], [({ targetId, parentId }) => isStrictEqual(targetId, parentId), constant(false)], constant(true));
3958
+ function useDropNode(targetId) {
3959
+ const driveId = useSelectedDriveId();
3960
+ const { srcId, parentId } = useDraggingNode() ?? {};
3961
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3962
+ const params = {
3963
+ driveId,
3964
+ parentId,
3965
+ targetId,
3966
+ srcId
3967
+ };
3968
+ function handleNodeDrop(event, cb) {
3969
+ if (!isNodeDrop(params)) return;
3970
+ event.preventDefault();
3971
+ event.stopPropagation();
3972
+ cb?.();
3973
+ }
3974
+ const onDragEnter = (event) => handleNodeDrop(event);
3975
+ const onDragOver = (event) => handleNodeDrop(event, once(setTarget));
3976
+ const onDragLeave = (event) => handleNodeDrop(event, once(unsetTarget));
3977
+ const onDrop = (event) => handleNodeDrop(event, once(() => {
3978
+ unsetDragging();
3979
+ unsetTarget();
3980
+ moveNodeById(params).catch(console.error);
3981
+ }));
3982
+ return {
3983
+ isDropTarget,
3984
+ onDragEnter,
3985
+ onDragOver,
3986
+ onDragLeave,
3987
+ onDrop
3988
+ };
3989
+ }
3990
+ //#endregion
3991
+ //#region src/hooks/graphql-reactor-client.ts
3992
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3993
+ const useGraphQLReactorClient = graphQLReactorClientEventFunctions.useValue;
3994
+ const setGraphQLReactorClient = graphQLReactorClientEventFunctions.setValue;
3995
+ const addGraphQLReactorClientEventHandler = graphQLReactorClientEventFunctions.addEventHandler;
3996
+ //#endregion
3997
+ //#region src/hooks/package-discovery.ts
3998
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3999
+ const usePackageDiscoveryService = packageDiscoveryFunctions.useValue;
4000
+ const setPackageDiscoveryService = packageDiscoveryFunctions.setValue;
4001
+ const addPackageDiscoveryServiceEventHandler = packageDiscoveryFunctions.addEventHandler;
4002
+ //#endregion
4003
+ //#region src/hooks/sync-selection.ts
4004
+ /** Applies a path's selection without writing the URL; idempotent.
4005
+ * @deprecated Set the store's `navigation`; its route loaders write the selection. */
4006
+ function syncSelectionFromPath(pathname = getCurrentPathname()) {
4007
+ const drives = getPHStore()?.drives;
4008
+ if (!drives) return;
4009
+ const driveSlug = extractDriveSlugFromPath(pathname);
4010
+ const selectedDriveId = getPHStore()?.selectedDriveId;
4011
+ if (!driveSlug) {
4012
+ if (selectedDriveId) selectDrive(void 0);
4013
+ return;
4014
+ }
4015
+ const drive = findDriveBySlug(drives, driveSlug);
4016
+ const selectedIsUnlisted = !!selectedDriveId && !drives.some((d) => d.header.id === selectedDriveId);
4017
+ if (drive) {
4018
+ if (drive.header.id !== selectedDriveId) setSelectedDriveId(drive.header.id);
4019
+ } else if (!selectedIsUnlisted) {
4020
+ selectDrive(driveSlug);
4021
+ return;
4022
+ }
4023
+ const nodeId = extractNodeIdFromSlug(extractNodeSlugFromPath(pathname));
4024
+ if (nodeId !== getPHStore()?.selectedNodeId) setSelectedNodeId(nodeId);
4025
+ }
4026
+ setBrowserOpenSync(() => syncSelectionFromPath());
4027
+ function syncOnPopState() {
4028
+ if (hasHostNavigation()) return;
4029
+ syncSelectionFromPath(window.location.pathname);
4030
+ }
4031
+ let popStateHandlerAdded = false;
4032
+ /** Syncs the selection on back/forward when no host navigation is set.
4033
+ * @deprecated Set the store's `navigation`; its router handles back/forward. */
4034
+ function addSyncSelectionOnPopStateEventHandler() {
4035
+ if (popStateHandlerAdded) return;
4036
+ popStateHandlerAdded = true;
4037
+ window.addEventListener("popstate", syncOnPopState);
4038
+ }
4039
+ /** @deprecated Set the store's `navigation`; its router handles back/forward. */
4040
+ const addSetSelectedDriveOnPopStateEventHandler = addSyncSelectionOnPopStateEventHandler;
4041
+ /** @deprecated Set the store's `navigation`; its router handles back/forward. */
4042
+ const addSetSelectedNodeOnPopStateEventHandler = addSyncSelectionOnPopStateEventHandler;
4043
+ //#endregion
4044
+ //#region src/hooks/selected-timeline-item.ts
4045
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
4046
+ /** Returns the selected timeline item */
4047
+ const useSelectedTimelineItem = selectedTimelineItemEventFunctions.useValue;
4048
+ /** Sets the selected timeline item */
4049
+ const setSelectedTimelineItem = selectedTimelineItemEventFunctions.setValue;
4050
+ /** Adds event handler for selected timeline item */
4051
+ const addSelectedTimelineItemEventHandler = selectedTimelineItemEventFunctions.addEventHandler;
4052
+ //#endregion
4053
+ //#region src/hooks/timeline-revision.ts
4054
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
4055
+ /** Returns the selected timeline revision. */
4056
+ const useSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.useValue;
4057
+ /** Sets the selected timeline revision. */
4058
+ const setSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.setValue;
4059
+ /** Adds an event handler for the selected timeline revision. */
4060
+ const addSelectedTimelineRevisionEventHandler = selectedTimelineRevisionEventFunctions.addEventHandler;
4061
+ //#endregion
4062
+ //#region src/hooks/toast.ts
4063
+ const toastEventFunctions = makePHEventFunctions("toast");
4064
+ /** Returns the toast function */
4065
+ const usePHToast = toastEventFunctions.useValue;
4066
+ /** Sets the toast function */
4067
+ const setPHToast = toastEventFunctions.setValue;
4068
+ /** Adds an event handler for the toast */
4069
+ const addToastEventHandler = toastEventFunctions.addEventHandler;
4070
+ //#endregion
4071
+ //#region src/hooks/add-ph-event-handlers.ts
4072
+ const commonGlobalEventHandlerFunctions = {
4073
+ loading: addLoadingEventHandler,
4074
+ drives: addDrivesEventHandler,
4075
+ backendAuth: addBackendAuthEventHandler,
4076
+ driveNodes: addDriveNodesEventHandler,
4077
+ selectedDriveId: () => {
4078
+ addSelectedDriveIdEventHandler();
4079
+ addSyncSelectionOnPopStateEventHandler();
4080
+ addResetSelectedNodeEventHandler();
4081
+ },
4082
+ selectedNodeId: () => {
4083
+ addSelectedNodeIdEventHandler();
4084
+ },
4085
+ documentCache: addDocumentCacheEventHandler,
4086
+ reactorGraphQLClient: addGraphQLReactorClientEventHandler,
4087
+ draggingNode: addDraggingNodeEventHandler
4088
+ };
4089
+ const phGlobalEventHandlerRegisterFunctions = {
4090
+ ...commonGlobalEventHandlerFunctions,
4091
+ reactorClientModule: addReactorClientModuleEventHandler,
4092
+ reactorClient: addReactorClientEventHandler,
4093
+ reactor: addReactorHalvesEventHandler,
4094
+ fullReactorClient: addFullReactorClientEventHandler,
4095
+ attachmentService: addAttachmentServiceEventHandler,
4096
+ switchboards: addSwitchboardsEventHandler,
4097
+ features: addFeaturesEventHandler,
4098
+ modal: addModalEventHandler,
4099
+ renown: addRenownEventHandler,
4100
+ vetraPackageManager: addVetraPackageManagerEventHandler,
4101
+ packageDiscoveryService: addPackageDiscoveryServiceEventHandler,
4102
+ selectedTimelineRevision: addSelectedTimelineRevisionEventHandler,
4103
+ selectedTimelineItem: addSelectedTimelineItemEventHandler,
4104
+ routerBasename: addRouterBasenameEventHandler,
4105
+ version: addVersionEventHandler,
4106
+ logLevel: addLogLevelEventHandler,
4107
+ requiresHardRefresh: addRequiresHardRefreshEventHandler,
4108
+ warnOutdatedApp: addWarnOutdatedAppEventHandler,
4109
+ studioMode: addStudioModeEventHandler,
4110
+ basePath: addBasePathEventHandler,
4111
+ versionCheckInterval: addVersionCheckIntervalEventHandler,
4112
+ cliVersion: addCliVersionEventHandler,
4113
+ fileUploadOperationsChunkSize: addFileUploadOperationsChunkSizeEventHandler,
4114
+ isDocumentModelSelectionSettingsEnabled: addIsDocumentModelSelectionSettingsEnabledEventHandler,
4115
+ gaTrackingId: addGaTrackingIdEventHandler,
4116
+ allowList: addAllowListEventHandler,
4117
+ defaultDrivesUrl: addDefaultDrivesUrlEventHandler,
4118
+ drivesPreserveStrategy: addDrivesPreserveStrategyEventHandler,
4119
+ allowedDocumentTypes: addAllowedDocumentTypesEventHandler,
4120
+ enabledEditors: addEnabledEditorsEventHandler,
4121
+ disabledEditors: addDisabledEditorsEventHandler,
4122
+ isAddDriveEnabled: addIsAddDriveEnabledEventHandler,
4123
+ isLocalDrivesEnabled: addIsLocalDrivesEnabledEventHandler,
4124
+ isPublicDrivesEnabled: addIsPublicDrivesEnabledEventHandler,
4125
+ isAddPublicDrivesEnabled: addIsAddPublicDrivesEnabledEventHandler,
4126
+ isDeletePublicDrivesEnabled: addIsDeletePublicDrivesEnabledEventHandler,
4127
+ isCloudDrivesEnabled: addIsCloudDrivesEnabledEventHandler,
4128
+ isAddCloudDrivesEnabled: addIsAddCloudDrivesEnabledEventHandler,
4129
+ isDeleteCloudDrivesEnabled: addIsDeleteCloudDrivesEnabledEventHandler,
4130
+ isAddLocalDrivesEnabled: addIsAddLocalDrivesEnabledEventHandler,
4131
+ isDeleteLocalDrivesEnabled: addIsDeleteLocalDrivesEnabledEventHandler,
4132
+ isDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,
4133
+ isExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,
4134
+ isEditorDebugModeEnabled: addIsEditorDebugModeEnabledEventHandler,
4135
+ isEditorReadModeEnabled: addIsEditorReadModeEnabledEventHandler,
4136
+ isRelationalProcessorsEnabled: addIsRelationalProcessorsEnabledEventHandler,
4137
+ isExternalRelationalProcessorsEnabled: addIsExternalRelationalProcessorsEnabledEventHandler,
4138
+ isAnalyticsEnabled: addIsAnalyticsEnabledEventHandler,
4139
+ isAnalyticsExternalProcessorsEnabled: addIsAnalyticsExternalProcessorsEnabledEventHandler,
4140
+ analyticsDatabaseName: addAnalyticsDatabaseNameEventHandler,
4141
+ isAnalyticsDatabaseWorkerEnabled: addIsAnalyticsDatabaseWorkerEnabledEventHandler,
4142
+ isDiffAnalyticsEnabled: addIsDiffAnalyticsEnabledEventHandler,
4143
+ isDriveAnalyticsEnabled: addIsDriveAnalyticsEnabledEventHandler,
4144
+ renownUrl: addRenownUrlEventHandler,
4145
+ renownNetworkId: addRenownNetworkIdEventHandler,
4146
+ renownChainId: addRenownChainIdEventHandler,
4147
+ switchboardUrl: addSwitchboardUrlEventHandler,
4148
+ renownAdapters: addRenownAdaptersEventHandler,
4149
+ sentryRelease: addSentryReleaseEventHandler,
4150
+ sentryDsn: addSentryDsnEventHandler,
4151
+ sentryEnv: addSentryEnvEventHandler,
4152
+ isSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,
4153
+ isExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,
4154
+ isExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,
4155
+ toast: addToastEventHandler,
4156
+ navigation: () => {},
4157
+ aiTools: () => {}
4158
+ };
4159
+ function addPHEventHandlers() {
4160
+ callEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);
4161
+ }
4162
+ function callEventHandlerRegisterFunctions(registerFunctions) {
4163
+ forEachObj(registerFunctions, (fn) => fn());
4164
+ }
4165
+ //#endregion
4166
+ //#region src/graphql-client/graphql-reactor-provider.tsx
4167
+ /**
4168
+ * Registers the `window.ph` event handlers once per page.
4169
+ *
4170
+ * The `set*` helpers only dispatch CustomEvents - nothing writes `window.ph`
4171
+ * until `addPHEventHandlers` has registered the listeners that do. Registration
4172
+ * is guarded by a marker on `window` rather than a module-level flag so that a
4173
+ * hot module replacement, or two copies of this module, still register once.
4174
+ */
4175
+ function ensurePHEventHandlers() {
4176
+ if (typeof window === "undefined" || window.__phEventHandlersRegistered) return;
4177
+ addPHEventHandlers();
4178
+ window.__phEventHandlersRegistered = true;
4179
+ }
4180
+ /**
4181
+ * Mounts a {@link GraphQLReactorClient} into the `window.ph` slots the
4182
+ * reactor-browser hooks read, so `useDocument`, `useDispatch` and
4183
+ * `useReactorClient` work below it against a Switchboard, with no reactor in
4184
+ * the bundle.
4185
+ *
4186
+ * It fills the document slots, plus `window.ph.vetraPackageManager` when
4187
+ * `documentModels` is given (a fixed {@link StaticPackageManager}, which makes
4188
+ * the document-model hooks work). The same modules go to the client itself, so
4189
+ * a dispatch of two or more actions is signed rather than refused.
4190
+ * `window.ph.reactorClientModule` always stays empty, so full-reactor surfaces
4191
+ * (drives, jobs, editor auto-discovery) find nothing - an app below this
4192
+ * provider renders components it imports itself.
4193
+ *
4194
+ * The client is built on the client only: on the server the slots stay empty
4195
+ * and the hooks report their normal loading states. The props are read once,
4196
+ * when the client is built - changing `url` afterwards does not rebuild it.
4197
+ *
4198
+ * The effect's cleanup disposes the cache and the client's socket, and the
4199
+ * effect rebuilds both if it runs again on the same client - which is what a
4200
+ * `StrictMode` mount does.
4201
+ */
4202
+ function GraphQLReactorProvider({ url, tokenProvider, subscriptionsUrl, realtime, attachmentService, documentModels, children }) {
4203
+ const [client] = useState(() => typeof window === "undefined" ? void 0 : new GraphQLReactorClient({
4204
+ url,
4205
+ tokenProvider,
4206
+ subscriptionsUrl,
4207
+ realtime,
4208
+ documentModels
4209
+ }));
4210
+ useEffect(() => {
4211
+ if (!client) return;
4212
+ ensurePHEventHandlers();
4213
+ setReactorClient(client);
4214
+ const documentCache = new DocumentCache(client);
4215
+ setDocumentCache(documentCache);
4216
+ return () => {
4217
+ documentCache.dispose();
4218
+ client.dispose();
4219
+ };
4220
+ }, [client]);
4221
+ useEffect(() => {
4222
+ if (!attachmentService) return;
4223
+ ensurePHEventHandlers();
4224
+ setAttachmentService(attachmentService);
4225
+ }, [attachmentService]);
4226
+ useEffect(() => {
4227
+ if (!documentModels || documentModels.length === 0) return;
4228
+ ensurePHEventHandlers();
4229
+ setVetraPackageManager(new StaticPackageManager([packageFromDocumentModels(documentModels)]));
4230
+ }, [documentModels]);
4231
+ return /* @__PURE__ */ jsx(Fragment, { children });
4232
+ }
4233
+ /**
4234
+ * Returns the {@link GraphQLReactorClient} mounted by
4235
+ * {@link GraphQLReactorProvider}, or `undefined` when the slot holds something
4236
+ * else - the full in-browser reactor client, or nothing yet.
4237
+ *
4238
+ * `useReactorClient` is typed as the narrow `IReactorBrowserClient` subset both
4239
+ * implementations share. This is how a component reaches the light client's own
4240
+ * surface, i.e. `subgraph` and `request`.
4241
+ *
4242
+ * The narrowing is by brand, not by `instanceof`: a page can carry two copies
4243
+ * of this module - a bundled package with its own copy, or a hot-replaced one -
4244
+ * and `instanceof` would then answer `false` for a perfectly good client and
4245
+ * leave the component silently without one.
4246
+ */
4247
+ function useSwitchboardClient() {
4248
+ const client = useReactorClient();
4249
+ return isGraphQLReactorClient(client) ? client : void 0;
4250
+ }
4251
+ //#endregion
4252
+ //#region src/graphql-client/switchboard-backend.ts
4253
+ const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
4254
+ const DEFAULT_BATCH_REQUEST_TIMEOUT_MS = 12e4;
4255
+ const DEFAULT_BREAKER = Object.freeze({
4256
+ failures: 3,
4257
+ openMs: 3e4
4258
+ });
4259
+ function breakerSettings(breaker) {
4260
+ if (breaker === false) return {
4261
+ failures: Infinity,
4262
+ openMs: 0
4263
+ };
4264
+ return {
4265
+ ...DEFAULT_BREAKER,
4266
+ ...breaker
4267
+ };
4268
+ }
4269
+ const FACTS_QUERY = `
4270
+ query SwitchboardFacts {
4271
+ inspection {
4272
+ info {
4273
+ storage {
4274
+ engine
4275
+ persistence
4276
+ durable
4277
+ selfHeal
4278
+ }
4279
+ workflows
4280
+ syncChannels
4281
+ access {
4282
+ admin
4283
+ sql
4284
+ }
4285
+ }
4286
+ documentModels {
4287
+ documentType
4288
+ }
4289
+ }
4290
+ queries: __type(name: "Query") {
4291
+ fields {
4292
+ name
4293
+ }
4294
+ }
4295
+ inspectionFields: __type(name: "ReactorInspection") {
4296
+ fields {
4297
+ name
4298
+ }
4299
+ }
4300
+ }
4301
+ `;
4302
+ const MODEL_LOADING_QUERY = `
4303
+ query SwitchboardModelLoading {
4304
+ inspection {
4305
+ loadsModelsOnDemand
4306
+ }
4307
+ }
4308
+ `;
4309
+ /** Queries this backend sends that a Switchboard serves only from some version. */
4310
+ const REQUIRED_QUERIES = [
4311
+ "documentServed",
4312
+ "createDefaults",
4313
+ "inspection"
4314
+ ];
4315
+ /** The Switchboard's circuit is open: nothing was sent. */
4316
+ var SwitchboardUnreachableError = class extends Error {
4317
+ backend;
4318
+ retryAt;
4319
+ name = "SwitchboardUnreachableError";
4320
+ constructor(backend, retryAt) {
4321
+ super(`Switchboard backend ${JSON.stringify(backend)} is unreachable; nothing is sent until ${new Date(retryAt).toISOString()}`);
4322
+ this.backend = backend;
4323
+ this.retryAt = retryAt;
4324
+ }
4325
+ };
4326
+ /**
4327
+ * Opens after `failures` transport failures in a row (a network error, a
4328
+ * deadline or a 5xx) and sends nothing for `openMs`. Any other answer, a
4329
+ * GraphQL error included, closes it. The first request after `openMs` goes
4330
+ * through; one more failure opens it again.
4331
+ */
4332
+ var Breaker = class {
4333
+ backend;
4334
+ settings;
4335
+ consecutive = 0;
4336
+ openUntil;
4337
+ constructor(backend, settings) {
4338
+ this.backend = backend;
4339
+ this.settings = settings;
4340
+ }
4341
+ health() {
4342
+ return this.isOpen() ? "down" : "up";
4343
+ }
4344
+ wrap(inner) {
4345
+ return async (input, init) => {
4346
+ const openUntil = this.openUntil;
4347
+ if (openUntil !== void 0 && Date.now() < openUntil) throw new SwitchboardUnreachableError(this.backend, openUntil);
4348
+ let response;
4349
+ try {
4350
+ response = await inner(input, init);
4351
+ } catch (error) {
4352
+ if (!abortedByCaller(init?.signal)) this.fail();
4353
+ throw error;
4354
+ }
4355
+ if (response.status >= 500) this.fail();
4356
+ else {
4357
+ this.consecutive = 0;
4358
+ this.openUntil = void 0;
4359
+ }
4360
+ return response;
4361
+ };
4362
+ }
4363
+ isOpen() {
4364
+ return this.openUntil !== void 0 && Date.now() < this.openUntil;
4365
+ }
4366
+ fail() {
4367
+ this.consecutive += 1;
4368
+ if (this.consecutive >= this.settings.failures) this.openUntil = Date.now() + this.settings.openMs;
4369
+ }
4370
+ };
4371
+ function abortedByCaller(signal) {
4372
+ return Boolean(signal?.aborted) && !isDeadlineError(signal?.reason);
4373
+ }
4374
+ const NO_ACCESS = Object.freeze({
4375
+ admin: false,
4376
+ sql: false
4377
+ });
4378
+ /** Ids and slugs of documents this backend answered as drives, by drive id. */
4379
+ var KnownDrives = class {
4380
+ ids = /* @__PURE__ */ new Map();
4381
+ learn(document) {
4382
+ const { id, slug, documentType } = document.header;
4383
+ if (DRIVE_DOCUMENT_TYPES.includes(documentType)) {
4384
+ this.ids.set(id, id);
4385
+ if (slug) this.ids.set(slug, id);
4386
+ }
4387
+ return document;
4388
+ }
4389
+ learnPage(page) {
4390
+ for (const document of page.results) this.learn(document);
4391
+ return page;
4392
+ }
4393
+ /** Drops a drive the Switchboard refused, by id and by slug. */
4394
+ forget(driveId) {
4395
+ for (const [identifier, id] of this.ids) if (id === driveId) this.ids.delete(identifier);
4396
+ }
4397
+ driveOf(identifier) {
4398
+ return identifier === void 0 ? void 0 : this.ids.get(identifier);
4399
+ }
4400
+ /** Names a drive only when this backend proved it is one. */
4401
+ driveIdFor = (call) => {
4402
+ switch (call.method) {
4403
+ case "create":
4404
+ case "find": return this.driveOf(call.parentId);
4405
+ case "execute":
4406
+ case "deleteDocument": return this.driveOf(call.documentId);
4407
+ case "executeBatch":
4408
+ for (const job of call.jobs ?? []) {
4409
+ const drive = this.driveOf(job.documentId);
4410
+ if (drive !== void 0) return drive;
4411
+ }
4412
+ return;
4413
+ }
4414
+ };
4415
+ /** Runs a call that may carry `Drive-Id`; a 421 forgets the drive it named. */
4416
+ async refusable(call) {
4417
+ try {
4418
+ return await call;
4419
+ } catch (error) {
4420
+ if (GraphQLWrongBackendError.isError(error)) this.forget(error.driveId);
4421
+ throw error;
4422
+ }
4423
+ }
4424
+ };
4425
+ function isUnknownJob(job) {
4426
+ return job.status === "FAILED" && job.error?.name === "JobNotFoundError";
4427
+ }
4428
+ /** A Switchboard as a router backend; members GraphQL cannot serve are absent. */
4429
+ function createSwitchboardBackend(descriptor) {
4430
+ const drives = new KnownDrives();
4431
+ const breaker = new Breaker(descriptor.name, breakerSettings(descriptor.breaker));
4432
+ const signer = descriptor.signer;
4433
+ const gql = new GraphQLReactorClient({
4434
+ url: descriptor.url,
4435
+ tokenProvider: descriptor.tokenProvider,
4436
+ signer: typeof signer === "function" ? signer : () => signer,
4437
+ documentModels: descriptor.documentModels,
4438
+ realtime: descriptor.realtime,
4439
+ driveIdFor: drives.driveIdFor,
4440
+ requestTimeoutMs: descriptor.requestTimeoutMs ?? 3e4,
4441
+ batchRequestTimeoutMs: descriptor.batchRequestTimeoutMs ?? 12e4,
4442
+ fetch: breaker.wrap(descriptor.fetch ?? switchboardFetch)
4443
+ });
4444
+ const backend = {
4445
+ supports: {
4446
+ find: findIsServableOverGraphQL,
4447
+ pointInTimeViews: false
4448
+ },
4449
+ health: () => breaker.health(),
4450
+ drives: gql.read.drives,
4451
+ driveNodes: gql.nodeSource(),
4452
+ driveFileLinkTypes: ["child", DRIVE_CHILD_RELATIONSHIP_TYPE],
4453
+ submit: { execute: (identifier, branch, actions, signal) => drives.refusable(gql.executeAsync(identifier, branch, actions, signal)) },
4454
+ get: async (identifier, view, signal, consistencyToken) => drives.learn(await gql.get(identifier, view, signal, consistencyToken)),
4455
+ getMany: async (ids, view, signal) => (await gql.getMany(ids, view, signal)).map((document) => drives.learn(document)),
4456
+ getOperations: (identifier, view, filter, paging, signal) => gql.getOperations(identifier, view, filter, paging, signal),
4457
+ find: async (search, view, paging, signal) => drives.learnPage(await drives.refusable(gql.find(search, view, paging, signal))),
4458
+ isServed: (identifier, view, signal) => gql.isServed(identifier, view, signal),
4459
+ getOutgoingRelationships: (source, type, view, paging, signal) => gql.getOutgoingRelationships(source, type, view, paging, signal),
4460
+ getIncomingRelationships: (target, type, view, paging, signal) => gql.getIncomingRelationships(target, type, view, paging, signal),
4461
+ getOutgoingRelationshipEdges: (source, type, view, paging, signal) => gql.getOutgoingRelationshipEdges(source, type, view, paging, signal),
4462
+ getIncomingRelationshipEdges: (target, type, view, paging, signal) => gql.getIncomingRelationshipEdges(target, type, view, paging, signal),
4463
+ subscribe: (search, callback, view) => gql.subscribe(search, callback, view),
4464
+ getCreateSignaturePolicy: () => gql.getCreateSignaturePolicy(),
4465
+ getCreateProtocolVersions: (options, signal) => gql.getCreateProtocolVersions(options, signal),
4466
+ create: async (document, parent, signal) => drives.learn(await drives.refusable(gql.create(document, parent, signal))),
4467
+ execute: async (identifier, branch, actions, signal) => drives.learn(await drives.refusable(gql.execute(identifier, branch, actions, signal))),
4468
+ executeBatch: (request, signal) => drives.refusable(gql.executeBatch(request, signal)),
4469
+ deleteDocument: (identifier, propagate, signal) => drives.refusable(gql.deleteDocument(identifier, propagate, signal)),
4470
+ setPreferredEditor: (identifier, editor, branch, signal) => gql.setPreferredEditor(identifier, editor, branch, signal),
4471
+ getJob: async (jobId, signal) => {
4472
+ const job = await gql.getJob(jobId, signal);
4473
+ return job && isUnknownJob(job) ? void 0 : job;
4474
+ },
4475
+ waitForJob: (job, signal) => gql.waitForJob(job, signal),
4476
+ undo: async (identifier, scope, branch, signal) => drives.learn(await drives.refusable(gql.undo(identifier, scope, branch, signal))),
4477
+ redo: async (identifier, scope, branch, signal) => drives.learn(await drives.refusable(gql.redo(identifier, scope, branch, signal))),
4478
+ undoRedoTargets: (identifier, scope, view, signal) => gql.undoRedoTargets(identifier, scope, view, signal),
4479
+ undoRedoAvailability: (identifier, scope, branch, signal) => gql.undoRedoAvailability(identifier, scope, branch, signal)
4480
+ };
4481
+ let reading;
4482
+ const read = () => reading ??= readFacts(gql, descriptor.url).finally(() => {
4483
+ reading = void 0;
4484
+ });
4485
+ return {
4486
+ config: {
4487
+ name: descriptor.name,
4488
+ backend,
4489
+ facts: async () => (await read()).info,
4490
+ documentTypes: async () => (await read()).documentTypes,
4491
+ reach: {
4492
+ hosting: "remote",
4493
+ inspection: descriptor.inspection ?? "rpc"
4494
+ },
4495
+ refusesMisroutes: false
4496
+ },
4497
+ notifyCredentialsChanged: () => gql.notifyCredentialsChanged(),
4498
+ dispose: () => gql.dispose()
4499
+ };
4500
+ }
4501
+ function fieldNames(type) {
4502
+ return new Set(type?.fields?.map((field) => field.name));
4503
+ }
4504
+ async function readFacts(gql, url) {
4505
+ const answer = await gql.request(FACTS_QUERY);
4506
+ const served = fieldNames(answer.queries);
4507
+ const missing = REQUIRED_QUERIES.filter((query) => !served.has(query));
4508
+ if (missing.length > 0) throw new Error(`The Switchboard at ${url} does not serve ${missing.join(", ")}; it is older than this client`);
4509
+ const { info, documentModels } = answer.inspection;
4510
+ const closed = fieldNames(answer.inspectionFields).has("loadsModelsOnDemand") && !(await gql.request(MODEL_LOADING_QUERY)).inspection.loadsModelsOnDemand;
4511
+ return {
4512
+ info: {
4513
+ ...info,
4514
+ access: info.access ?? NO_ACCESS
4515
+ },
4516
+ documentTypes: closed ? documentModels.map((model) => model.documentType) : void 0
4517
+ };
4518
+ }
4519
+ //#endregion
4520
+ //#region src/hooks/document-operations.ts
4521
+ const DEFAULT_LIMIT = 100;
4522
+ function toError(reason) {
4523
+ return reason instanceof Error ? reason : new Error(String(reason));
4524
+ }
4525
+ const EMPTY_OPERATIONS = [];
4526
+ function useScopeOperations(documentId, scope, options = {}) {
4527
+ const { limit = DEFAULT_LIMIT, enabled = true } = options;
4528
+ const documentCache = useDocumentCache();
4529
+ const cache = documentCache && isOperationCache(documentCache) ? documentCache : void 0;
4530
+ const activeId = enabled && cache && documentId ? documentId : void 0;
4531
+ const getEntry = () => activeId && cache ? cache.getOperationsState(activeId, scope) : IDLE_OPERATIONS_ENTRY;
4532
+ const entry = useSyncExternalStore((onChange) => activeId && cache ? cache.subscribeOperations(activeId, onChange) : () => {}, getEntry, getEntry);
4533
+ useEffect(() => {
4534
+ if (activeId && cache && entry.status === "idle") cache.loadOperations(activeId, scope, limit);
4535
+ }, [
4536
+ activeId,
4537
+ cache,
4538
+ scope,
4539
+ limit,
4540
+ entry.status
4541
+ ]);
4542
+ const fetchNextPage = useCallback(() => {
4543
+ if (activeId && cache) cache.loadMoreOperations(activeId, scope);
4544
+ }, [
4545
+ activeId,
4546
+ cache,
4547
+ scope
4548
+ ]);
4549
+ const refetch = useCallback(() => {
4550
+ if (activeId && cache) cache.invalidateOperations(activeId);
4551
+ }, [activeId, cache]);
4552
+ const error = useMemo(() => entry.status === "error" ? toError(entry.error) : void 0, [entry.status, entry.error]);
4553
+ return {
4554
+ operations: entry.operations,
4555
+ isLoading: entry.status === "pending" || !!activeId && entry.status === "idle",
4556
+ error,
4557
+ hasNextPage: entry.hasNextPage,
4558
+ fetchNextPage,
4559
+ refetch
4560
+ };
4561
+ }
4562
+ /** Keeps paging `result` to completion while `enabled` is true. */
4563
+ function useLoadAllPages(result, enabled) {
4564
+ useEffect(() => {
4565
+ if (!enabled || !result.hasNextPage || result.isLoading) return;
4566
+ const handle = window.setTimeout(result.fetchNextPage, 0);
4567
+ return () => window.clearTimeout(handle);
4568
+ }, [
4569
+ enabled,
4570
+ result.hasNextPage,
4571
+ result.isLoading,
4572
+ result.fetchNextPage
4573
+ ]);
4574
+ }
4575
+ function useDocumentOperations(documentId, scope, options = {}) {
4576
+ const legacy = scope === void 0;
4577
+ const primary = useScopeOperations(documentId, legacy ? "global" : scope, legacy ? {} : options);
4578
+ const local = useScopeOperations(documentId, "local", { enabled: legacy });
4579
+ useLoadAllPages(primary, legacy);
4580
+ useLoadAllPages(local, legacy);
4581
+ const globalOperations = useMemo(() => legacy ? [...primary.operations] : EMPTY_OPERATIONS, [legacy, primary.operations]);
4582
+ const localOperations = useMemo(() => legacy ? [...local.operations] : EMPTY_OPERATIONS, [legacy, local.operations]);
4583
+ const refetch = useCallback(() => {
4584
+ primary.refetch();
4585
+ local.refetch();
4586
+ }, [primary.refetch, local.refetch]);
4587
+ const error = primary.error ?? local.error;
4588
+ const legacyResult = useMemo(() => ({
4589
+ globalOperations,
4590
+ localOperations,
4591
+ isLoading: !error && (primary.isLoading || local.isLoading || primary.hasNextPage || local.hasNextPage),
4592
+ error,
4593
+ refetch
4594
+ }), [
4595
+ globalOperations,
4596
+ localOperations,
4597
+ error,
4598
+ primary.isLoading,
4599
+ local.isLoading,
4600
+ primary.hasNextPage,
4601
+ local.hasNextPage,
4602
+ refetch
4603
+ ]);
4604
+ return legacy ? legacyResult : primary;
4605
+ }
4606
+ //#endregion
4607
+ export { addIsAddDriveEnabledEventHandler as $, copyNode$1 as $i, useIsDeleteLocalDrivesEnabled as $n, isGraphQLReactorClient as $r, setIsAnalyticsDatabaseWorkerEnabled as $t, setGraphQLReactorClient as A, useSearchParams as Aa, phDocumentFromGetDocument as Ai, setSwitchboardUrl as An, addIsDragAndDropEnabledEventHandler as Ar, addSentryEnvEventHandler as At, setAttachmentService as B, underSignaturePolicy as Bi, useDrivesPreserveStrategy as Bn, useAllowedDocumentTypes as Br, setAnalyticsDatabaseName as Bt, addSetSelectedNodeOnPopStateEventHandler as C, showPHModal as Ca, switchboardFetch as Ci, setRenownUrl as Cn, useSentryRelease as Cr, addRenownAdaptersEventHandler as Ct, setPackageDiscoveryService as D, isPlainClick as Da, GraphQLDriveReadClient as Di, setSentryEnv as Dn, useVersionCheckInterval as Dr, addRequiresHardRefreshEventHandler as Dt, addPackageDiscoveryServiceEventHandler as E, withoutModalSearch as Ea, GraphQLDriveNodeSource as Ei, setSentryDsn as En, useVersion as Er, addRenownUrlEventHandler as Et, useDropTarget as F, convertRemoteOperations as Fi, useAnalyticsDatabaseName as Fn, phDocumentEditorConfigHooks as Fr, addVersionEventHandler as Ft, addCliVersionEventHandler as G, GraphQLOperationNotSupportedError as Gi, useIsAddDriveEnabled as Gn, isBackendAuthError as Gr, setDrivesPreserveStrategy as Gt, addAllowListEventHandler as H, DEFAULT_DRIVE_EDITOR_ID as Hi, useFileUploadOperationsChunkSize as Hn, useIsExternalControlsEnabled as Hr, setCliVersion as Ht, addFeaturesEventHandler as I, extractRevisionMap as Ii, useBasePath as In, phDocumentEditorConfigSetters as Ir, addWarnOutdatedAppEventHandler as It, addDrivesPreserveStrategyEventHandler as J, queriesUnknownArgument as Ji, useIsAnalyticsDatabaseWorkerEnabled as Jn, useBackendAuth as Jr, setGaTrackingId as Jt, addDefaultDrivesUrlEventHandler as K, GraphQLWrongBackendError as Ki, useIsAddLocalDrivesEnabled as Kn, recordBackendAuthError as Kr, setEnabledEditors as Kt, setFeatures as L, hasRevisionConflict as Li, useCliVersion as Ln, setAllowedDocumentTypes as Lr, phGlobalConfigHooks as Lt, addDraggingNodeEventHandler as M, revisionMapFromRevisionsList as Mi, setVersionCheckInterval as Mn, isExternalControlsEnabledEventFunctions as Mr, addStudioModeEventHandler as Mt, useDragNode as N, ConflictError as Ni, setWarnOutdatedApp as Nn, phAppConfigHooks as Nr, addSwitchboardUrlEventHandler as Nt, usePackageDiscoveryService as O, useLinkProps as Oa, toLegacyNode as Oi, setSentryRelease as On, useWarnOutdatedApp as Or, addRouterBasenameEventHandler as Ot, useDropNode as P, buildPulledDocument as Pi, useAllowList as Pn, phAppConfigSetters as Pr, addVersionCheckIntervalEventHandler as Pt, addIsAddCloudDrivesEnabledEventHandler as Q, addFolder$1 as Qi, useIsDeleteCloudDrivesEnabled as Qn, findIsServableOverGraphQL as Qr, setIsAddPublicDrivesEnabled as Qt, useFeatures as R, screamingSnakeToCamel as Ri, useDefaultDrivesUrl as Rn, setIsDragAndDropEnabled as Rr, phGlobalConfigSetters as Rt, addSetSelectedDriveOnPopStateEventHandler as S, showDeleteNodeModal as Sa, isNodeFetch as Si, setRenownNetworkId as Sn, useSentryEnv as Sr, addLogLevelEventHandler as St, syncSelectionFromPath as T, usePHModal as Ta, withStreamedBodies as Ti, setRouterBasename as Tn, useSwitchboardUrl as Tr, addRenownNetworkIdEventHandler as Tt, addAnalyticsDatabaseNameEventHandler as U, DRIVE_DOCUMENT_TYPES as Ui, useGaTrackingId as Un, addBackendAuthEventHandler as Ur, setDefaultDrivesUrl as Ut, useAttachmentService as V, COMMON_PACKAGE_ID as Vi, useEnabledEditors as Vn, useIsDragAndDropEnabled as Vr, setBasePath as Vt, addBasePathEventHandler as W, BatchJobFailedError as Wi, useIsAddCloudDrivesEnabled as Wn, backendAuthStatusOf as Wr, setDisabledEditors as Wt, addFileUploadOperationsChunkSizeEventHandler as X, addDocument as Xi, useIsAnalyticsExternalProcessorsEnabled as Xn, ambientRenownSigner as Xr, setIsAddDriveEnabled as Xt, addEnabledEditorsEventHandler as Y, queriesUnknownField as Yi, useIsAnalyticsEnabled as Yn, GraphQLReactorClient as Yr, setIsAddCloudDrivesEnabled as Yt, addGaTrackingIdEventHandler as Z, addFileWithProgress as Zi, useIsCloudDrivesEnabled as Zn, createGraphQLDriveNodeSource as Zr, setIsAddLocalDrivesEnabled as Zt, setSelectedTimelineRevision as _, modalFromSearch as _a, ReactorOperationFieldsFragmentDoc as _i, setIsSentryTracingEnabled as _n, useRenownNetworkId as _r, addIsLocalDrivesEnabledEventHandler as _t, SwitchboardUnreachableError as a, loadFile as aa, subscriptionsUrlFromGraphqlUrl as ai, setIsDeletePublicDrivesEnabled as an, useIsEditorReadModeEnabled as ar, addIsCloudDrivesEnabledEventHandler as at, setSelectedTimelineItem as b, setPHModal as ba, globalFetch as bi, setRenownAdapters as bn, useRouterBasename as br, addIsSentryTracingEnabledEventHandler as bt, ensurePHEventHandlers as c, renameNode as ca, subgraphUrlFromGraphqlUrl as ci, setIsDriveAnalyticsEnabled as cn, useIsExternalRelationalProcessorsEnabled as cr, addIsDeletePublicDrivesEnabledEventHandler as ct, callEventHandlerRegisterFunctions as d, getUserPermissions as da, resolveDocumentModelModule as di, setIsExternalPackagesEnabled as dn, useIsRelationalProcessorsEnabled as dr, addIsDriveAnalyticsEnabledEventHandler as dt, deleteNode as ea, viewFilterInputFromViewFilter as ei, setIsAnalyticsEnabled as en, useIsDeletePublicDrivesEnabled as er, addIsAddLocalDrivesEnabledEventHandler as et, commonGlobalEventHandlerFunctions as f, isDocumentTypeSupported as fa, prepareSignedActions as fi, setIsExternalProcessorsEnabled as fn, useIsSentryTracingEnabled as fr, addIsEditorDebugModeEnabledEventHandler as ft, addSelectedTimelineRevisionEventHandler as g, isRoutedModal as ga, MutateDocumentWithOperationsDocument as gi, setIsRelationalProcessorsEnabled as gn, useRenownChainId as gr, addIsExternalRelationalProcessorsEnabledEventHandler as gt, usePHToast as h, closePHModal as ha, GetDocumentAtConsistencyDocument as hi, setIsPublicDrivesEnabled as hn, useRenownAdapters as hr, addIsExternalProcessorsEnabledEventHandler as ht, DEFAULT_REQUEST_TIMEOUT_MS as i, getDocumentExtension as ia, startDocumentChangesSubscription as ii, setIsDeleteLocalDrivesEnabled as in, useIsEditorDebugModeEnabled as ir, addIsAnalyticsExternalProcessorsEnabledEventHandler as it, useGraphQLReactorClient as j, useSetSearchParams as ja, phDocumentFromMutation as ji, setVersion as jn, addIsExternalControlsEnabledEventHandler as jr, addSentryReleaseEventHandler as jt, addGraphQLReactorClientEventHandler as k, usePHNavigation as ka, isoStringFromDateTime as ki, setStudioMode as kn, addAllowedDocumentTypesEventHandler as kr, addSentryDsnEventHandler as kt, useSwitchboardClient as l, setPreferredEditorOnNode as la, StaticPackageManager as li, setIsEditorDebugModeEnabled as ln, useIsLocalDrivesEnabled as lr, addIsDiffAnalyticsEnabledEventHandler as lt, setPHToast as m, addModalEventHandler as ma, stampAction as mi, setIsLocalDrivesEnabled as mn, useLogLevel as mr, addIsExternalPackagesEnabledEventHandler as mt, DEFAULT_BATCH_REQUEST_TIMEOUT_MS as n, extractInitialState as na, isAuthRefusalClose as ni, setIsCloudDrivesEnabled as nn, useIsDocumentModelSelectionSettingsEnabled as nr, addIsAnalyticsDatabaseWorkerEnabledEventHandler as nt, createSwitchboardBackend as o, moveNode$1 as oa, SubgraphSdkRegistry as oi, setIsDiffAnalyticsEnabled as on, useIsExternalPackagesEnabled as or, addIsDeleteCloudDrivesEnabledEventHandler as ot, addToastEventHandler as p, MODAL_SEARCH_PARAM as pa, signStampedAction as pi, setIsExternalRelationalProcessorsEnabled as pn, useLocalDrivesEnabled as pr, addIsEditorReadModeEnabledEventHandler as pt, addDisabledEditorsEventHandler as q, JobFailedError as qi, useIsAddPublicDrivesEnabled as qn, setBackendAuth as qr, setFileUploadOperationsChunkSize as qt, DEFAULT_BREAKER as r, fetchDocumentOperations as ra, makeAuthConnectionParams as ri, setIsDeleteCloudDrivesEnabled as rn, useIsDriveAnalyticsEnabled as rr, addIsAnalyticsEnabledEventHandler as rt, GraphQLReactorProvider as s, renameDriveNode as sa, describeGraphQLDocument as si, setIsDocumentModelSelectionSettingsEnabled as sn, useIsExternalProcessorsEnabled as sr, addIsDeleteLocalDrivesEnabledEventHandler as st, useDocumentOperations as t, exportFile as ta, createJobChangesSocket as ti, setIsAnalyticsExternalProcessorsEnabled as tn, useIsDiffAnalyticsEnabled as tr, addIsAddPublicDrivesEnabledEventHandler as tt, addPHEventHandlers as u, upgradeDocument as ua, packageFromDocumentModels as ui, setIsEditorReadModeEnabled as un, useIsPublicDrivesEnabled as ur, addIsDocumentModelSelectionSettingsEnabledEventHandler as ut, useSelectedTimelineRevision as v, modalHref as va, readCreateProtocolVersions as vi, setLocalDrivesEnabled as vn, useRenownUrl as vr, addIsPublicDrivesEnabledEventHandler as vt, addSyncSelectionOnPopStateEventHandler as w, useModalLinkProps as wa, withRequestDeadline as wi, setRequiresHardRefresh as wn, useStudioMode as wr, addRenownChainIdEventHandler as wt, useSelectedTimelineItem as x, showCreateDocumentModal as xa, isDeadlineError as xi, setRenownChainId as xn, useSentryDsn as xr, addLocalDrivesEnabledEventHandler as xt, addSelectedTimelineItemEventHandler as y, modalSearch as ya, readCreateSignaturePolicy as yi, setLogLevel as yn, useRequiresHardRefresh as yr, addIsRelationalProcessorsEnabledEventHandler as yt, addAttachmentServiceEventHandler as z, uncreatedDocument as zi, useDisabledEditors as zn, setIsExternalControlsEnabled as zr, setAllowList as zt };
4608
+
4609
+ //# sourceMappingURL=document-operations-D5QXcJbV.js.map