@powerhousedao/reactor-browser 6.2.2-dev.27 → 6.2.2-dev.29

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 (58) hide show
  1. package/dist/attachment-service-BbtWv6CL.d.ts +965 -0
  2. package/dist/attachment-service-BbtWv6CL.d.ts.map +1 -0
  3. package/dist/{client-_Gh2Uf0E.js → client-B1Af81HB.js} +26 -4
  4. package/dist/{client-_Gh2Uf0E.js.map → client-B1Af81HB.js.map} +1 -1
  5. package/dist/{client-DAJGpNZH.d.ts → client-CPfxm_9L.d.ts} +2 -2
  6. package/dist/{client-DAJGpNZH.d.ts.map → client-CPfxm_9L.d.ts.map} +1 -1
  7. package/dist/{client-DKuvLO3_.js → client-Zz_l9QzI.js} +1 -1
  8. package/dist/{client-DKuvLO3_.js.map → client-Zz_l9QzI.js.map} +1 -1
  9. package/dist/{document-by-id-dLYFX-xz.js → document-by-id-RNQCGkYh.js} +34 -42
  10. package/dist/document-by-id-RNQCGkYh.js.map +1 -0
  11. package/dist/document-model-modules-B2_aAWc7.js +2593 -0
  12. package/dist/document-model-modules-B2_aAWc7.js.map +1 -0
  13. package/dist/global-C8gV1GYv.d.ts +391 -0
  14. package/dist/global-C8gV1GYv.d.ts.map +1 -0
  15. package/dist/index-BHQr61KK.d.ts +345 -0
  16. package/dist/index-BHQr61KK.d.ts.map +1 -0
  17. package/dist/{index-B3keszpu.d.ts → index-CxxxP14A.d.ts} +2 -2
  18. package/dist/{index-B3keszpu.d.ts.map → index-CxxxP14A.d.ts.map} +1 -1
  19. package/dist/index.d.ts +25 -319
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +16 -1557
  22. package/dist/index.js.map +1 -1
  23. package/dist/{inspector-proxy-Doocf0nD.d.ts → inspector-proxy-CL1NSQyn.d.ts} +1 -1
  24. package/dist/{inspector-proxy-Doocf0nD.d.ts.map → inspector-proxy-CL1NSQyn.d.ts.map} +1 -1
  25. package/dist/{make-ph-event-functions-BHoLPif5.js → make-ph-event-functions-DBq3iWYn.js} +1 -1
  26. package/dist/{make-ph-event-functions-BHoLPif5.js.map → make-ph-event-functions-DBq3iWYn.js.map} +1 -1
  27. package/dist/{pglite-CntadC_p-BgIvrYtV.d.ts → pglite-CntadC_p-BtEalg1H.d.ts} +1 -1
  28. package/dist/{pglite-CntadC_p-BgIvrYtV.d.ts.map → pglite-CntadC_p-BtEalg1H.d.ts.map} +1 -1
  29. package/dist/{relational-Dj06-YkI.js → relational-DJlbclWB.js} +1 -1
  30. package/dist/{relational-Dj06-YkI.js.map → relational-DJlbclWB.js.map} +1 -1
  31. package/dist/renown-BZabzj4l.js +68 -0
  32. package/dist/renown-BZabzj4l.js.map +1 -0
  33. package/dist/{renown-Bihtk0Mj.js → renown-C7a1ygsj.js} +3 -65
  34. package/dist/renown-C7a1ygsj.js.map +1 -0
  35. package/dist/src/analytics/index.d.ts +1 -1
  36. package/dist/src/analytics/index.js +2 -1
  37. package/dist/src/analytics/index.js.map +1 -1
  38. package/dist/src/graphql/client.d.ts +3 -3
  39. package/dist/src/graphql/client.js +1 -1
  40. package/dist/src/graphql-client/entry.d.ts +4 -0
  41. package/dist/src/graphql-client/entry.js +3 -0
  42. package/dist/src/relational/index.d.ts +1 -1
  43. package/dist/src/relational/index.js +1 -1
  44. package/dist/src/renown/index.d.ts +1 -1
  45. package/dist/src/renown/index.js +2 -1
  46. package/dist/src/rpc/index.d.ts +2 -2
  47. package/dist/src/rpc/index.js +1 -1
  48. package/dist/store-DAJq6vSs.js +37 -0
  49. package/dist/store-DAJq6vSs.js.map +1 -0
  50. package/dist/{types-CVZRGBXo.d.ts → types-jEQ5crx9.d.ts} +20 -4
  51. package/dist/{types-CVZRGBXo.d.ts.map → types-jEQ5crx9.d.ts.map} +1 -1
  52. package/dist/{types-CPV0Cnsy.d.ts → types-wGaiXwjh.d.ts} +1 -1
  53. package/dist/{types-CPV0Cnsy.d.ts.map → types-wGaiXwjh.d.ts.map} +1 -1
  54. package/package.json +15 -9
  55. package/dist/document-by-id-dLYFX-xz.js.map +0 -1
  56. package/dist/index-BlPURnJv.d.ts +0 -714
  57. package/dist/index-BlPURnJv.d.ts.map +0 -1
  58. package/dist/renown-Bihtk0Mj.js.map +0 -1
@@ -0,0 +1,2593 @@
1
+ import { S as uploadOperations, _ as isDuplicateManifestError, a as setDocumentCache, b as queueActions, g as DOCUMENT_CHANGE_TYPE, i as addDocumentCacheEventHandler, n as useDocumentsByIds, p as DocumentCache, r as useDispatch, v as isDuplicateModuleError, x as queueOperations } from "./document-by-id-RNQCGkYh.js";
2
+ import { t as makePHEventFunctions } from "./make-ph-event-functions-DBq3iWYn.js";
3
+ import { a as PhDocumentFieldsFragmentDoc, n as DocumentChangeType, o as PropagationMode, r as DocumentChangesDocument, t as createClient$1 } from "./client-B1Af81HB.js";
4
+ import { f as addLoadingEventHandler, t as addRenownEventHandler } from "./renown-BZabzj4l.js";
5
+ import { logger } from "document-model";
6
+ import { assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, createPresignedHeader, createZip, documentModelDocumentType, generateId, hashDocumentStateForScope, replayDocumentVersioned, setName } from "@powerhousedao/shared/document-model";
7
+ import { addFolder, copyNode, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
8
+ import { allPass, conditional, constant, forEachObj, funnel, isDefined, isNot, isStrictEqual, isString, isTruthy, once } from "remeda";
9
+ import { useEffect, useState, useSyncExternalStore } from "react";
10
+ import { GraphQLClient } from "graphql-request";
11
+ import { gql } from "graphql-tag";
12
+ import { Kind, print } from "graphql";
13
+ import { createClient } from "graphql-ws/client";
14
+ import slug from "slug";
15
+ import { Fragment, jsx } from "react/jsx-runtime";
16
+ //#region src/errors.ts
17
+ var UnsupportedDocumentTypeError = class extends Error {
18
+ constructor(documentType) {
19
+ super(`Document type ${documentType} is not supported`);
20
+ this.name = "UnsupportedDocumentTypeError";
21
+ }
22
+ static isError(error) {
23
+ return Error.isError(error) && error.name === "UnsupportedDocumentTypeError";
24
+ }
25
+ };
26
+ var DocumentNotFoundError = class extends Error {
27
+ constructor(documentId) {
28
+ super(`Document with id ${documentId} not found`);
29
+ }
30
+ };
31
+ var DocumentModelNotFoundError = class extends Error {
32
+ documentType;
33
+ name = "DocumentModelNotFoundError";
34
+ constructor(documentType) {
35
+ super(`Document model module for type ${documentType} not found`);
36
+ this.documentType = documentType;
37
+ }
38
+ static isError(error) {
39
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
40
+ }
41
+ };
42
+ var DocumentTypeMismatchError = class extends Error {
43
+ constructor(documentId, expectedType, actualType) {
44
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
45
+ }
46
+ };
47
+ var NoSelectedDocumentError = class extends Error {
48
+ constructor() {
49
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
50
+ }
51
+ };
52
+ //#endregion
53
+ //#region src/utils/documents.ts
54
+ function isDocumentTypeSupported(documentType, supportedDocuments) {
55
+ if (!supportedDocuments?.length) return true;
56
+ return supportedDocuments.some((pattern) => {
57
+ if (pattern.endsWith("/*")) {
58
+ const prefix = pattern.slice(0, -2);
59
+ return documentType.startsWith(prefix + "/");
60
+ }
61
+ if (pattern.endsWith("*") && !pattern.endsWith("/*")) {
62
+ const prefix = pattern.slice(0, -1);
63
+ return documentType.startsWith(prefix);
64
+ }
65
+ return pattern === documentType;
66
+ });
67
+ }
68
+ //#endregion
69
+ //#region src/utils/user.ts
70
+ function getUserPermissions() {
71
+ const user = window.ph?.renown?.user;
72
+ const allowList = window.ph?.allowList;
73
+ if (!allowList) return {
74
+ isAllowedToCreateDocuments: true,
75
+ isAllowedToEditDocuments: true
76
+ };
77
+ return {
78
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
79
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
80
+ };
81
+ }
82
+ //#endregion
83
+ //#region src/actions/document.ts
84
+ const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
85
+ async function isDocumentInLocation(document, driveId, parentFolder) {
86
+ const reactorClient = window.ph?.reactorClient;
87
+ if (!reactorClient) return { isDuplicate: false };
88
+ let drive;
89
+ try {
90
+ drive = await reactorClient.get(driveId);
91
+ } catch {
92
+ return { isDuplicate: false };
93
+ }
94
+ const nodeById = drive.state.global.nodes.find((node) => node.id === document.header.id);
95
+ if (nodeById && nodeById.parentFolder === (parentFolder ?? null)) return {
96
+ isDuplicate: true,
97
+ duplicateType: "id",
98
+ nodeId: nodeById.id
99
+ };
100
+ const nodeByNameAndType = drive.state.global.nodes.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType && node.parentFolder === (parentFolder ?? null));
101
+ if (nodeByNameAndType) return {
102
+ isDuplicate: true,
103
+ duplicateType: "name",
104
+ nodeId: nodeByNameAndType.id
105
+ };
106
+ return { isDuplicate: false };
107
+ }
108
+ function getDocumentTypeIcon(document) {
109
+ switch (document.header.documentType) {
110
+ case "powerhouse/document-model": return "document-model";
111
+ case "powerhouse/app": return "app";
112
+ case "powerhouse/document-editor": return "editor";
113
+ case "powerhouse/subgraph": return "subgraph";
114
+ case "powerhouse/package": return "package";
115
+ case "powerhouse/processor": {
116
+ const processorType = document.state.global?.type;
117
+ if (processorType === "analytics") return "analytics-processor";
118
+ if (processorType === "relational") return "relational-processor";
119
+ if (processorType === "codegen") return "codegen-processor";
120
+ return;
121
+ }
122
+ default: return;
123
+ }
124
+ }
125
+ async function downloadFile(document, fileName) {
126
+ try {
127
+ const data = await createZip(document);
128
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
129
+ const link = window.document.createElement("a");
130
+ link.style.display = "none";
131
+ link.href = URL.createObjectURL(blob);
132
+ link.download = fileName;
133
+ window.document.body.appendChild(link);
134
+ link.click();
135
+ window.document.body.removeChild(link);
136
+ } catch (e) {
137
+ logger.error(e instanceof Error ? e.message : String(e));
138
+ }
139
+ }
140
+ async function getDocumentExtension(document) {
141
+ const documentType = document.header.documentType;
142
+ let rawExtension;
143
+ if (documentType === documentModelDocumentType) rawExtension = document.state.global?.extension;
144
+ else {
145
+ const reactorClient = window.ph?.reactorClientModule?.client;
146
+ if (reactorClient) {
147
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
148
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
149
+ }
150
+ }
151
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
152
+ }
153
+ /**
154
+ * Fetches all operations for a document using cursor-based pagination.
155
+ * The reactor client handles multi-scope cursors transparently via
156
+ * composite cursors, so all scopes are fetched in a single paginated stream.
157
+ */
158
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
159
+ const scopes = Object.keys(document.state);
160
+ const operations = {};
161
+ for (const scope of scopes) operations[scope] = [];
162
+ let cursor = "";
163
+ do {
164
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
165
+ cursor,
166
+ limit: pageSize
167
+ });
168
+ for (const op of page.results) {
169
+ const scope = op.action.scope ?? "global";
170
+ if (operations[scope]) operations[scope].push(op);
171
+ }
172
+ cursor = page.nextCursor ?? "";
173
+ } while (cursor);
174
+ return operations;
175
+ }
176
+ function extractInitialState(documentScopeOps) {
177
+ const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
178
+ if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
179
+ const input = upgradeOp.action.input;
180
+ const initialState = input.initialState ?? input.state;
181
+ if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
182
+ return initialState;
183
+ }
184
+ function filterDomainOperations(operations) {
185
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
186
+ }
187
+ async function exportFile(document, suggestedName) {
188
+ const reactorClient = window.ph?.reactorClient;
189
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
190
+ const operations = await fetchDocumentOperations(reactorClient, document);
191
+ const initialState = extractInitialState(operations["document"] ?? []);
192
+ const documentWithOps = {
193
+ ...document,
194
+ operations,
195
+ initialState
196
+ };
197
+ const extension = await getDocumentExtension(documentWithOps);
198
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
199
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
200
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
201
+ try {
202
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
203
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
204
+ return fileHandle;
205
+ } catch (e) {
206
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
207
+ }
208
+ }
209
+ /**
210
+ * Loads a document file and replays it with version-aware reducers from the registry.
211
+ * Falls back to single-version legacy replay when no upgrade manifest is registered for
212
+ * the document type.
213
+ */
214
+ async function loadFile(path) {
215
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
216
+ const reactorClient = window.ph?.reactorClientModule?.client;
217
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
218
+ const documentType = baseDocument.header.documentType;
219
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
220
+ const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
221
+ if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
222
+ const reducers = {};
223
+ for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
224
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
225
+ let upgradeManifest;
226
+ if (registry) try {
227
+ upgradeManifest = registry.getUpgradeManifest(documentType);
228
+ } catch {}
229
+ return baseLoadFromInputVersioned(path, {
230
+ reducers,
231
+ upgradeManifest
232
+ });
233
+ }
234
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
235
+ const { isAllowedToCreateDocuments } = getUserPermissions();
236
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
237
+ const reactorClient = window.ph?.reactorClientModule?.client;
238
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
239
+ const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
240
+ const newDocument = document ?? documentModelModule.utils.createDocument();
241
+ newDocument.header.name = name;
242
+ if (preferredEditor) newDocument.header.meta = {
243
+ ...newDocument.header.meta,
244
+ preferredEditor
245
+ };
246
+ let newDoc;
247
+ try {
248
+ newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
249
+ } catch (e) {
250
+ logger.error("Error adding document: @error", e);
251
+ throw new Error("There was an error adding document", { cause: e });
252
+ }
253
+ return {
254
+ id: newDoc.header.id,
255
+ name: newDoc.header.name,
256
+ documentType,
257
+ parentFolder: parentFolder ?? null,
258
+ kind: "file"
259
+ };
260
+ }
261
+ async function addFile(file, driveId, name, parentFolder) {
262
+ logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
263
+ const { isAllowedToCreateDocuments } = getUserPermissions();
264
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
265
+ const document = await loadFile(file);
266
+ let duplicateId = false;
267
+ const reactorClient = window.ph?.reactorClient;
268
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
269
+ try {
270
+ await reactorClient.get(document.header.id);
271
+ duplicateId = true;
272
+ } catch {}
273
+ const documentId = duplicateId ? generateId() : document.header.id;
274
+ const header = createPresignedHeader(documentId, document.header.documentType);
275
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
276
+ header.meta = document.header.meta;
277
+ header.name = name || document.header.name;
278
+ const initialDocument = {
279
+ ...document,
280
+ header,
281
+ state: document.initialState,
282
+ operations: Object.keys(document.operations).reduce((acc, key) => {
283
+ acc[key] = [];
284
+ return acc;
285
+ }, {})
286
+ };
287
+ await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
288
+ await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
289
+ }
290
+ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
291
+ logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
292
+ const reactor = window.ph?.reactorClientModule?.client;
293
+ if (!reactor) return;
294
+ const { isAllowedToCreateDocuments } = getUserPermissions();
295
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
296
+ try {
297
+ onProgress?.({
298
+ stage: "loading",
299
+ progress: 0
300
+ });
301
+ let document;
302
+ try {
303
+ document = await loadFile(file);
304
+ } catch (loadError) {
305
+ const discoveryService = window.ph?.packageDiscoveryService;
306
+ if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
307
+ retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
308
+ return;
309
+ }
310
+ throw loadError;
311
+ }
312
+ const duplicateCheck = await isDocumentInLocation(document, driveId, parentFolder);
313
+ if (duplicateCheck.isDuplicate && !resolveConflict) {
314
+ onProgress?.({
315
+ stage: "conflict",
316
+ progress: 0,
317
+ duplicateType: duplicateCheck.duplicateType
318
+ });
319
+ return;
320
+ }
321
+ const documentType = getDocumentTypeIcon(document);
322
+ if (documentType) onProgress?.({
323
+ stage: "loading",
324
+ progress: 10,
325
+ documentType
326
+ });
327
+ else onProgress?.({
328
+ stage: "loading",
329
+ progress: 10
330
+ });
331
+ if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {
332
+ onProgress?.({
333
+ stage: "unsupported-document-type",
334
+ progress: 100,
335
+ error: `Document type ${document.header.documentType} is not supported`
336
+ });
337
+ throw new UnsupportedDocumentTypeError(document.header.documentType);
338
+ }
339
+ await reactor.getDocumentModelModule(document.header.documentType);
340
+ onProgress?.({
341
+ stage: "initializing",
342
+ progress: 10
343
+ });
344
+ let duplicateId = false;
345
+ try {
346
+ await reactor.get(document.header.id);
347
+ duplicateId = true;
348
+ } catch {}
349
+ const documentId = duplicateId ? generateId() : document.header.id;
350
+ const header = createPresignedHeader(documentId, document.header.documentType);
351
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
352
+ header.meta = document.header.meta;
353
+ header.name = name || document.header.name;
354
+ const initialDocument = {
355
+ ...document,
356
+ header,
357
+ state: document.initialState,
358
+ operations: Object.keys(document.operations).reduce((acc, key) => {
359
+ acc[key] = [];
360
+ return acc;
361
+ }, {})
362
+ };
363
+ const fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
364
+ if (!fileNode) throw new Error("There was an error adding file");
365
+ onProgress?.({
366
+ stage: "initializing",
367
+ progress: 20
368
+ });
369
+ await reactor.get(documentId);
370
+ console.log("Document created, starting upload of operations");
371
+ await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations, { onProgress: (uploadProgress) => {
372
+ if (uploadProgress.totalOperations && uploadProgress.uploadedOperations !== void 0) {
373
+ const uploadPercent = uploadProgress.totalOperations > 0 ? uploadProgress.uploadedOperations / uploadProgress.totalOperations : 0;
374
+ const overallProgress = 20 + Math.round(uploadPercent * 80);
375
+ onProgress?.({
376
+ stage: "uploading",
377
+ progress: overallProgress,
378
+ totalOperations: uploadProgress.totalOperations,
379
+ uploadedOperations: uploadProgress.uploadedOperations
380
+ });
381
+ }
382
+ } });
383
+ onProgress?.({
384
+ stage: "complete",
385
+ progress: 100,
386
+ fileNode
387
+ });
388
+ return fileNode;
389
+ } catch (error) {
390
+ if (!UnsupportedDocumentTypeError.isError(error)) {
391
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
392
+ onProgress?.({
393
+ stage: "failed",
394
+ progress: 100,
395
+ error: errorMessage
396
+ });
397
+ }
398
+ throw error;
399
+ }
400
+ }
401
+ async function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
402
+ if (!discoveryService) return;
403
+ try {
404
+ await discoveryService.load(documentType);
405
+ } catch {
406
+ onProgress?.({
407
+ stage: "unsupported-document-type",
408
+ progress: 100,
409
+ error: `Document type ${documentType} is not supported`
410
+ });
411
+ return;
412
+ }
413
+ await addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
414
+ }
415
+ async function addFolder$1(driveId, name, parentFolder) {
416
+ const { isAllowedToCreateDocuments } = getUserPermissions();
417
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
418
+ const reactorClient = window.ph?.reactorClient;
419
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
420
+ await reactorClient.get(driveId);
421
+ const folderId = generateId();
422
+ const node = (await reactorClient.execute(driveId, "main", [addFolder({
423
+ id: folderId,
424
+ name,
425
+ parentFolder
426
+ })])).state.global.nodes.find((node) => node.id === folderId);
427
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
428
+ return node;
429
+ }
430
+ async function deleteNode(driveId, nodeId) {
431
+ const { isAllowedToCreateDocuments } = getUserPermissions();
432
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to delete documents");
433
+ const reactorClient = window.ph?.reactorClientModule?.client;
434
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
435
+ await reactorClient.drives.removeNode(driveId, nodeId);
436
+ }
437
+ async function renameNode(driveId, nodeId, name) {
438
+ const { isAllowedToCreateDocuments } = getUserPermissions();
439
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
440
+ const reactorClient = window.ph?.reactorClient;
441
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
442
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
443
+ const node = (await reactorClient.execute(driveId, "main", [updateNode({
444
+ id: nodeId,
445
+ name
446
+ })])).state.global.nodes.find((n) => n.id === nodeId);
447
+ if (!node) throw new Error("There was an error renaming node in the drive");
448
+ return node;
449
+ }
450
+ async function renameDriveNode(driveId, nodeId, name) {
451
+ const { isAllowedToCreateDocuments } = getUserPermissions();
452
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
453
+ const reactorClient = window.ph?.reactorClient;
454
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
455
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
456
+ await reactorClient.execute(driveId, "main", [updateNode({
457
+ id: nodeId,
458
+ name
459
+ })]);
460
+ return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
461
+ }
462
+ async function moveNodeById(args) {
463
+ const { driveId, srcId, targetId } = args;
464
+ if (!driveId || !srcId) return;
465
+ const { isAllowedToCreateDocuments } = getUserPermissions();
466
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
467
+ const reactorClient = window.ph?.reactorClient;
468
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
469
+ const targetParentFolder = conditional(targetId, [isNot(isDefined), constant(void 0)], [isStrictEqual(driveId), constant(void 0)], constant(targetId));
470
+ if (isStrictEqual(targetParentFolder, srcId)) return;
471
+ return await reactorClient.execute(driveId, "main", [moveNode({
472
+ srcFolder: srcId,
473
+ targetParentFolder
474
+ })]);
475
+ }
476
+ async function moveNode$1(driveId, src, target) {
477
+ const { isAllowedToCreateDocuments } = getUserPermissions();
478
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
479
+ const reactorClient = window.ph?.reactorClient;
480
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
481
+ return await reactorClient.execute(driveId, "main", [moveNode({
482
+ srcFolder: src.id,
483
+ targetParentFolder: target?.id
484
+ })]);
485
+ }
486
+ /**
487
+ * Duplicates a document under a new id using version-aware replay.
488
+ * Falls back gracefully when no upgrade manifest is registered for the document type.
489
+ */
490
+ async function _duplicateDocument(reactor, document, newId = generateId()) {
491
+ const documentType = document.header.documentType;
492
+ const { results: allModules } = await reactor.getDocumentModelModules();
493
+ const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
494
+ const reducers = {};
495
+ for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
496
+ if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
497
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
498
+ let upgradeManifest;
499
+ if (registry) try {
500
+ upgradeManifest = registry.getUpgradeManifest(documentType);
501
+ } catch {}
502
+ const config = {
503
+ reducers,
504
+ upgradeManifest
505
+ };
506
+ const header = createPresignedHeader(newId, documentType);
507
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
508
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
509
+ return duplicated;
510
+ }
511
+ async function copyNode$1(driveId, src, target) {
512
+ const reactor = window.ph?.reactorClientModule?.client;
513
+ if (!reactor) return;
514
+ const { isAllowedToCreateDocuments } = getUserPermissions();
515
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
516
+ const drive = await reactor.get(driveId);
517
+ const copyNodesInput = generateNodesCopy({
518
+ srcId: src.id,
519
+ targetParentFolder: target?.id,
520
+ targetName: src.name
521
+ }, () => generateId(), drive.state.global.nodes);
522
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
523
+ for (const copyNodeInput of copyNodesInput) {
524
+ const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
525
+ if (node) {
526
+ const resolvedName = handleTargetNameCollisions({
527
+ nodes: drive.state.global.nodes,
528
+ srcName: copyNodeInput.targetName || node.name,
529
+ srcKind: isFileNode(node) ? "file" : "folder",
530
+ targetParentFolder: copyNodeInput.targetParentFolder || null
531
+ });
532
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
533
+ }
534
+ }
535
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
536
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
537
+ return node !== void 0 && isFileNode(node);
538
+ });
539
+ for (const fileNodeToCopy of fileNodesToCopy) try {
540
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
541
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
542
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
543
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
544
+ } catch (e) {
545
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
546
+ }
547
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
548
+ }
549
+ //#endregion
550
+ //#region src/hooks/modals.ts
551
+ const modalEventFunctions = makePHEventFunctions("modal");
552
+ /** Returns the current modal */
553
+ const usePHModal = modalEventFunctions.useValue;
554
+ /** Sets the current modal */
555
+ const setPHModal = modalEventFunctions.setValue;
556
+ /** Adds an event handler for the modal */
557
+ const addModalEventHandler = modalEventFunctions.addEventHandler;
558
+ /** Shows a modal */
559
+ function showPHModal(modal) {
560
+ setPHModal(modal);
561
+ }
562
+ /** Closes the current modal */
563
+ function closePHModal() {
564
+ setPHModal(void 0);
565
+ }
566
+ /** Shows the create document modal */
567
+ function showCreateDocumentModal(documentType) {
568
+ setPHModal({
569
+ type: "createDocument",
570
+ documentType
571
+ });
572
+ }
573
+ /** Shows the delete node modal */
574
+ function showDeleteNodeModal(nodeOrId) {
575
+ setPHModal({
576
+ type: "deleteItem",
577
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
578
+ });
579
+ }
580
+ //#endregion
581
+ //#region src/remote-controller/utils.ts
582
+ /** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. "SET_MODEL_NAME" → "setModelName"). */
583
+ function screamingSnakeToCamel(s) {
584
+ return s.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase());
585
+ }
586
+ /** Error thrown when a push conflict is detected with the "reject" strategy. */
587
+ var ConflictError = class extends Error {
588
+ constructor(conflict) {
589
+ super("Push conflict: remote has new operations since last pull");
590
+ this.conflict = conflict;
591
+ this.name = "ConflictError";
592
+ }
593
+ };
594
+ /** Convert a remote operation to the local Operation type. */
595
+ function remoteOperationToLocal(remote) {
596
+ return {
597
+ id: remote.id ?? "",
598
+ index: remote.index,
599
+ skip: remote.skip,
600
+ timestampUtcMs: remote.timestampUtcMs,
601
+ hash: remote.hash,
602
+ error: remote.error ?? void 0,
603
+ action: {
604
+ id: remote.action.id,
605
+ type: remote.action.type,
606
+ timestampUtcMs: remote.action.timestampUtcMs,
607
+ input: remote.action.input,
608
+ scope: remote.action.scope,
609
+ context: remote.action.context?.signer ? { signer: {
610
+ user: remote.action.context.signer.user ?? {
611
+ address: "",
612
+ networkId: "",
613
+ chainId: 0
614
+ },
615
+ app: remote.action.context.signer.app ?? {
616
+ name: "",
617
+ key: ""
618
+ },
619
+ signatures: remote.action.context.signer.signatures.map((s) => deserializeSignature(s))
620
+ } } : void 0
621
+ }
622
+ };
623
+ }
624
+ /**
625
+ * Deserialize a signature string back to a 5-element tuple.
626
+ * The server serializes tuples via `tuple.join(", ")`.
627
+ */
628
+ function deserializeSignature(s) {
629
+ const parts = s.split(", ");
630
+ return [
631
+ parts[0] ?? "",
632
+ parts[1] ?? "",
633
+ parts[2] ?? "",
634
+ parts[3] ?? "",
635
+ parts[4] ?? ""
636
+ ];
637
+ }
638
+ /** Convert remote operations to local DocumentOperations format. */
639
+ function convertRemoteOperations(operationsByScope) {
640
+ const operations = {};
641
+ for (const [scope, remoteOps] of Object.entries(operationsByScope)) operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));
642
+ return operations;
643
+ }
644
+ /** Reconstruct a PHDocument from remote document data and operations. */
645
+ function buildPulledDocument(remoteDoc, operations, initialDoc, branch) {
646
+ return {
647
+ header: {
648
+ ...initialDoc.header,
649
+ id: remoteDoc.id,
650
+ name: remoteDoc.name,
651
+ slug: remoteDoc.slug ?? "",
652
+ documentType: remoteDoc.documentType,
653
+ createdAtUtcIso: typeof remoteDoc.createdAtUtcIso === "string" ? remoteDoc.createdAtUtcIso : remoteDoc.createdAtUtcIso.toISOString(),
654
+ lastModifiedAtUtcIso: typeof remoteDoc.lastModifiedAtUtcIso === "string" ? remoteDoc.lastModifiedAtUtcIso : remoteDoc.lastModifiedAtUtcIso.toISOString(),
655
+ revision: Object.fromEntries(remoteDoc.revisionsList.map((r) => [r.scope, r.revision])),
656
+ branch
657
+ },
658
+ state: remoteDoc.state,
659
+ initialState: initialDoc.initialState,
660
+ operations,
661
+ clipboard: []
662
+ };
663
+ }
664
+ /** Extract revision map from a remote document's revisionsList. */
665
+ function extractRevisionMap(revisionsList) {
666
+ return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
667
+ }
668
+ /**
669
+ * Check if any scope in currentRevision is ahead of knownRevision.
670
+ * When `scopes` is provided, only those scopes are checked.
671
+ */
672
+ function hasRevisionConflict(currentRevision, knownRevision, scopes) {
673
+ for (const scope in currentRevision) {
674
+ if (scopes && !scopes.has(scope)) continue;
675
+ if ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) return true;
676
+ }
677
+ return false;
678
+ }
679
+ //#endregion
680
+ //#region src/graphql-client/adapter.ts
681
+ /**
682
+ * Converts a `GetDocument` result into a `PHDocument`.
683
+ *
684
+ * Unlike the legacy `src/graphql/adapters.ts` this preserves the per-scope
685
+ * revision map, which the write path needs to compute the `prevOpIndex` of a
686
+ * signed action. `sig` is filled with the empty shape used by
687
+ * `createPresignedHeader`: the creation signature is not fetchable over
688
+ * GraphQL and is not part of the operation signing payload.
689
+ *
690
+ * The read path never fetches operation history, so `operations` is a map of
691
+ * the document's known scopes to empty arrays.
692
+ *
693
+ * `branch` is the branch the document was read from. The GraphQL type does not
694
+ * carry it, so it has to be passed back in by the caller; it defaults to the
695
+ * server's own default branch.
696
+ */
697
+ function phDocumentFromGetDocument(document, branch) {
698
+ const state = document.state;
699
+ return {
700
+ header: phDocumentHeaderFromGetDocument(document, branch),
701
+ state,
702
+ initialState: state,
703
+ operations: emptyOperationsForScopes(document.revisionsList),
704
+ clipboard: []
705
+ };
706
+ }
707
+ /**
708
+ * Converts a mutation result into a `PHDocument`, carrying the operations the
709
+ * mutation produced.
710
+ *
711
+ * `dispatchActions` reads per-action failures out of `operations[scope]`, so
712
+ * unlike the read path this one must not return empty operation lists.
713
+ */
714
+ function phDocumentFromMutation(document, operations, branch) {
715
+ const phDocument = phDocumentFromGetDocument(document, branch);
716
+ const operationsByScope = { ...phDocument.operations };
717
+ for (const remote of operations) {
718
+ const operation = remoteOperationToLocal(remote);
719
+ const scope = operation.action.scope;
720
+ const scopeOperations = operationsByScope[scope] ?? [];
721
+ scopeOperations.push(operation);
722
+ operationsByScope[scope] = scopeOperations;
723
+ }
724
+ phDocument.operations = operationsByScope;
725
+ return phDocument;
726
+ }
727
+ /** Turns a `revisionsList` selection into the header's per-scope revision map. */
728
+ function revisionMapFromRevisionsList(revisionsList) {
729
+ return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
730
+ }
731
+ /** The branch the server reads and writes when none is asked for. */
732
+ const defaultBranch = "main";
733
+ function phDocumentHeaderFromGetDocument(document, branch) {
734
+ return {
735
+ id: document.id,
736
+ sig: {
737
+ publicKey: {},
738
+ nonce: ""
739
+ },
740
+ documentType: document.documentType,
741
+ createdAtUtcIso: isoStringFromDateTime(document.createdAtUtcIso),
742
+ slug: document.slug ?? "",
743
+ name: document.name,
744
+ branch: branch ?? defaultBranch,
745
+ revision: revisionMapFromRevisionsList(document.revisionsList),
746
+ lastModifiedAtUtcIso: isoStringFromDateTime(document.lastModifiedAtUtcIso)
747
+ };
748
+ }
749
+ function emptyOperationsForScopes(revisionsList) {
750
+ return Object.fromEntries(revisionsList.map((r) => [r.scope, []]));
751
+ }
752
+ /** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */
753
+ function isoStringFromDateTime(value) {
754
+ return value instanceof Date ? value.toISOString() : value;
755
+ }
756
+ //#endregion
757
+ //#region src/graphql-client/auth.ts
758
+ /** Lifetime requested for an ambient Renown token, in seconds. */
759
+ const ambientTokenExpiresInSeconds = 600;
760
+ /**
761
+ * The default token provider: the token of the currently logged-in Renown user.
762
+ *
763
+ * It is deliberately resolved from `window.ph` on every call rather than
764
+ * captured at construction time, so a client built before login starts sending
765
+ * the token as soon as there is one.
766
+ *
767
+ * The token is requested WITHOUT an `aud` claim - the Switchboard verifier
768
+ * rejects tokens that carry an audience.
769
+ */
770
+ async function ambientRenownTokenProvider() {
771
+ if (typeof window === "undefined") return;
772
+ const renown = window.ph?.renown;
773
+ if (!renown?.user) return;
774
+ return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });
775
+ }
776
+ /**
777
+ * Builds the SDK middleware that authenticates every request.
778
+ *
779
+ * The token is resolved per request and never cached, so a login, a logout or
780
+ * an expiry between two calls is picked up by the next one. When no token is
781
+ * available the request goes out unauthenticated.
782
+ */
783
+ function makeAuthMiddleware(tokenProvider) {
784
+ return async (action) => {
785
+ const token = await tokenProvider();
786
+ if (!token) return action();
787
+ return action({ authorization: `Bearer ${token}` });
788
+ };
789
+ }
790
+ //#endregion
791
+ //#region src/graphql-client/operations.ts
792
+ /**
793
+ * The operation selection of `GetDocumentOperations`, lifted into a fragment so
794
+ * the write path can reuse `remoteOperationToLocal` on the items it selects.
795
+ */
796
+ const ReactorOperationFieldsFragmentDoc = gql`
797
+ fragment ReactorOperationFields on ReactorOperation {
798
+ index
799
+ timestampUtcMs
800
+ hash
801
+ skip
802
+ error
803
+ id
804
+ action {
805
+ id
806
+ type
807
+ timestampUtcMs
808
+ input
809
+ scope
810
+ context {
811
+ signer {
812
+ user {
813
+ address
814
+ networkId
815
+ chainId
816
+ }
817
+ app {
818
+ name
819
+ key
820
+ }
821
+ signatures
822
+ }
823
+ }
824
+ }
825
+ }
826
+ `;
827
+ /**
828
+ * `mutateDocument` plus the operations the mutation produced.
829
+ *
830
+ * The generated `MutateDocument` only selects the document fields, but
831
+ * `dispatchActions` reads per-action failures out of `result.operations[scope]`
832
+ * (`src/actions/dispatch.ts`), so the reducer-level errors would be lost.
833
+ *
834
+ * The operations filter keeps the extra selection to the operations this call
835
+ * could have appended rather than the whole history. All three of its fields
836
+ * matter:
837
+ * - `sinceRevision` is the lowest head revision across the targeted scopes, so
838
+ * it is only a safe window when the selection is scope-limited as well;
839
+ * - `scopes` limits the response to the scopes the pushed actions target,
840
+ * without it the server walks every scope of the document
841
+ * (`packages/reactor/src/core/reactor.ts` `getOperations`);
842
+ * - `branch` must match the branch the mutation writes to, otherwise the
843
+ * operations come from `main` (the server's default) while the actions were
844
+ * applied elsewhere.
845
+ */
846
+ const MutateDocumentWithOperationsDocument = gql`
847
+ mutation MutateDocumentWithOperations(
848
+ $documentIdentifier: String!
849
+ $actions: [JSONObject!]!
850
+ $view: ViewFilterInput
851
+ $sinceRevision: Int
852
+ $scopes: [String!]
853
+ $branch: String
854
+ ) {
855
+ mutateDocument(
856
+ documentIdentifier: $documentIdentifier
857
+ actions: $actions
858
+ view: $view
859
+ ) {
860
+ ...PHDocumentFields
861
+ operations(
862
+ filter: {
863
+ sinceRevision: $sinceRevision
864
+ scopes: $scopes
865
+ branch: $branch
866
+ }
867
+ ) {
868
+ items {
869
+ ...ReactorOperationFields
870
+ }
871
+ }
872
+ }
873
+ }
874
+ ${PhDocumentFieldsFragmentDoc}
875
+ ${ReactorOperationFieldsFragmentDoc}
876
+ `;
877
+ //#endregion
878
+ //#region src/graphql-client/signing.ts
879
+ /**
880
+ * Stamps an action with the head of the scope it targets.
881
+ *
882
+ * `prevOpHash` is the hash of the scope state the action is meant to apply to;
883
+ * for a document at head that is the hash of the last operation in the scope,
884
+ * which the read path cannot fetch, so it is recomputed from the state.
885
+ * `prevOpIndex` is the index of that last operation: revisions count
886
+ * operations and indices are zero based, so an empty scope stamps `-1`, which
887
+ * matches what the remote controller records.
888
+ */
889
+ function stampAction(action, document) {
890
+ const revision = document.header.revision[action.scope] ?? 0;
891
+ return {
892
+ ...action,
893
+ context: {
894
+ ...action.context,
895
+ prevOpHash: hashDocumentStateForScope(document, action.scope),
896
+ prevOpIndex: revision - 1
897
+ }
898
+ };
899
+ }
900
+ /**
901
+ * Signs a stamped action, preserving any signatures it already carries.
902
+ *
903
+ * The signer reads `context.prevOpHash` off the action, so this must run after
904
+ * {@link stampAction}.
905
+ */
906
+ async function signStampedAction(action, signer) {
907
+ const actionSigner = action.context?.signer;
908
+ const user = actionSigner?.user ?? signer.user;
909
+ const app = actionSigner?.app ?? signer.app;
910
+ if (!user || !app) throw new Error("cannot sign an action: the signer has no user or app identity");
911
+ const signature = await signer.signAction(action);
912
+ return {
913
+ ...action,
914
+ context: {
915
+ ...action.context,
916
+ signer: {
917
+ user,
918
+ app,
919
+ signatures: [...actionSigner?.signatures ?? [], signature]
920
+ }
921
+ }
922
+ };
923
+ }
924
+ //#endregion
925
+ //#region src/graphql-client/subgraph.ts
926
+ /** What {@link describeGraphQLDocument} could not read off a document. */
927
+ const unnamedOperation = "AnonymousOperation";
928
+ const defaultOperationType = "query";
929
+ /**
930
+ * Derives a subgraph's endpoint from the Switchboard's GraphQL endpoint.
931
+ *
932
+ * Subgraphs are served next to the supergraph, at `<graphql base>/<name>`, so
933
+ * `http://localhost:4001/graphql` plus `statements` is
934
+ * `http://localhost:4001/graphql/statements`.
935
+ */
936
+ function subgraphUrlFromGraphqlUrl(url, name) {
937
+ const trimmed = name.trim();
938
+ if (trimmed === "") throw new Error("a subgraph name is required");
939
+ return `${url.replace(/\/+$/, "")}/${trimmed}`;
940
+ }
941
+ /**
942
+ * Reads the operation name and type off a document, for the middleware.
943
+ *
944
+ * Nothing depends on getting this right - it is reported to the middleware, not
945
+ * sent to the server - so an unreadable document falls back to an anonymous
946
+ * query rather than throwing.
947
+ */
948
+ function describeGraphQLDocument(document) {
949
+ if (typeof document !== "string") {
950
+ const operation = document.definitions.find((definition) => definition.kind === Kind.OPERATION_DEFINITION);
951
+ if (!operation || operation.kind !== Kind.OPERATION_DEFINITION) return {
952
+ operationName: unnamedOperation,
953
+ operationType: defaultOperationType
954
+ };
955
+ return {
956
+ operationName: operation.name?.value ?? unnamedOperation,
957
+ operationType: operation.operation
958
+ };
959
+ }
960
+ const match = /\b(query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/.exec(document);
961
+ if (!match) return {
962
+ operationName: unnamedOperation,
963
+ operationType: /\bmutation\b/.test(document) ? "mutation" : defaultOperationType
964
+ };
965
+ return {
966
+ operationName: match[2],
967
+ operationType: match[1]
968
+ };
969
+ }
970
+ /**
971
+ * Binds typed subgraph SDKs to one Switchboard's transport and auth.
972
+ *
973
+ * Every capability a Switchboard exposes lives behind the same base URL, so an
974
+ * app should not have to build a second client - with a second copy of the auth
975
+ * configuration - to reach a project's own subgraph. The registry derives the
976
+ * endpoint, reuses one transport per subgraph and hands the code generator's
977
+ * `getSdk` the very middleware the reactor operations already go through.
978
+ *
979
+ * Transport and typing only: subgraph results are not cached and produce no
980
+ * change events.
981
+ */
982
+ var SubgraphSdkRegistry = class {
983
+ url;
984
+ middleware;
985
+ bindings = /* @__PURE__ */ new Map();
986
+ constructor(url, middleware) {
987
+ this.url = url;
988
+ this.middleware = middleware;
989
+ }
990
+ /**
991
+ * Returns the subgraph's SDK, building it on first use.
992
+ *
993
+ * The transport is kept per subgraph name, so repeated calls do not rebuild
994
+ * it. The SDK itself is only reused when the same factory is passed again -
995
+ * two different generated SDKs over one subgraph each get their own, rather
996
+ * than the second call being handed the first one's methods.
997
+ */
998
+ get(name, getSdk) {
999
+ const binding = this.binding(name);
1000
+ if (binding.factory === getSdk) return binding.sdk;
1001
+ const sdk = getSdk(binding.transport, this.middleware);
1002
+ binding.factory = getSdk;
1003
+ binding.sdk = sdk;
1004
+ return sdk;
1005
+ }
1006
+ /** Returns the subgraph's endpoint, for diagnostics and tests. */
1007
+ urlFor(name) {
1008
+ return subgraphUrlFromGraphqlUrl(this.url, name);
1009
+ }
1010
+ binding(name) {
1011
+ const existing = this.bindings.get(name);
1012
+ if (existing) return existing;
1013
+ const binding = { transport: new GraphQLClient(this.urlFor(name)) };
1014
+ this.bindings.set(name, binding);
1015
+ return binding;
1016
+ }
1017
+ };
1018
+ //#endregion
1019
+ //#region src/graphql-client/subscriptions.ts
1020
+ /**
1021
+ * Opens one `documentChanges` subscription and feeds every event to `onEvent`.
1022
+ *
1023
+ * The subscription is a firehose: no `search` argument, so the server sends
1024
+ * every change the connection is allowed to see and the caller filters. This is
1025
+ * the only module that knows about `graphql-ws`.
1026
+ *
1027
+ * Returns the stop function, which cancels the subscription and closes the
1028
+ * socket. It is safe to call more than once.
1029
+ */
1030
+ function startDocumentChangesSubscription(options) {
1031
+ const client = createClient({
1032
+ url: options.wsUrl,
1033
+ connectionParams: options.connectionParams
1034
+ });
1035
+ const unsubscribe = client.subscribe({
1036
+ operationName: "DocumentChanges",
1037
+ query: print(DocumentChangesDocument)
1038
+ }, {
1039
+ next: (result) => {
1040
+ const event = result.data?.documentChanges;
1041
+ if (event) options.onEvent(event);
1042
+ },
1043
+ error: (error) => options.onError(error),
1044
+ complete: () => void 0
1045
+ });
1046
+ let stopped = false;
1047
+ return () => {
1048
+ if (stopped) return;
1049
+ stopped = true;
1050
+ unsubscribe();
1051
+ client.dispose();
1052
+ };
1053
+ }
1054
+ /**
1055
+ * Derives the websocket endpoint from the GraphQL http endpoint.
1056
+ *
1057
+ * `http://host/graphql` becomes `ws://host/graphql/subscriptions`, which is
1058
+ * where the Switchboard mounts its websocket server (`packages/reactor-api`
1059
+ * `startServer`). A URL that already speaks `ws`/`wss` only gets the path.
1060
+ */
1061
+ function subscriptionsUrlFromGraphqlUrl(url) {
1062
+ const trimmed = url.replace(/\/+$/, "");
1063
+ return `${trimmed.startsWith("https://") ? `wss://${trimmed.slice(8)}` : trimmed.startsWith("http://") ? `ws://${trimmed.slice(7)}` : trimmed}/subscriptions`;
1064
+ }
1065
+ /**
1066
+ * Turns a bearer token provider into `connectionParams`.
1067
+ *
1068
+ * The header key is the lowercase `authorization` the Switchboard's websocket
1069
+ * context factory reads. Without a token the payload is empty: an open
1070
+ * Switchboard serves anonymous subscribers.
1071
+ */
1072
+ function makeAuthConnectionParams(tokenProvider) {
1073
+ return async () => {
1074
+ const token = await tokenProvider();
1075
+ if (!token) return {};
1076
+ return { authorization: `Bearer ${token}` };
1077
+ };
1078
+ }
1079
+ //#endregion
1080
+ //#region src/graphql-client/graphql-reactor-client.ts
1081
+ /** Paging defaults, matching the reactor's own client. */
1082
+ const defaultPaging = {
1083
+ cursor: "0",
1084
+ limit: 100
1085
+ };
1086
+ /**
1087
+ * The marker {@link isGraphQLReactorClient} looks for.
1088
+ *
1089
+ * A page can end up with two copies of this module - an app that bundles a
1090
+ * package carrying its own copy, or a dev server that hot-replaced it - and
1091
+ * then `instanceof` compares an instance against the other copy's class object
1092
+ * and answers `false`. A branded property survives both.
1093
+ */
1094
+ const graphQLReactorClientBrand = "__powerhouseGraphQLReactorClient";
1095
+ /**
1096
+ * A light implementation of {@link IReactorBrowserClient} that talks plain
1097
+ * GraphQL to a Switchboard, with no reactor in the bundle.
1098
+ *
1099
+ * It fills the same `window.ph` slots the full in-browser reactor client fills,
1100
+ * so the reactor-browser hooks cannot tell the two apart.
1101
+ */
1102
+ var GraphQLReactorClient = class {
1103
+ /** See {@link isGraphQLReactorClient}. */
1104
+ [graphQLReactorClientBrand] = true;
1105
+ sdk;
1106
+ subgraphs;
1107
+ listeners = [];
1108
+ tokenProvider;
1109
+ subscriptionsUrl;
1110
+ stopRealtime;
1111
+ realtimeStarted = false;
1112
+ realtimeGeneration = 0;
1113
+ realtimeErrorLogged = false;
1114
+ constructor(options) {
1115
+ this.tokenProvider = options.tokenProvider ?? ambientRenownTokenProvider;
1116
+ this.subscriptionsUrl = options.realtime === false ? void 0 : options.subscriptionsUrl ?? subscriptionsUrlFromGraphqlUrl(options.url);
1117
+ const middleware = makeAuthMiddleware(this.tokenProvider);
1118
+ this.sdk = options.graphqlClient ?? createClient$1(options.url, middleware);
1119
+ this.subgraphs = new SubgraphSdkRegistry(options.url, middleware);
1120
+ }
1121
+ async get(identifier, view, signal) {
1122
+ const viewInput = viewFilterInputFromViewFilter(view);
1123
+ const document = (await this.sdk.GetDocument({
1124
+ identifier,
1125
+ view: viewInput
1126
+ }, void 0, signal)).document;
1127
+ if (!document) throw new Error(`Document not found: ${identifier}`);
1128
+ return phDocumentFromGetDocument(document.document, view?.branch);
1129
+ }
1130
+ async getOperations(documentIdentifier, view, filter, paging, signal) {
1131
+ const viewInput = viewFilterInputFromViewFilter(view);
1132
+ const operationsFilter = {
1133
+ documentId: documentIdentifier,
1134
+ branch: viewInput?.branch,
1135
+ scopes: viewInput?.scopes,
1136
+ actionTypes: filter?.actionTypes,
1137
+ timestampFrom: filter?.timestampFrom,
1138
+ timestampTo: filter?.timestampTo,
1139
+ sinceRevision: filter?.sinceRevision
1140
+ };
1141
+ const page = (await this.sdk.GetDocumentOperations({
1142
+ filter: operationsFilter,
1143
+ paging: pagingInputFromPaging(paging)
1144
+ }, void 0, signal)).documentOperations;
1145
+ const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
1146
+ const effectivePaging = paging ?? defaultPaging;
1147
+ return {
1148
+ results: page.items.map((item) => remoteOperationToLocal(item)),
1149
+ options: effectivePaging,
1150
+ nextCursor,
1151
+ totalCount: page.totalCount,
1152
+ next: nextCursor ? () => this.getOperations(documentIdentifier, view, filter, {
1153
+ cursor: nextCursor,
1154
+ limit: effectivePaging.limit
1155
+ }, signal) : void 0
1156
+ };
1157
+ }
1158
+ async create(document, parentIdentifier, signal) {
1159
+ const created = phDocumentFromGetDocument((await this.sdk.CreateDocument({
1160
+ document,
1161
+ parentIdentifier
1162
+ }, void 0, signal)).createDocument);
1163
+ this.emitChange({
1164
+ type: DOCUMENT_CHANGE_TYPE.Created,
1165
+ documents: [created]
1166
+ });
1167
+ return created;
1168
+ }
1169
+ /**
1170
+ * Pushes actions to the Switchboard and returns the updated document.
1171
+ *
1172
+ * The document is fetched first: the response is the baseline for the
1173
+ * `sinceRevision` filter that narrows the returned operations to the ones
1174
+ * this call appended, and it carries the state hash a signed action is
1175
+ * stamped with.
1176
+ *
1177
+ * The emitted `Updated` event carries the document's id, never the
1178
+ * identifier this was called with: subscribers - including `DocumentCache` -
1179
+ * work in id space.
1180
+ */
1181
+ async execute(documentIdentifier, branch, actions, signal) {
1182
+ const document = await this.get(documentIdentifier, { branch }, signal);
1183
+ const variables = {
1184
+ documentIdentifier,
1185
+ actions: await prepareActionsForPush(actions, document),
1186
+ view: { branch },
1187
+ sinceRevision: sinceRevisionForActions(document, actions),
1188
+ scopes: scopesForActions(actions),
1189
+ branch
1190
+ };
1191
+ const mutated = (await this.sdk.RunDocument({
1192
+ operationName: "MutateDocumentWithOperations",
1193
+ operationType: "mutation",
1194
+ document: MutateDocumentWithOperationsDocument,
1195
+ variables,
1196
+ signal
1197
+ })).mutateDocument;
1198
+ const updated = phDocumentFromMutation(mutated, mutated.operations?.items ?? [], branch);
1199
+ this.emitChange({
1200
+ type: DOCUMENT_CHANGE_TYPE.Updated,
1201
+ documents: [updated]
1202
+ });
1203
+ return updated;
1204
+ }
1205
+ /**
1206
+ * Deletes a document and announces it as a `Deleted` event.
1207
+ *
1208
+ * Pass a document id. The server resolves a slug just as happily, but
1209
+ * `deleteDocument` returns a boolean - there is no document left to read an
1210
+ * id off - so the identifier is announced verbatim on `context.childId`. A
1211
+ * subscriber keyed by id, `DocumentCache` included, therefore only reacts to
1212
+ * a delete by id.
1213
+ */
1214
+ async deleteDocument(identifier, propagate, signal) {
1215
+ await this.sdk.DeleteDocument({
1216
+ identifier,
1217
+ propagate: propagationModeInput(propagate)
1218
+ }, void 0, signal);
1219
+ this.emitChange({
1220
+ type: DOCUMENT_CHANGE_TYPE.Deleted,
1221
+ documents: [],
1222
+ context: { childId: identifier }
1223
+ });
1224
+ }
1225
+ /**
1226
+ * Registers a change subscriber and returns its unsubscribe function.
1227
+ *
1228
+ * Two things produce the events delivered here. Every successful `create`,
1229
+ * `execute` and `deleteDocument` emits one, which is what makes a
1230
+ * `DocumentCache` built on this client invalidate after a dispatch. And,
1231
+ * unless realtime is switched off, the first call to this method opens a
1232
+ * websocket to the Switchboard and every change it reports - from another
1233
+ * user, another tab or a server-side processor - is emitted too. A write of
1234
+ * this client's own is therefore announced twice, once locally and once by
1235
+ * the server; the cache refetches twice, which is harmless.
1236
+ *
1237
+ * A websocket that cannot be opened or is refused is logged once and then
1238
+ * ignored: realtime is an enhancement, never a dependency. The failed socket
1239
+ * is closed, so the next subscriber to arrive tries again.
1240
+ *
1241
+ * `view` is accepted for interface compatibility and ignored: the emitted
1242
+ * documents are whatever the write returned, so there is nothing to re-scope.
1243
+ *
1244
+ * Events live in id space: `search.ids` is matched against the resolved
1245
+ * document id, never against the identifier the write was issued with. The
1246
+ * one exception is `deleteDocument`, which has no document to resolve an id
1247
+ * from - see its own note. A `DocumentCache` on this client must therefore
1248
+ * be read by id: a slug-keyed entry is never invalidated.
1249
+ */
1250
+ subscribe(search, callback, view) {
1251
+ const listener = {
1252
+ search,
1253
+ callback
1254
+ };
1255
+ this.listeners.push(listener);
1256
+ this.startRealtime();
1257
+ return () => {
1258
+ const index = this.listeners.indexOf(listener);
1259
+ if (index !== -1) this.listeners.splice(index, 1);
1260
+ };
1261
+ }
1262
+ /**
1263
+ * Closes the realtime socket, if one was opened.
1264
+ *
1265
+ * Registered subscribers are left in place: they still receive the events
1266
+ * this client produces itself.
1267
+ *
1268
+ * Disposing is NOT final - a later `subscribe` opens a new socket. React
1269
+ * remounts a tree by running an effect's cleanup and then the effect again,
1270
+ * on the same client, and `StrictMode` does exactly that on every mount; a
1271
+ * terminal flag here would leave those pages without realtime for good, with
1272
+ * nothing logged.
1273
+ */
1274
+ dispose() {
1275
+ this.teardownRealtime();
1276
+ }
1277
+ /**
1278
+ * Binds a project's generated SDK to this client's transport and auth.
1279
+ *
1280
+ * Subgraphs are served next to the reactor's own supergraph, so the endpoint
1281
+ * is derived from the client's `url` by appending the name, and the SDK is
1282
+ * handed the same auth middleware every reactor call goes through. An app
1283
+ * therefore configures one URL and one token provider, and reaches every
1284
+ * capability of its Switchboard through this one client.
1285
+ *
1286
+ * `getSdk` is the function a GraphQL code generator emits for the subgraph's
1287
+ * schema - see the README in this folder for the codegen recipe.
1288
+ *
1289
+ * Transport and typing only. Subgraph results are not cached, produce no
1290
+ * change events and never reach `useDocument`.
1291
+ */
1292
+ subgraph(name, getSdk) {
1293
+ return this.subgraphs.get(name, getSdk);
1294
+ }
1295
+ /**
1296
+ * Runs a one-off GraphQL document against the Switchboard's own endpoint,
1297
+ * through the same transport and auth as everything else.
1298
+ *
1299
+ * The escape hatch for an operation not worth generating an SDK for. Pass a
1300
+ * document a code generator typed and the result type follows; pass a plain
1301
+ * `gql` document or a string and name the result type at the call site.
1302
+ */
1303
+ async request(document, variables, options) {
1304
+ const described = describeGraphQLDocument(document);
1305
+ return this.sdk.RunDocument({
1306
+ operationName: options?.operationName ?? described.operationName,
1307
+ operationType: options?.operationType ?? described.operationType,
1308
+ document,
1309
+ variables,
1310
+ signal: options?.signal
1311
+ });
1312
+ }
1313
+ /**
1314
+ * Opens the realtime socket on the first subscriber.
1315
+ *
1316
+ * The subscription is a firehose - no `search` argument - and this client
1317
+ * applies each subscriber's own filter on the way out, exactly as it does for
1318
+ * its own emissions.
1319
+ */
1320
+ startRealtime() {
1321
+ if (!this.subscriptionsUrl || this.realtimeStarted) return;
1322
+ this.realtimeStarted = true;
1323
+ const generation = this.realtimeGeneration;
1324
+ const stop = startDocumentChangesSubscription({
1325
+ wsUrl: this.subscriptionsUrl,
1326
+ connectionParams: makeAuthConnectionParams(this.tokenProvider),
1327
+ onEvent: (event) => this.emitServerEvent(event),
1328
+ onError: (error) => this.handleRealtimeFailure(generation, error)
1329
+ });
1330
+ if (this.realtimeGeneration !== generation) {
1331
+ stop();
1332
+ return;
1333
+ }
1334
+ this.stopRealtime = stop;
1335
+ }
1336
+ /**
1337
+ * Gives up on a failed socket so that a later subscriber can try again.
1338
+ *
1339
+ * `graphql-ws` retries on its own and only reports here once it has given up,
1340
+ * or once the server refused the subscription outright - which is what an
1341
+ * auth-enabled Switchboard does to an anonymous subscriber. Keeping the dead
1342
+ * stop function would make every later `subscribe` a no-op, so realtime would
1343
+ * stay off for the life of the page even after the user signs in.
1344
+ *
1345
+ * The generation stamp discards a report from a socket that has already been
1346
+ * replaced or disposed.
1347
+ */
1348
+ handleRealtimeFailure(generation, error) {
1349
+ if (generation !== this.realtimeGeneration) return;
1350
+ this.teardownRealtime();
1351
+ this.logRealtimeError(error);
1352
+ }
1353
+ /** Closes the socket and lets a later subscriber open a new one. */
1354
+ teardownRealtime() {
1355
+ this.realtimeGeneration += 1;
1356
+ this.realtimeStarted = false;
1357
+ this.stopRealtime?.();
1358
+ this.stopRealtime = void 0;
1359
+ }
1360
+ /** Maps a server event onto the client-side event and emits it. */
1361
+ emitServerEvent(event) {
1362
+ this.emitChange({
1363
+ type: documentChangeTypes[event.type],
1364
+ documents: event.documents.map((document) => phDocumentFromGetDocument(document)),
1365
+ context: event.context ? {
1366
+ parentId: event.context.parentId ?? void 0,
1367
+ childId: event.context.childId ?? void 0
1368
+ } : void 0
1369
+ });
1370
+ }
1371
+ /**
1372
+ * Reports a broken realtime socket once per client, however many sockets it
1373
+ * goes through.
1374
+ *
1375
+ * `graphql-ws` retries on its own, and a Switchboard without a websocket
1376
+ * endpoint would otherwise fill the console for as long as the page is open.
1377
+ */
1378
+ logRealtimeError(error) {
1379
+ if (this.realtimeErrorLogged) return;
1380
+ this.realtimeErrorLogged = true;
1381
+ logger.warn("GraphQLReactorClient: realtime document changes are unavailable, falling back to local change events", error);
1382
+ }
1383
+ /**
1384
+ * Delivers an event to every matching subscriber.
1385
+ *
1386
+ * A subscriber that throws is logged and skipped so one bad listener cannot
1387
+ * stop the others from being notified.
1388
+ */
1389
+ emitChange(event) {
1390
+ for (const listener of [...this.listeners]) {
1391
+ if (!eventMatchesSearch(event, listener.search)) continue;
1392
+ try {
1393
+ listener.callback(event);
1394
+ } catch (error) {
1395
+ logger.error("GraphQLReactorClient: a document change subscriber threw", error);
1396
+ }
1397
+ }
1398
+ }
1399
+ };
1400
+ /**
1401
+ * Whether a value is a {@link GraphQLReactorClient}, including one built by
1402
+ * another copy of this module.
1403
+ *
1404
+ * Use this rather than `instanceof`: the brand it tests for is shared by every
1405
+ * copy of the class, so a client built by a hot-replaced module or by a package
1406
+ * that bundled its own copy is still recognised.
1407
+ */
1408
+ function isGraphQLReactorClient(client) {
1409
+ return client?.[graphQLReactorClientBrand] === true;
1410
+ }
1411
+ /** The schema's change types, mapped onto the reactor's. */
1412
+ const documentChangeTypes = {
1413
+ [DocumentChangeType.Created]: DOCUMENT_CHANGE_TYPE.Created,
1414
+ [DocumentChangeType.Deleted]: DOCUMENT_CHANGE_TYPE.Deleted,
1415
+ [DocumentChangeType.Updated]: DOCUMENT_CHANGE_TYPE.Updated,
1416
+ [DocumentChangeType.ParentAdded]: DOCUMENT_CHANGE_TYPE.ParentAdded,
1417
+ [DocumentChangeType.ParentRemoved]: DOCUMENT_CHANGE_TYPE.ParentRemoved,
1418
+ [DocumentChangeType.ChildAdded]: DOCUMENT_CHANGE_TYPE.ChildAdded,
1419
+ [DocumentChangeType.ChildRemoved]: DOCUMENT_CHANGE_TYPE.ChildRemoved
1420
+ };
1421
+ /**
1422
+ * Decides whether an event reaches a subscriber.
1423
+ *
1424
+ * Every populated field of the search filter is an AND condition, matching the
1425
+ * reactor's own subscription manager - which also treats an empty array as a
1426
+ * filter that nothing satisfies. `parentId` is a drive concept and is ignored.
1427
+ *
1428
+ * A `Deleted` event carries no documents, so it is matched on its
1429
+ * `context.childId` for identifier filters and delivered unconditionally to
1430
+ * type and slug filters: there is no document left to check them against.
1431
+ */
1432
+ function eventMatchesSearch(event, search) {
1433
+ const deleted = event.type === DOCUMENT_CHANGE_TYPE.Deleted;
1434
+ const { ids, slugs, type } = search;
1435
+ if (ids) {
1436
+ if (!(deleted ? [event.context?.childId] : event.documents.map((document) => document.header.id)).some((id) => id !== void 0 && ids.includes(id))) return false;
1437
+ }
1438
+ if (slugs && !deleted) {
1439
+ if (!event.documents.map((document) => document.header.slug).some((slug) => slugs.includes(slug))) return false;
1440
+ }
1441
+ if (type && !deleted) {
1442
+ if (!event.documents.map((document) => document.header.documentType).includes(type)) return false;
1443
+ }
1444
+ return true;
1445
+ }
1446
+ /**
1447
+ * Maps a reactor `ViewFilter` onto the GraphQL `ViewFilterInput`.
1448
+ *
1449
+ * Point-in-time reads are rejected: the Switchboard read API has no revision
1450
+ * argument, so silently returning the head state would be wrong.
1451
+ */
1452
+ function viewFilterInputFromViewFilter(view) {
1453
+ if (!view) return;
1454
+ if (view.revision !== void 0) throw new Error("point-in-time views are not supported by GraphQLReactorClient");
1455
+ if (view.branch === void 0 && view.scopes === void 0) return;
1456
+ return {
1457
+ branch: view.branch,
1458
+ scopes: view.scopes
1459
+ };
1460
+ }
1461
+ function pagingInputFromPaging(paging) {
1462
+ if (!paging) return;
1463
+ return {
1464
+ cursor: paging.cursor,
1465
+ limit: paging.limit
1466
+ };
1467
+ }
1468
+ /**
1469
+ * The reactor and the GraphQL schema disagree on the enum: the reactor's
1470
+ * `None` is the schema's `ORPHAN`. This is the inverse of the server's
1471
+ * `toReactorPropagationMode`.
1472
+ */
1473
+ const propagationModeInputs = {
1474
+ cascade: PropagationMode.Cascade,
1475
+ none: PropagationMode.Orphan
1476
+ };
1477
+ function propagationModeInput(propagate) {
1478
+ return propagate === void 0 ? void 0 : propagationModeInputs[propagate];
1479
+ }
1480
+ /**
1481
+ * Stamps and signs the actions about to be pushed.
1482
+ *
1483
+ * Signing needs the state the action applies to, so only a single action can be
1484
+ * signed per call: the second action of a batch applies to a state this client
1485
+ * cannot compute without running the reducer. Batches are pushed unsigned.
1486
+ */
1487
+ async function prepareActionsForPush(actions, document) {
1488
+ const signer = resolveAmbientSigner();
1489
+ if (!signer || actions.length === 0) return actions;
1490
+ if (actions.length > 1) {
1491
+ logger.warn("GraphQLReactorClient: pushing a multi-action batch unsigned, only single actions can be signed");
1492
+ return actions;
1493
+ }
1494
+ return [await signStampedAction(stampAction(actions[0], document), signer)];
1495
+ }
1496
+ /** Resolves the signer of the logged-in user, if there is one. */
1497
+ function resolveAmbientSigner() {
1498
+ if (typeof window === "undefined") return;
1499
+ const renown = window.ph?.renown;
1500
+ return renown?.user ? renown.signer : void 0;
1501
+ }
1502
+ /**
1503
+ * The revision the pushed operations start from: the lowest head revision
1504
+ * across the scopes the actions target.
1505
+ *
1506
+ * The baseline is only meaningful together with {@link scopesForActions}: a
1507
+ * batch that touches a scope at revision 1 and one at revision 5000 would
1508
+ * otherwise re-download the whole history of every scope of the document.
1509
+ */
1510
+ function sinceRevisionForActions(document, actions) {
1511
+ const revisions = actions.map((action) => document.header.revision[action.scope] ?? 0);
1512
+ return revisions.length > 0 ? Math.min(...revisions) : 0;
1513
+ }
1514
+ /** The distinct scopes the pushed actions target, in first-seen order. */
1515
+ function scopesForActions(actions) {
1516
+ if (actions.length === 0) return;
1517
+ return [...new Set(actions.map((action) => action.scope))];
1518
+ }
1519
+ //#endregion
1520
+ //#region src/hooks/config/editor.ts
1521
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
1522
+ /** Sets whether external controls are enabled for a given editor. */
1523
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
1524
+ /** Gets whether external controls are enabled for a given editor. */
1525
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
1526
+ /** Adds an event handler for when the external controls enabled state changes. */
1527
+ const addIsExternalControlsEnabledEventHandler = isExternalControlsEnabledEventFunctions.addEventHandler;
1528
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
1529
+ /** Sets whether drag and drop is enabled for a given app. */
1530
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
1531
+ /** Gets whether drag and drop is enabled for a given app. */
1532
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
1533
+ /** Adds an event handler for when the drag and drop enabled state changes. */
1534
+ const addIsDragAndDropEnabledEventHandler = isDragAndDropEnabledEventFunctions.addEventHandler;
1535
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
1536
+ /** Sets the allowed document types for a given app. */
1537
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
1538
+ /** Defines the document types a drive supports.
1539
+ *
1540
+ * Defaults to all of the document types registered in the reactor.
1541
+ */
1542
+ function useAllowedDocumentTypes() {
1543
+ return allowedDocumentTypesEventFunctions.useValue();
1544
+ }
1545
+ /** Adds an event handler for when the allowed document types for a given app changes. */
1546
+ const addAllowedDocumentTypesEventHandler = allowedDocumentTypesEventFunctions.addEventHandler;
1547
+ const phAppConfigSetters = {
1548
+ allowedDocumentTypes: setAllowedDocumentTypes,
1549
+ isDragAndDropEnabled: setIsDragAndDropEnabled
1550
+ };
1551
+ const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
1552
+ const phAppConfigHooks = {
1553
+ allowedDocumentTypes: useAllowedDocumentTypes,
1554
+ isDragAndDropEnabled: useIsDragAndDropEnabled
1555
+ };
1556
+ const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
1557
+ //#endregion
1558
+ //#region src/hooks/config/connect.ts
1559
+ const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
1560
+ const { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions("version");
1561
+ const { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions("requiresHardRefresh");
1562
+ const { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions("warnOutdatedApp");
1563
+ const { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions("studioMode");
1564
+ const { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions("basePath");
1565
+ const { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions("versionCheckInterval");
1566
+ const { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions("cliVersion");
1567
+ const { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions("fileUploadOperationsChunkSize");
1568
+ const { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions("isDocumentModelSelectionSettingsEnabled");
1569
+ const { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions("gaTrackingId");
1570
+ const { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions("defaultDrivesUrl");
1571
+ const { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions("drivesPreserveStrategy");
1572
+ const { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
1573
+ const { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions("isAddDriveEnabled");
1574
+ const { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions("isPublicDrivesEnabled");
1575
+ const { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions("isAddPublicDrivesEnabled");
1576
+ const { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions("isDeletePublicDrivesEnabled");
1577
+ const { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions("isCloudDrivesEnabled");
1578
+ const { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions("isAddCloudDrivesEnabled");
1579
+ const { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteCloudDrivesEnabled");
1580
+ const { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
1581
+ const { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions("isAddLocalDrivesEnabled");
1582
+ const { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteLocalDrivesEnabled");
1583
+ const { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions("isEditorDebugModeEnabled");
1584
+ const { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions("isEditorReadModeEnabled");
1585
+ const { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled");
1586
+ const { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions("isDiffAnalyticsEnabled");
1587
+ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions("isDriveAnalyticsEnabled");
1588
+ const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
1589
+ const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
1590
+ const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
1591
+ const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
1592
+ const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
1593
+ const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
1594
+ const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
1595
+ const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
1596
+ const { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions("isSentryTracingEnabled");
1597
+ const { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions("isExternalProcessorsEnabled");
1598
+ const { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions("isExternalPackagesEnabled");
1599
+ const enabledEditorsEventFunctions = makePHEventFunctions("enabledEditors");
1600
+ /** Sets the enabled editors for Connect. */
1601
+ const setEnabledEditors = enabledEditorsEventFunctions.setValue;
1602
+ /** Gets the enabled editors for Connect. */
1603
+ const useEnabledEditors = enabledEditorsEventFunctions.useValue;
1604
+ /** Adds an event handler for when the enabled editors for Connect changes. */
1605
+ const addEnabledEditorsEventHandler = enabledEditorsEventFunctions.addEventHandler;
1606
+ const disabledEditorsEventFunctions = makePHEventFunctions("disabledEditors");
1607
+ /** Sets the disabled editors for Connect. */
1608
+ const setDisabledEditors = disabledEditorsEventFunctions.setValue;
1609
+ /** Gets the disabled editors for Connect. */
1610
+ const useDisabledEditors = disabledEditorsEventFunctions.useValue;
1611
+ /** Adds an event handler for when the disabled editors for Connect changes. */
1612
+ const addDisabledEditorsEventHandler = disabledEditorsEventFunctions.addEventHandler;
1613
+ const isRelationalProcessorsEnabled = makePHEventFunctions("isRelationalProcessorsEnabled");
1614
+ /** Sets the isRelationalProcessorsEnabled for Connect. */
1615
+ const setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;
1616
+ /** Gets the isRelationalProcessorsEnabled for Connect. */
1617
+ const useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;
1618
+ /** Adds an event handler for when the isRelationalProcessorsEnabled for Connect changes. */
1619
+ const addIsRelationalProcessorsEnabledEventHandler = isRelationalProcessorsEnabled.addEventHandler;
1620
+ const isExternalRelationalProcessorsEnabled = makePHEventFunctions("isExternalRelationalProcessorsEnabled");
1621
+ /** Sets the isExternalRelationalProcessorsEnabled for Connect. */
1622
+ const setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;
1623
+ /** Gets the isExternalRelationalProcessorsEnabled for Connect. */
1624
+ const useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;
1625
+ /** Adds an event handler for when the isExternalRelationalProcessorsEnabled for Connect changes. */
1626
+ const addIsExternalRelationalProcessorsEnabledEventHandler = isExternalRelationalProcessorsEnabled.addEventHandler;
1627
+ const isAnalyticsEnabledEventFunctions = makePHEventFunctions("isAnalyticsEnabled");
1628
+ /** Sets the isAnalyticsEnabled for Connect. */
1629
+ const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;
1630
+ /** Gets the isAnalyticsEnabled for Connect. */
1631
+ const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;
1632
+ /** Adds an event handler for when the isAnalyticsEnabled for Connect changes. */
1633
+ const addIsAnalyticsEnabledEventHandler = isAnalyticsEnabledEventFunctions.addEventHandler;
1634
+ const isAnalyticsExternalProcessorsEnabled = makePHEventFunctions("isAnalyticsExternalProcessorsEnabled");
1635
+ /** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */
1636
+ const setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;
1637
+ /** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */
1638
+ const useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;
1639
+ /** Adds an event handler for when the isAnalyticsExternalProcessorsEnabled for Connect changes. */
1640
+ const addIsAnalyticsExternalProcessorsEnabledEventHandler = isAnalyticsExternalProcessorsEnabled.addEventHandler;
1641
+ const analyticsDatabaseNameEventFunctions = makePHEventFunctions("analyticsDatabaseName");
1642
+ /** Sets the analytics database name for Connect. */
1643
+ const setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;
1644
+ /** Gets the analytics database name for Connect. */
1645
+ const useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;
1646
+ /** Adds an event handler for when the analytics database name for Connect changes. */
1647
+ const addAnalyticsDatabaseNameEventHandler = analyticsDatabaseNameEventFunctions.addEventHandler;
1648
+ const logLevelEventFunctions = makePHEventFunctions("logLevel");
1649
+ /** Sets the log level for Connect. */
1650
+ const setLogLevel = logLevelEventFunctions.setValue;
1651
+ /** Gets the log level for Connect. */
1652
+ const useLogLevel = logLevelEventFunctions.useValue;
1653
+ /** Adds an event handler for when the log level for Connect changes. */
1654
+ const addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;
1655
+ const allowListEventFunctions = makePHEventFunctions("allowList");
1656
+ /** Sets the allow list for Connect. */
1657
+ const setAllowList = allowListEventFunctions.setValue;
1658
+ /** Gets the allow list for Connect. */
1659
+ const useAllowList = allowListEventFunctions.useValue;
1660
+ /** Adds an event handler for when the allow list for Connect changes. */
1661
+ const addAllowListEventHandler = allowListEventFunctions.addEventHandler;
1662
+ const nonUserConfigSetters = {
1663
+ routerBasename: setRouterBasename,
1664
+ version: setVersion,
1665
+ requiresHardRefresh: setRequiresHardRefresh,
1666
+ warnOutdatedApp: setWarnOutdatedApp,
1667
+ studioMode: setStudioMode,
1668
+ basePath: setBasePath,
1669
+ versionCheckInterval: setVersionCheckInterval,
1670
+ cliVersion: setCliVersion,
1671
+ fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,
1672
+ isDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,
1673
+ gaTrackingId: setGaTrackingId,
1674
+ defaultDrivesUrl: setDefaultDrivesUrl,
1675
+ drivesPreserveStrategy: setDrivesPreserveStrategy,
1676
+ isLocalDrivesEnabled: setIsLocalDrivesEnabled,
1677
+ isAddDriveEnabled: setIsAddDriveEnabled,
1678
+ isPublicDrivesEnabled: setIsPublicDrivesEnabled,
1679
+ isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,
1680
+ isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,
1681
+ isCloudDrivesEnabled: setIsCloudDrivesEnabled,
1682
+ isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,
1683
+ isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,
1684
+ isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,
1685
+ isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,
1686
+ isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,
1687
+ isEditorReadModeEnabled: setIsEditorReadModeEnabled,
1688
+ isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,
1689
+ isExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,
1690
+ isAnalyticsEnabled: setIsAnalyticsEnabled,
1691
+ analyticsDatabaseName: setAnalyticsDatabaseName,
1692
+ isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,
1693
+ isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,
1694
+ isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,
1695
+ isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,
1696
+ renownUrl: setRenownUrl,
1697
+ renownNetworkId: setRenownNetworkId,
1698
+ renownChainId: setRenownChainId,
1699
+ switchboardUrl: setSwitchboardUrl,
1700
+ renownAdapters: setRenownAdapters,
1701
+ sentryRelease: setSentryRelease,
1702
+ sentryDsn: setSentryDsn,
1703
+ sentryEnv: setSentryEnv,
1704
+ isSentryTracingEnabled: setIsSentryTracingEnabled,
1705
+ isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,
1706
+ isExternalPackagesEnabled: setIsExternalPackagesEnabled,
1707
+ allowList: setAllowList,
1708
+ logLevel: setLogLevel,
1709
+ disabledEditors: setDisabledEditors,
1710
+ enabledEditors: setEnabledEditors
1711
+ };
1712
+ const phGlobalConfigSetters = {
1713
+ ...phAppConfigSetters,
1714
+ ...phDocumentEditorConfigSetters,
1715
+ ...nonUserConfigSetters
1716
+ };
1717
+ const nonUserConfigHooks = {
1718
+ routerBasename: useRouterBasename,
1719
+ version: useVersion,
1720
+ requiresHardRefresh: useRequiresHardRefresh,
1721
+ warnOutdatedApp: useWarnOutdatedApp,
1722
+ studioMode: useStudioMode,
1723
+ basePath: useBasePath,
1724
+ versionCheckInterval: useVersionCheckInterval,
1725
+ cliVersion: useCliVersion,
1726
+ fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,
1727
+ isDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,
1728
+ gaTrackingId: useGaTrackingId,
1729
+ defaultDrivesUrl: useDefaultDrivesUrl,
1730
+ drivesPreserveStrategy: useDrivesPreserveStrategy,
1731
+ isAddDriveEnabled: useIsAddDriveEnabled,
1732
+ isPublicDrivesEnabled: useIsPublicDrivesEnabled,
1733
+ isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,
1734
+ isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,
1735
+ isCloudDrivesEnabled: useIsCloudDrivesEnabled,
1736
+ isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,
1737
+ isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,
1738
+ isLocalDrivesEnabled: useIsLocalDrivesEnabled,
1739
+ isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,
1740
+ isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,
1741
+ isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,
1742
+ isEditorReadModeEnabled: useIsEditorReadModeEnabled,
1743
+ isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,
1744
+ isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,
1745
+ isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,
1746
+ renownUrl: useRenownUrl,
1747
+ renownNetworkId: useRenownNetworkId,
1748
+ renownChainId: useRenownChainId,
1749
+ switchboardUrl: useSwitchboardUrl,
1750
+ renownAdapters: useRenownAdapters,
1751
+ sentryRelease: useSentryRelease,
1752
+ sentryDsn: useSentryDsn,
1753
+ sentryEnv: useSentryEnv,
1754
+ isSentryTracingEnabled: useIsSentryTracingEnabled,
1755
+ isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,
1756
+ isExternalPackagesEnabled: useIsExternalPackagesEnabled,
1757
+ allowList: useAllowList,
1758
+ isAnalyticsEnabled: useIsAnalyticsEnabled,
1759
+ isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,
1760
+ isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,
1761
+ isExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,
1762
+ analyticsDatabaseName: useAnalyticsDatabaseName,
1763
+ logLevel: useLogLevel,
1764
+ disabledEditors: useDisabledEditors,
1765
+ enabledEditors: useEnabledEditors
1766
+ };
1767
+ const phGlobalConfigHooks = {
1768
+ ...phAppConfigHooks,
1769
+ ...phDocumentEditorConfigHooks,
1770
+ ...nonUserConfigHooks
1771
+ };
1772
+ //#endregion
1773
+ //#region src/hooks/attachment-service.ts
1774
+ const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
1775
+ /** Returns the attachment service from window.ph */
1776
+ const useAttachmentService = attachmentServiceEventFunctions.useValue;
1777
+ /** Sets the attachment service on window.ph */
1778
+ const setAttachmentService = attachmentServiceEventFunctions.setValue;
1779
+ /** Registers the attachmentService window event handler */
1780
+ const addAttachmentServiceEventHandler = attachmentServiceEventFunctions.addEventHandler;
1781
+ //#endregion
1782
+ //#region src/hooks/features.ts
1783
+ const featuresEventFunctions = makePHEventFunctions("features");
1784
+ const useFeatures = featuresEventFunctions.useValue;
1785
+ const setFeatures = featuresEventFunctions.setValue;
1786
+ const addFeaturesEventHandler = featuresEventFunctions.addEventHandler;
1787
+ //#endregion
1788
+ //#region src/utils/url.ts
1789
+ function resolveUrlPathname(path) {
1790
+ return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
1791
+ }
1792
+ /** Returns the current path without the base path */
1793
+ function getPathWithoutBase(path) {
1794
+ const basePath = window.ph?.basePath ?? "/";
1795
+ return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
1796
+ }
1797
+ /** Makes a URL component for a drive. */
1798
+ function makeDriveUrlComponent(drive) {
1799
+ if (!drive) return "";
1800
+ return `/d/${slug(drive.header.slug)}`;
1801
+ }
1802
+ /** Makes a URL component for a node. */
1803
+ function makeNodeSlug(node) {
1804
+ if (!node) return "";
1805
+ const nodeName = node.name;
1806
+ if (!nodeName) return slug(node.id);
1807
+ return slug(`${nodeName}-${node.id}`);
1808
+ }
1809
+ /** Extracts the node slug from a path.
1810
+ *
1811
+ * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
1812
+ */
1813
+ function extractNodeSlugFromPath(path) {
1814
+ const currentPath = getPathWithoutBase(path);
1815
+ return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
1816
+ }
1817
+ /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
1818
+ function findUuid(input) {
1819
+ if (!input) return void 0;
1820
+ return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
1821
+ }
1822
+ function extractNodeIdFromSlug(nodeSlug) {
1823
+ return findUuid(nodeSlug);
1824
+ }
1825
+ function extractNodeIdFromPath(path) {
1826
+ return extractNodeIdFromSlug(extractNodeSlugFromPath(path));
1827
+ }
1828
+ /** Extracts the drive slug from a path.
1829
+ * Used for extracting drive ids from drive slugs in the URL.
1830
+ * Expects the path to be in the format `/d/<drive-slug>`.
1831
+ */
1832
+ function extractDriveSlugFromPath(path) {
1833
+ const currentPath = getPathWithoutBase(path);
1834
+ return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
1835
+ }
1836
+ function extractDriveIdFromSlug(driveSlug) {
1837
+ return findUuid(driveSlug);
1838
+ }
1839
+ function extractDriveIdFromPath(path) {
1840
+ return extractDriveIdFromSlug(extractDriveSlugFromPath(path));
1841
+ }
1842
+ /**
1843
+ * Creates a URL string with the given pathname while preserving existing query parameters.
1844
+ */
1845
+ function createUrlWithPreservedParams(pathname) {
1846
+ const search = window.location.search;
1847
+ return search ? `${pathname}${search}` : pathname;
1848
+ }
1849
+ //#endregion
1850
+ //#region src/hooks/drives.ts
1851
+ const drivesEventFunctions = makePHEventFunctions("drives");
1852
+ /** Returns all of the drives in the reactor */
1853
+ const useDrives = drivesEventFunctions.useValue;
1854
+ /** Sets the drives in the reactor */
1855
+ const setDrives = drivesEventFunctions.setValue;
1856
+ /** Adds an event handler for the drives */
1857
+ const addDrivesEventHandler = drivesEventFunctions.addEventHandler;
1858
+ //#endregion
1859
+ //#region src/hooks/set-selected-node.ts
1860
+ const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
1861
+ const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
1862
+ const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
1863
+ const addSelectedNodeIdEventHandler = selectedNodeIdEventFunctions.addEventHandler;
1864
+ /** Sets the selected node (file or folder). */
1865
+ function setSelectedNode(nodeOrNodeSlug) {
1866
+ const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
1867
+ setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
1868
+ const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
1869
+ if (!driveSlugFromPath) return;
1870
+ if (!nodeSlug) {
1871
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
1872
+ if (pathname === window.location.pathname) return;
1873
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1874
+ return;
1875
+ }
1876
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
1877
+ if (pathname === window.location.pathname) return;
1878
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1879
+ }
1880
+ function addResetSelectedNodeEventHandler() {
1881
+ window.addEventListener("ph:selectedDriveIdUpdated", () => {
1882
+ setSelectedNodeId(void 0);
1883
+ });
1884
+ }
1885
+ function addSetSelectedNodeOnPopStateEventHandler() {
1886
+ window.addEventListener("popstate", () => {
1887
+ const pathname = window.location.pathname;
1888
+ const nodeSlug = extractNodeSlugFromPath(pathname);
1889
+ if (extractNodeIdFromSlug(nodeSlug) !== window.ph?.selectedNodeId) setSelectedNode(nodeSlug);
1890
+ });
1891
+ }
1892
+ //#endregion
1893
+ //#region src/hooks/selected-drive.ts
1894
+ const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
1895
+ /** Returns the selected drive id */
1896
+ const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
1897
+ /** Sets the selected drive id */
1898
+ const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
1899
+ /** Adds an event handler for the selected drive id */
1900
+ const addSelectedDriveIdEventHandler = selectedDriveIdEventFunctions.addEventHandler;
1901
+ /** Returns the selected drive */
1902
+ function useSelectedDrive() {
1903
+ const drive = useSelectedDriveSafe();
1904
+ if (!drive[0]) throw new Error("There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?");
1905
+ return drive;
1906
+ }
1907
+ /** Returns the selected drive, or undefined if no drive is selected */
1908
+ function useSelectedDriveSafe() {
1909
+ const selectedDriveId = useSelectedDriveId();
1910
+ const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
1911
+ const [drive, dispatch] = useDispatch(selectedDrive);
1912
+ if (!selectedDrive) return [void 0, void 0];
1913
+ return [drive, dispatch];
1914
+ }
1915
+ function setSelectedDrive(driveOrDriveSlug) {
1916
+ const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
1917
+ const drives = window.ph?.drives;
1918
+ const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
1919
+ if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
1920
+ if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
1921
+ deferDriveSelection(driveSlug);
1922
+ return;
1923
+ }
1924
+ cancelPendingDriveSelection();
1925
+ setSelectedDriveId(driveId);
1926
+ if (!driveId) {
1927
+ const pathname = resolveUrlPathname("/");
1928
+ if (pathname === window.location.pathname) return;
1929
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1930
+ return;
1931
+ }
1932
+ const pathname = resolveUrlPathname(`/d/${driveSlug}`);
1933
+ if (pathname === window.location.pathname) return;
1934
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1935
+ }
1936
+ const DEFERRED_DRIVE_TICK_MS = 2e3;
1937
+ const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
1938
+ function isInitialSyncInFlight() {
1939
+ const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
1940
+ if (!remotes?.length) return false;
1941
+ return remotes.some((remote) => {
1942
+ try {
1943
+ const snapshot = remote.channel.getConnectionState();
1944
+ return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
1945
+ } catch {
1946
+ return false;
1947
+ }
1948
+ });
1949
+ }
1950
+ let pendingHandler;
1951
+ let pendingTimeout;
1952
+ function cancelPendingDriveSelection() {
1953
+ if (pendingHandler) {
1954
+ window.removeEventListener("ph:drivesUpdated", pendingHandler);
1955
+ pendingHandler = void 0;
1956
+ }
1957
+ if (pendingTimeout) {
1958
+ clearTimeout(pendingTimeout);
1959
+ pendingTimeout = void 0;
1960
+ }
1961
+ }
1962
+ function deferDriveSelection(driveSlug) {
1963
+ cancelPendingDriveSelection();
1964
+ const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
1965
+ const handler = () => {
1966
+ if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
1967
+ cancelPendingDriveSelection();
1968
+ setSelectedDrive(driveSlug);
1969
+ setSelectedNode(nodeSlug);
1970
+ };
1971
+ pendingHandler = handler;
1972
+ window.addEventListener("ph:drivesUpdated", handler);
1973
+ const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
1974
+ const scheduleTick = () => {
1975
+ pendingTimeout = setTimeout(() => {
1976
+ if (Date.now() < deadline && isInitialSyncInFlight()) {
1977
+ scheduleTick();
1978
+ return;
1979
+ }
1980
+ cancelPendingDriveSelection();
1981
+ const pathname = resolveUrlPathname("/");
1982
+ if (pathname === window.location.pathname) return;
1983
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1984
+ }, DEFERRED_DRIVE_TICK_MS);
1985
+ };
1986
+ scheduleTick();
1987
+ }
1988
+ function addSetSelectedDriveOnPopStateEventHandler() {
1989
+ window.addEventListener("popstate", () => {
1990
+ const pathname = window.location.pathname;
1991
+ const driveId = extractDriveIdFromPath(pathname);
1992
+ if (driveId !== window.ph?.selectedDriveId) setSelectedDrive(driveId);
1993
+ });
1994
+ }
1995
+ //#endregion
1996
+ //#region src/hooks/use-drop-target.ts
1997
+ function useDropTarget() {
1998
+ const [isDropTarget, setIsDropTarget] = useState(false);
1999
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
2000
+ const targetSetter = funnel(() => setIsDropTarget(true), {
2001
+ triggerAt: "start",
2002
+ minQuietPeriodMs: 100
2003
+ });
2004
+ const targetUnsetter = funnel(() => setIsDropTarget(false), {
2005
+ triggerAt: "start",
2006
+ minQuietPeriodMs: 100
2007
+ });
2008
+ function setTarget() {
2009
+ if (!isDragAndDropEnabled) return;
2010
+ targetUnsetter.cancel();
2011
+ targetSetter.call();
2012
+ }
2013
+ function unsetTarget() {
2014
+ if (!isDragAndDropEnabled) return;
2015
+ targetSetter.cancel();
2016
+ targetUnsetter.call();
2017
+ }
2018
+ return {
2019
+ isDropTarget,
2020
+ setTarget,
2021
+ unsetTarget
2022
+ };
2023
+ }
2024
+ //#endregion
2025
+ //#region src/hooks/node-drag-and-drop.ts
2026
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
2027
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
2028
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
2029
+ const addDraggingNodeEventHandler = draggingNodeEventFunctions.addEventHandler;
2030
+ const draggingNodeSetter = funnel((node) => setDraggingNode(node), {
2031
+ reducer: (_, newNode) => newNode,
2032
+ triggerAt: "start",
2033
+ minQuietPeriodMs: 100
2034
+ });
2035
+ const draggingNodeUnsetter = funnel(() => setDraggingNode(void 0), {
2036
+ triggerAt: "start",
2037
+ minQuietPeriodMs: 100
2038
+ });
2039
+ function setDragging(node) {
2040
+ draggingNodeUnsetter.cancel();
2041
+ draggingNodeSetter.call(node);
2042
+ }
2043
+ function unsetDragging() {
2044
+ draggingNodeSetter.cancel();
2045
+ draggingNodeUnsetter.call();
2046
+ }
2047
+ 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));
2048
+ function useDragNode(args) {
2049
+ const { srcId, parentId } = args;
2050
+ const driveId = useSelectedDriveId();
2051
+ const draggingNodeId = useDraggingNode()?.srcId;
2052
+ const params = {
2053
+ driveId,
2054
+ srcId,
2055
+ parentId
2056
+ };
2057
+ const draggable = isNodeDrag(params);
2058
+ const isDragging = allPass({
2059
+ srcId,
2060
+ draggingNodeId
2061
+ }, [
2062
+ () => draggable,
2063
+ ({ srcId }) => isString(srcId),
2064
+ ({ draggingNodeId }) => isString(draggingNodeId),
2065
+ ({ srcId, draggingNodeId }) => isStrictEqual(srcId, draggingNodeId)
2066
+ ]);
2067
+ const onDragStart = () => {
2068
+ if (!draggable) return;
2069
+ setDragging(params);
2070
+ };
2071
+ const onDragEnd = () => {
2072
+ if (!draggable) return;
2073
+ unsetDragging();
2074
+ };
2075
+ return {
2076
+ isDragging,
2077
+ draggable,
2078
+ onDragStart,
2079
+ onDragEnd
2080
+ };
2081
+ }
2082
+ 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));
2083
+ function useDropNode(targetId) {
2084
+ const driveId = useSelectedDriveId();
2085
+ const { srcId, parentId } = useDraggingNode() ?? {};
2086
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
2087
+ const params = {
2088
+ driveId,
2089
+ parentId,
2090
+ targetId,
2091
+ srcId
2092
+ };
2093
+ function handleNodeDrop(event, cb) {
2094
+ if (!isNodeDrop(params)) return;
2095
+ event.preventDefault();
2096
+ event.stopPropagation();
2097
+ cb?.();
2098
+ }
2099
+ const onDragEnter = (event) => handleNodeDrop(event);
2100
+ const onDragOver = (event) => handleNodeDrop(event, once(setTarget));
2101
+ const onDragLeave = (event) => handleNodeDrop(event, once(unsetTarget));
2102
+ const onDrop = (event) => handleNodeDrop(event, once(() => {
2103
+ unsetDragging();
2104
+ unsetTarget();
2105
+ moveNodeById(params).catch(console.error);
2106
+ }));
2107
+ return {
2108
+ isDropTarget,
2109
+ onDragEnter,
2110
+ onDragOver,
2111
+ onDragLeave,
2112
+ onDrop
2113
+ };
2114
+ }
2115
+ //#endregion
2116
+ //#region src/hooks/graphql-reactor-client.ts
2117
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
2118
+ const useGraphQLReactorClient = graphQLReactorClientEventFunctions.useValue;
2119
+ const setGraphQLReactorClient = graphQLReactorClientEventFunctions.setValue;
2120
+ const addGraphQLReactorClientEventHandler = graphQLReactorClientEventFunctions.addEventHandler;
2121
+ //#endregion
2122
+ //#region src/hooks/package-discovery.ts
2123
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
2124
+ const usePackageDiscoveryService = packageDiscoveryFunctions.useValue;
2125
+ const setPackageDiscoveryService = packageDiscoveryFunctions.setValue;
2126
+ const addPackageDiscoveryServiceEventHandler = packageDiscoveryFunctions.addEventHandler;
2127
+ //#endregion
2128
+ //#region src/hooks/reactor.ts
2129
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
2130
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
2131
+ /** Returns the reactor client module (in-process or worker-backed) */
2132
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
2133
+ /** Sets the reactor client module */
2134
+ const setReactorClientModule = reactorClientModuleEventFunctions.setValue;
2135
+ /** Adds an event handler for the reactor client module */
2136
+ const addReactorClientModuleEventHandler = reactorClientModuleEventFunctions.addEventHandler;
2137
+ /** Returns the reactor client */
2138
+ const useReactorClient = reactorClientEventFunctions.useValue;
2139
+ /** Sets the reactor client */
2140
+ const setReactorClient = reactorClientEventFunctions.setValue;
2141
+ /** Adds an event handler for the reactor client */
2142
+ const addReactorClientEventHandler = reactorClientEventFunctions.addEventHandler;
2143
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
2144
+ const useSyncList = () => {
2145
+ return useSync()?.list() ?? [];
2146
+ };
2147
+ const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
2148
+ const useDatabase = () => {
2149
+ const module = useReactorClientModule();
2150
+ return module?.kind === "browser" ? module.reactorModule?.database : void 0;
2151
+ };
2152
+ const usePGlite = () => {
2153
+ const module = useReactorClientModule();
2154
+ return module?.kind === "browser" ? module.reactorModule?.pg : void 0;
2155
+ };
2156
+ //#endregion
2157
+ //#region src/hooks/revision-history.ts
2158
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
2159
+ /** Returns whether revision history is visible */
2160
+ const useRevisionHistoryVisible = revisionHistoryEventFunctions.useValue;
2161
+ /** Sets revision history visibility */
2162
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
2163
+ /** Adds event handler for revision history visibility */
2164
+ const addRevisionHistoryVisibleEventHandler = revisionHistoryEventFunctions.addEventHandler;
2165
+ /** Shows the revision history */
2166
+ function showRevisionHistory() {
2167
+ setRevisionHistoryVisible(true);
2168
+ }
2169
+ /** Hides the revision history */
2170
+ function hideRevisionHistory() {
2171
+ setRevisionHistoryVisible(false);
2172
+ }
2173
+ //#endregion
2174
+ //#region src/utils/nodes.ts
2175
+ /** Sorts nodes by name. */
2176
+ function sortNodesByName(nodes) {
2177
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
2178
+ }
2179
+ /** Returns whether a node is a file. */
2180
+ function isFileNodeKind(node) {
2181
+ if (!node) return false;
2182
+ return node.kind.toUpperCase() === "FILE";
2183
+ }
2184
+ /** Returns whether a node is a folder. */
2185
+ function isFolderNodeKind(node) {
2186
+ if (!node) return false;
2187
+ return node.kind.toUpperCase() === "FOLDER";
2188
+ }
2189
+ //#endregion
2190
+ //#region src/hooks/items-in-selected-drive.ts
2191
+ /** Returns the nodes in the selected drive. */
2192
+ function useNodesInSelectedDrive() {
2193
+ const [selectedDrive] = useSelectedDriveSafe();
2194
+ return selectedDrive?.state.global.nodes;
2195
+ }
2196
+ /** Returns the file nodes in the selected drive. */
2197
+ function useFileNodesInSelectedDrive() {
2198
+ return useNodesInSelectedDrive()?.filter((n) => isFileNodeKind(n));
2199
+ }
2200
+ /** Returns the folder nodes in the selected drive. */
2201
+ function useFolderNodesInSelectedDrive() {
2202
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
2203
+ }
2204
+ /** Returns the documents in the selected drive. */
2205
+ function useDocumentsInSelectedDrive() {
2206
+ const fileNodeIds = useFileNodesInSelectedDrive()?.map((node) => node.id);
2207
+ return useDocumentsByIds(fileNodeIds);
2208
+ }
2209
+ /** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */
2210
+ function useDocumentTypesInSelectedDrive() {
2211
+ return (useDocumentsInSelectedDrive()?.filter(isDocumentModelDocument))?.map((doc) => doc.state.global.id);
2212
+ }
2213
+ function isDocumentModelDocument(document) {
2214
+ return document.header.documentType === "powerhouse/document-model";
2215
+ }
2216
+ //#endregion
2217
+ //#region src/hooks/selected-node.ts
2218
+ /** Returns the selected node. */
2219
+ function useSelectedNode() {
2220
+ const selectedNodeId = useSelectedNodeId();
2221
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
2222
+ }
2223
+ //#endregion
2224
+ //#region src/hooks/selected-timeline-item.ts
2225
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
2226
+ /** Returns the selected timeline item */
2227
+ const useSelectedTimelineItem = selectedTimelineItemEventFunctions.useValue;
2228
+ /** Sets the selected timeline item */
2229
+ const setSelectedTimelineItem = selectedTimelineItemEventFunctions.setValue;
2230
+ /** Adds event handler for selected timeline item */
2231
+ const addSelectedTimelineItemEventHandler = selectedTimelineItemEventFunctions.addEventHandler;
2232
+ //#endregion
2233
+ //#region src/hooks/timeline-revision.ts
2234
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
2235
+ /** Returns the selected timeline revision. */
2236
+ const useSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.useValue;
2237
+ /** Sets the selected timeline revision. */
2238
+ const setSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.setValue;
2239
+ /** Adds an event handler for the selected timeline revision. */
2240
+ const addSelectedTimelineRevisionEventHandler = selectedTimelineRevisionEventFunctions.addEventHandler;
2241
+ //#endregion
2242
+ //#region src/hooks/toast.ts
2243
+ const toastEventFunctions = makePHEventFunctions("toast");
2244
+ /** Returns the toast function */
2245
+ const usePHToast = toastEventFunctions.useValue;
2246
+ /** Sets the toast function */
2247
+ const setPHToast = toastEventFunctions.setValue;
2248
+ /** Adds an event handler for the toast */
2249
+ const addToastEventHandler = toastEventFunctions.addEventHandler;
2250
+ //#endregion
2251
+ //#region src/hooks/vetra-packages.ts
2252
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
2253
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
2254
+ /** Returns all of the Vetra packages loaded by the Connect instance */
2255
+ const useVetraPackages = () => {
2256
+ const packageManager = useVetraPackageManager();
2257
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
2258
+ };
2259
+ /** Adds the Vetra package manager event handler */
2260
+ const addVetraPackageManagerEventHandler = vetraPackageManagerFunctions.addEventHandler;
2261
+ /** Sets the Vetra package manager and registers its packages */
2262
+ function setVetraPackageManager(packageManager) {
2263
+ vetraPackageManagerFunctions.setValue(packageManager);
2264
+ updateReactorClientDocumentModels(packageManager.packages);
2265
+ updateReactorClientUpgradeManifests(packageManager.packages);
2266
+ packageManager.subscribe(({ packages }) => {
2267
+ updateReactorClientDocumentModels(packages);
2268
+ updateReactorClientUpgradeManifests(packages);
2269
+ });
2270
+ }
2271
+ function updateReactorClientDocumentModels(packages) {
2272
+ const documentModelModules = packages.flatMap((pkg) => pkg.documentModels);
2273
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2274
+ if (!registry || documentModelModules.length === 0) return;
2275
+ const results = registry.registerModules(...documentModelModules);
2276
+ const duplicates = [];
2277
+ for (const result of results) if (result.status === "error") if (isDuplicateModuleError(result.error)) duplicates.push(result);
2278
+ else console.error("Failed to register document model module:", result.error);
2279
+ if (duplicates.length > 0) {
2280
+ const duplicateTypes = duplicates.map((r) => r.item.documentModel.global.id);
2281
+ registry.unregisterModules(...duplicateTypes);
2282
+ registry.registerModules(...duplicates.map((r) => r.item));
2283
+ }
2284
+ }
2285
+ function updateReactorClientUpgradeManifests(packages) {
2286
+ const upgradeManifests = packages.flatMap((pkg) => pkg.upgradeManifests).filter((u) => u !== void 0);
2287
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2288
+ if (!registry || upgradeManifests.length === 0) return;
2289
+ const results = registry.registerUpgradeManifests(...upgradeManifests);
2290
+ const duplicates = [];
2291
+ for (const result of results) if (result.status === "error") if (isDuplicateManifestError(result.error)) duplicates.push(result);
2292
+ else console.error("Failed to register upgrade manifest:", result.error);
2293
+ if (duplicates.length > 0) {
2294
+ const duplicateTypes = duplicates.map((r) => r.item.documentType).filter((t) => !!t);
2295
+ registry.unregisterUpgradeManifests(...duplicateTypes);
2296
+ registry.registerUpgradeManifests(...duplicates.map((r) => r.item));
2297
+ }
2298
+ }
2299
+ //#endregion
2300
+ //#region src/hooks/add-ph-event-handlers.ts
2301
+ const commonGlobalEventHandlerFunctions = {
2302
+ loading: addLoadingEventHandler,
2303
+ drives: addDrivesEventHandler,
2304
+ selectedDriveId: () => {
2305
+ addSelectedDriveIdEventHandler();
2306
+ addSetSelectedDriveOnPopStateEventHandler();
2307
+ addResetSelectedNodeEventHandler();
2308
+ },
2309
+ selectedNodeId: () => {
2310
+ addSelectedNodeIdEventHandler();
2311
+ addSetSelectedNodeOnPopStateEventHandler();
2312
+ },
2313
+ documentCache: addDocumentCacheEventHandler,
2314
+ reactorGraphQLClient: addGraphQLReactorClientEventHandler,
2315
+ draggingNode: addDraggingNodeEventHandler
2316
+ };
2317
+ const phGlobalEventHandlerRegisterFunctions = {
2318
+ ...commonGlobalEventHandlerFunctions,
2319
+ reactorClientModule: addReactorClientModuleEventHandler,
2320
+ reactorClient: addReactorClientEventHandler,
2321
+ attachmentService: addAttachmentServiceEventHandler,
2322
+ features: addFeaturesEventHandler,
2323
+ modal: addModalEventHandler,
2324
+ renown: addRenownEventHandler,
2325
+ vetraPackageManager: addVetraPackageManagerEventHandler,
2326
+ packageDiscoveryService: addPackageDiscoveryServiceEventHandler,
2327
+ selectedTimelineRevision: addSelectedTimelineRevisionEventHandler,
2328
+ revisionHistoryVisible: addRevisionHistoryVisibleEventHandler,
2329
+ selectedTimelineItem: addSelectedTimelineItemEventHandler,
2330
+ routerBasename: addRouterBasenameEventHandler,
2331
+ version: addVersionEventHandler,
2332
+ logLevel: addLogLevelEventHandler,
2333
+ requiresHardRefresh: addRequiresHardRefreshEventHandler,
2334
+ warnOutdatedApp: addWarnOutdatedAppEventHandler,
2335
+ studioMode: addStudioModeEventHandler,
2336
+ basePath: addBasePathEventHandler,
2337
+ versionCheckInterval: addVersionCheckIntervalEventHandler,
2338
+ cliVersion: addCliVersionEventHandler,
2339
+ fileUploadOperationsChunkSize: addFileUploadOperationsChunkSizeEventHandler,
2340
+ isDocumentModelSelectionSettingsEnabled: addIsDocumentModelSelectionSettingsEnabledEventHandler,
2341
+ gaTrackingId: addGaTrackingIdEventHandler,
2342
+ allowList: addAllowListEventHandler,
2343
+ defaultDrivesUrl: addDefaultDrivesUrlEventHandler,
2344
+ drivesPreserveStrategy: addDrivesPreserveStrategyEventHandler,
2345
+ allowedDocumentTypes: addAllowedDocumentTypesEventHandler,
2346
+ enabledEditors: addEnabledEditorsEventHandler,
2347
+ disabledEditors: addDisabledEditorsEventHandler,
2348
+ isAddDriveEnabled: addIsAddDriveEnabledEventHandler,
2349
+ isLocalDrivesEnabled: addIsLocalDrivesEnabledEventHandler,
2350
+ isPublicDrivesEnabled: addIsPublicDrivesEnabledEventHandler,
2351
+ isAddPublicDrivesEnabled: addIsAddPublicDrivesEnabledEventHandler,
2352
+ isDeletePublicDrivesEnabled: addIsDeletePublicDrivesEnabledEventHandler,
2353
+ isCloudDrivesEnabled: addIsCloudDrivesEnabledEventHandler,
2354
+ isAddCloudDrivesEnabled: addIsAddCloudDrivesEnabledEventHandler,
2355
+ isDeleteCloudDrivesEnabled: addIsDeleteCloudDrivesEnabledEventHandler,
2356
+ isAddLocalDrivesEnabled: addIsAddLocalDrivesEnabledEventHandler,
2357
+ isDeleteLocalDrivesEnabled: addIsDeleteLocalDrivesEnabledEventHandler,
2358
+ isDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,
2359
+ isExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,
2360
+ isEditorDebugModeEnabled: addIsEditorDebugModeEnabledEventHandler,
2361
+ isEditorReadModeEnabled: addIsEditorReadModeEnabledEventHandler,
2362
+ isRelationalProcessorsEnabled: addIsRelationalProcessorsEnabledEventHandler,
2363
+ isExternalRelationalProcessorsEnabled: addIsExternalRelationalProcessorsEnabledEventHandler,
2364
+ isAnalyticsEnabled: addIsAnalyticsEnabledEventHandler,
2365
+ isAnalyticsExternalProcessorsEnabled: addIsAnalyticsExternalProcessorsEnabledEventHandler,
2366
+ analyticsDatabaseName: addAnalyticsDatabaseNameEventHandler,
2367
+ isAnalyticsDatabaseWorkerEnabled: addIsAnalyticsDatabaseWorkerEnabledEventHandler,
2368
+ isDiffAnalyticsEnabled: addIsDiffAnalyticsEnabledEventHandler,
2369
+ isDriveAnalyticsEnabled: addIsDriveAnalyticsEnabledEventHandler,
2370
+ renownUrl: addRenownUrlEventHandler,
2371
+ renownNetworkId: addRenownNetworkIdEventHandler,
2372
+ renownChainId: addRenownChainIdEventHandler,
2373
+ switchboardUrl: addSwitchboardUrlEventHandler,
2374
+ renownAdapters: addRenownAdaptersEventHandler,
2375
+ sentryRelease: addSentryReleaseEventHandler,
2376
+ sentryDsn: addSentryDsnEventHandler,
2377
+ sentryEnv: addSentryEnvEventHandler,
2378
+ isSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,
2379
+ isExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,
2380
+ isExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,
2381
+ toast: addToastEventHandler
2382
+ };
2383
+ function addPHEventHandlers() {
2384
+ callEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);
2385
+ }
2386
+ function callEventHandlerRegisterFunctions(registerFunctions) {
2387
+ forEachObj(registerFunctions, (fn) => fn());
2388
+ }
2389
+ //#endregion
2390
+ //#region src/graphql-client/static-package-manager.ts
2391
+ /**
2392
+ * A fixed set of packages presented through the `IPackageManager` interface,
2393
+ * so the package-derived hooks - `useDocumentModelModules`,
2394
+ * `useDocumentModelModuleById`, `useEditorModules`, `useVetraPackages` - work
2395
+ * below `GraphQLReactorProvider` exactly as they do below Connect.
2396
+ *
2397
+ * Connect's package manager installs, updates and removes packages at runtime.
2398
+ * A light app instead declares its packages once, as code it imports itself
2399
+ * (every generated package root exports `manifest`, `documentModels`, `editors`
2400
+ * and `upgradeManifests` by name), so every mutating member throws and
2401
+ * `subscribe` never emits. For hand-picked modules without package artifacts,
2402
+ * {@link packageFromDocumentModels} wraps them in one synthetic package.
2403
+ */
2404
+ var StaticPackageManager = class {
2405
+ registryUrl = null;
2406
+ packages;
2407
+ constructor(packages) {
2408
+ this.packages = [...packages];
2409
+ }
2410
+ /**
2411
+ * Resolves a module by document type across all packages. Mirrors the
2412
+ * registry's semantics (`IDocumentModelRegistry.getModule`): the LATEST
2413
+ * version wins, with `version ?? 1` as each module's default.
2414
+ */
2415
+ load(documentType) {
2416
+ let latestModule;
2417
+ let latestVersion = -1;
2418
+ for (const pkg of this.packages) for (const module of pkg.documentModels) {
2419
+ if (module.documentModel.global.id !== documentType) continue;
2420
+ const moduleVersion = module.version ?? 1;
2421
+ if (moduleVersion > latestVersion) {
2422
+ latestVersion = moduleVersion;
2423
+ latestModule = module;
2424
+ }
2425
+ }
2426
+ return latestModule ? Promise.resolve(latestModule) : Promise.reject(/* @__PURE__ */ new Error(`Unknown document type: ${documentType}`));
2427
+ }
2428
+ subscribe(_handler) {
2429
+ return () => {};
2430
+ }
2431
+ getPackageSource(_packageName) {
2432
+ return null;
2433
+ }
2434
+ getPackageVersion(_packageName) {}
2435
+ getRegistryPackages() {
2436
+ return [];
2437
+ }
2438
+ addPackage(_packageName) {
2439
+ throw staticPackageManagerError("addPackage");
2440
+ }
2441
+ addPackages(_packageNames) {
2442
+ throw staticPackageManagerError("addPackages");
2443
+ }
2444
+ removePackage(_name) {
2445
+ throw staticPackageManagerError("removePackage");
2446
+ }
2447
+ updateLocalPackage(_pkg, _version) {
2448
+ throw staticPackageManagerError("updateLocalPackage");
2449
+ }
2450
+ addLocalPackage(_name, _loadedPackage, _version) {
2451
+ throw staticPackageManagerError("addLocalPackage");
2452
+ }
2453
+ };
2454
+ function staticPackageManagerError(member) {
2455
+ return /* @__PURE__ */ new Error(`${member} is not supported: StaticPackageManager holds a fixed set of packages`);
2456
+ }
2457
+ /**
2458
+ * Wraps hand-picked modules in one synthetic `DocumentModelLib`, for apps that
2459
+ * assemble their model list from mixed sources instead of passing whole
2460
+ * packages. The manifest is fabricated - loose modules carry none - so prefer
2461
+ * the `packages` prop with the real package exports when you have them: a real
2462
+ * package also carries `editors`, which makes the editor hooks work.
2463
+ */
2464
+ function packageFromDocumentModels(documentModels) {
2465
+ return {
2466
+ manifest: {
2467
+ name: "graphql-reactor-provider",
2468
+ description: "Document models passed to GraphQLReactorProvider"
2469
+ },
2470
+ documentModels,
2471
+ editors: []
2472
+ };
2473
+ }
2474
+ //#endregion
2475
+ //#region src/graphql-client/graphql-reactor-provider.tsx
2476
+ /**
2477
+ * Registers the `window.ph` event handlers once per page.
2478
+ *
2479
+ * The `set*` helpers only dispatch CustomEvents - nothing writes `window.ph`
2480
+ * until `addPHEventHandlers` has registered the listeners that do. Registration
2481
+ * is guarded by a marker on `window` rather than a module-level flag so that a
2482
+ * hot module replacement, or two copies of this module, still register once.
2483
+ */
2484
+ function ensurePHEventHandlers() {
2485
+ if (typeof window === "undefined" || window.__phEventHandlersRegistered) return;
2486
+ addPHEventHandlers();
2487
+ window.__phEventHandlersRegistered = true;
2488
+ }
2489
+ /**
2490
+ * Mounts a {@link GraphQLReactorClient} into the `window.ph` slots the
2491
+ * reactor-browser hooks read, so `useDocument`, `useDispatch` and
2492
+ * `useReactorClient` work below it against a Switchboard, with no reactor in
2493
+ * the bundle.
2494
+ *
2495
+ * It fills the document slots, plus `window.ph.vetraPackageManager` when
2496
+ * `documentModels` is given (a fixed {@link StaticPackageManager}, which makes
2497
+ * the document-model hooks work). `window.ph.reactorClientModule` always stays
2498
+ * empty, so full-reactor surfaces (drives, jobs, editor auto-discovery) find
2499
+ * nothing - an app below this provider renders components it imports itself.
2500
+ *
2501
+ * The client is built on the client only: on the server the slots stay empty
2502
+ * and the hooks report their normal loading states. The props are read once,
2503
+ * when the client is built - changing `url` afterwards does not rebuild it.
2504
+ *
2505
+ * The effect's cleanup disposes the cache and the client's socket, and the
2506
+ * effect rebuilds both if it runs again on the same client - which is what a
2507
+ * `StrictMode` mount does.
2508
+ */
2509
+ function GraphQLReactorProvider({ url, tokenProvider, subscriptionsUrl, realtime, attachmentService, packages, documentModels, children }) {
2510
+ const [client] = useState(() => typeof window === "undefined" ? void 0 : new GraphQLReactorClient({
2511
+ url,
2512
+ tokenProvider,
2513
+ subscriptionsUrl,
2514
+ realtime
2515
+ }));
2516
+ useEffect(() => {
2517
+ if (!client) return;
2518
+ ensurePHEventHandlers();
2519
+ setReactorClient(client);
2520
+ const documentCache = new DocumentCache(client);
2521
+ setDocumentCache(documentCache);
2522
+ return () => {
2523
+ documentCache.dispose();
2524
+ client.dispose();
2525
+ };
2526
+ }, [client]);
2527
+ useEffect(() => {
2528
+ if (!attachmentService) return;
2529
+ ensurePHEventHandlers();
2530
+ setAttachmentService(attachmentService);
2531
+ }, [attachmentService]);
2532
+ useEffect(() => {
2533
+ const libs = [...packages ?? [], ...documentModels && documentModels.length > 0 ? [packageFromDocumentModels(documentModels)] : []];
2534
+ if (libs.length === 0) return;
2535
+ ensurePHEventHandlers();
2536
+ setVetraPackageManager(new StaticPackageManager(libs));
2537
+ }, [packages, documentModels]);
2538
+ return /* @__PURE__ */ jsx(Fragment, { children });
2539
+ }
2540
+ /**
2541
+ * Returns the {@link GraphQLReactorClient} mounted by
2542
+ * {@link GraphQLReactorProvider}, or `undefined` when the slot holds something
2543
+ * else - the full in-browser reactor client, or nothing yet.
2544
+ *
2545
+ * `useReactorClient` is typed as the narrow `IReactorBrowserClient` subset both
2546
+ * implementations share. This is how a component reaches the light client's own
2547
+ * surface, i.e. `subgraph` and `request`.
2548
+ *
2549
+ * The narrowing is by brand, not by `instanceof`: a page can carry two copies
2550
+ * of this module - a bundled package with its own copy, or a hot-replaced one -
2551
+ * and `instanceof` would then answer `false` for a perfectly good client and
2552
+ * leave the component silently without one.
2553
+ */
2554
+ function useSwitchboardClient() {
2555
+ const client = useReactorClient();
2556
+ return isGraphQLReactorClient(client) ? client : void 0;
2557
+ }
2558
+ //#endregion
2559
+ //#region src/hooks/document-model-modules.ts
2560
+ function useDocumentModelModules() {
2561
+ return useVetraPackages().flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && m.version === module.version) === index);
2562
+ }
2563
+ /**
2564
+ * Resolves a document model module by document type, mirroring the registry's
2565
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
2566
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
2567
+ * with `version` given only an exact match is returned. The reactor resolves
2568
+ * modules the same way when a document is created, so metadata read through
2569
+ * this hook and the version a creation actually uses cannot disagree.
2570
+ */
2571
+ function useDocumentModelModuleById(id, version) {
2572
+ const documentModelModules = useDocumentModelModules();
2573
+ if (!id || !documentModelModules) return void 0;
2574
+ let latestModule;
2575
+ let latestVersion = -1;
2576
+ for (const module of documentModelModules) {
2577
+ if (module.documentModel.global.id !== id) continue;
2578
+ const moduleVersion = module.version ?? 1;
2579
+ if (version !== void 0) {
2580
+ if (moduleVersion === version) return module;
2581
+ continue;
2582
+ }
2583
+ if (moduleVersion > latestVersion) {
2584
+ latestVersion = moduleVersion;
2585
+ latestModule = module;
2586
+ }
2587
+ }
2588
+ return latestModule;
2589
+ }
2590
+ //#endregion
2591
+ export { setGraphQLReactorClient as $, phDocumentFromGetDocument as $i, setIsDeleteLocalDrivesEnabled as $n, useIsEditorDebugModeEnabled as $r, addIsAnalyticsExternalProcessorsEnabledEventHandler as $t, isFileNodeKind as A, DocumentTypeMismatchError as Aa, phDocumentEditorConfigHooks as Ai, addVersionEventHandler as An, useAnalyticsDatabaseName as Ar, resolveUrlPathname as At, setReactorClient as B, viewFilterInputFromViewFilter as Bi, setDrivesPreserveStrategy as Bn, useIsAddDriveEnabled as Br, addCliVersionEventHandler as Bt, useSelectedTimelineItem as C, moveNode$1 as Ca, useWarnOutdatedApp as Ci, addRouterBasenameEventHandler as Cn, setSentryRelease as Cr, extractNodeIdFromPath as Ct, useFileNodesInSelectedDrive as D, isDocumentTypeSupported as Da, isExternalControlsEnabledEventFunctions as Di, addStudioModeEventHandler as Dn, setVersionCheckInterval as Dr, getPathWithoutBase as Dt, useDocumentsInSelectedDrive as E, getUserPermissions as Ea, addIsExternalControlsEnabledEventHandler as Ei, addSentryReleaseEventHandler as En, setVersion as Er, findUuid as Et, setRevisionHistoryVisible as F, useAllowedDocumentTypes as Fi, setAnalyticsDatabaseName as Fn, useDrivesPreserveStrategy as Fr, setAttachmentService as Ft, useReactorClient as G, describeGraphQLDocument as Gi, setIsAddDriveEnabled as Gn, useIsAnalyticsExternalProcessorsEnabled as Gr, addFileUploadOperationsChunkSizeEventHandler as Gt, useDatabase as H, startDocumentChangesSubscription as Hi, setFileUploadOperationsChunkSize as Hn, useIsAddPublicDrivesEnabled as Hr, addDisabledEditorsEventHandler as Ht, showRevisionHistory as I, useIsDragAndDropEnabled as Ii, setBasePath as In, useEnabledEditors as Ir, useAttachmentService as It, useSyncList as J, stampAction as Ji, setIsAnalyticsDatabaseWorkerEnabled as Jn, useIsDeleteLocalDrivesEnabled as Jr, addIsAddDriveEnabledEventHandler as Jt, useReactorClientModule as K, subgraphUrlFromGraphqlUrl as Ki, setIsAddLocalDrivesEnabled as Kn, useIsCloudDrivesEnabled as Kr, addGaTrackingIdEventHandler as Kt, useRevisionHistoryVisible as L, useIsExternalControlsEnabled as Li, setCliVersion as Ln, useFileUploadOperationsChunkSize as Lr, addAllowListEventHandler as Lt, sortNodesByName as M, UnsupportedDocumentTypeError as Ma, setAllowedDocumentTypes as Mi, phGlobalConfigHooks as Mn, useCliVersion as Mr, setFeatures as Mt, addRevisionHistoryVisibleEventHandler as N, setIsDragAndDropEnabled as Ni, phGlobalConfigSetters as Nn, useDefaultDrivesUrl as Nr, useFeatures as Nt, useFolderNodesInSelectedDrive as O, DocumentModelNotFoundError as Oa, phAppConfigHooks as Oi, addSwitchboardUrlEventHandler as On, setWarnOutdatedApp as Or, makeDriveUrlComponent as Ot, hideRevisionHistory as P, setIsExternalControlsEnabled as Pi, setAllowList as Pn, useDisabledEditors as Pr, addAttachmentServiceEventHandler as Pt, addGraphQLReactorClientEventHandler as Q, makeAuthMiddleware as Qi, setIsDeleteCloudDrivesEnabled as Qn, useIsDriveAnalyticsEnabled as Qr, addIsAnalyticsEnabledEventHandler as Qt, addReactorClientEventHandler as R, GraphQLReactorClient as Ri, setDefaultDrivesUrl as Rn, useGaTrackingId as Rr, addAnalyticsDatabaseNameEventHandler as Rt, setSelectedTimelineItem as S, loadFile as Sa, useVersionCheckInterval as Si, addRequiresHardRefreshEventHandler as Sn, setSentryEnv as Sr, extractDriveSlugFromPath as St, useDocumentTypesInSelectedDrive as T, renameNode as Ta, addIsDragAndDropEnabledEventHandler as Ti, addSentryEnvEventHandler as Tn, setSwitchboardUrl as Tr, extractNodeSlugFromPath as Tt, useModelRegistry as U, subscriptionsUrlFromGraphqlUrl as Ui, setGaTrackingId as Un, useIsAnalyticsDatabaseWorkerEnabled as Ur, addDrivesPreserveStrategyEventHandler as Ut, setReactorClientModule as V, makeAuthConnectionParams as Vi, setEnabledEditors as Vn, useIsAddLocalDrivesEnabled as Vr, addDefaultDrivesUrlEventHandler as Vt, usePGlite as W, SubgraphSdkRegistry as Wi, setIsAddCloudDrivesEnabled as Wn, useIsAnalyticsEnabled as Wr, addEnabledEditorsEventHandler as Wt, setPackageDiscoveryService as X, ReactorOperationFieldsFragmentDoc as Xi, setIsAnalyticsExternalProcessorsEnabled as Xn, useIsDiffAnalyticsEnabled as Xr, addIsAddPublicDrivesEnabledEventHandler as Xt, addPackageDiscoveryServiceEventHandler as Y, MutateDocumentWithOperationsDocument as Yi, setIsAnalyticsEnabled as Yn, useIsDeletePublicDrivesEnabled as Yr, addIsAddLocalDrivesEnabledEventHandler as Yt, usePackageDiscoveryService as Z, ambientRenownTokenProvider as Zi, setIsCloudDrivesEnabled as Zn, useIsDocumentModelSelectionSettingsEnabled as Zr, addIsAnalyticsDatabaseWorkerEnabledEventHandler as Zt, usePHToast as _, addFileWithProgress as _a, useSentryEnv as _i, addLogLevelEventHandler as _n, setRenownNetworkId as _r, setDrives as _t, useSwitchboardClient as a, extractRevisionMap as aa, useIsPublicDrivesEnabled as ai, addIsDocumentModelSelectionSettingsEnabledEventHandler as an, setIsEditorReadModeEnabled as ar, addSelectedDriveIdEventHandler as at, useSelectedTimelineRevision as b, deleteNode as ba, useSwitchboardUrl as bi, addRenownNetworkIdEventHandler as bn, setRouterBasename as br, extractDriveIdFromPath as bt, addPHEventHandlers as c, addModalEventHandler as ca, useLocalDrivesEnabled as ci, addIsEditorReadModeEnabledEventHandler as cn, setIsExternalRelationalProcessorsEnabled as cr, setSelectedDriveId as ct, addVetraPackageManagerEventHandler as d, showCreateDocumentModal as da, useRenownChainId as di, addIsExternalRelationalProcessorsEnabledEventHandler as dn, setIsRelationalProcessorsEnabled as dr, useSelectedDriveSafe as dt, phDocumentFromMutation as ea, useIsEditorReadModeEnabled as ei, addIsCloudDrivesEnabledEventHandler as en, setIsDeletePublicDrivesEnabled as er, useGraphQLReactorClient as et, setVetraPackageManager as f, showDeleteNodeModal as fa, useRenownNetworkId as fi, addIsLocalDrivesEnabledEventHandler as fn, setIsSentryTracingEnabled as fr, addResetSelectedNodeEventHandler as ft, setPHToast as g, addFile as ga, useSentryDsn as gi, addLocalDrivesEnabledEventHandler as gn, setRenownChainId as gr, addDrivesEventHandler as gt, addToastEventHandler as h, addDocument as ha, useRouterBasename as hi, addIsSentryTracingEnabledEventHandler as hn, setRenownAdapters as hr, setSelectedNode as ht, ensurePHEventHandlers as i, convertRemoteOperations as ia, useIsLocalDrivesEnabled as ii, addIsDiffAnalyticsEnabledEventHandler as in, setIsEditorDebugModeEnabled as ir, useDropTarget as it, isFolderNodeKind as j, NoSelectedDocumentError as ja, phDocumentEditorConfigSetters as ji, addWarnOutdatedAppEventHandler as jn, useBasePath as jr, addFeaturesEventHandler as jt, useNodesInSelectedDrive as k, DocumentNotFoundError as ka, phAppConfigSetters as ki, addVersionCheckIntervalEventHandler as kn, useAllowList as kr, makeNodeSlug as kt, callEventHandlerRegisterFunctions as l, closePHModal as la, useLogLevel as li, addIsExternalPackagesEnabledEventHandler as ln, setIsLocalDrivesEnabled as lr, useSelectedDrive as lt, useVetraPackages as m, usePHModal as ma, useRequiresHardRefresh as mi, addIsRelationalProcessorsEnabledEventHandler as mn, setLogLevel as mr, addSetSelectedNodeOnPopStateEventHandler as mt, useDocumentModelModules as n, ConflictError as na, useIsExternalProcessorsEnabled as ni, addIsDeleteLocalDrivesEnabledEventHandler as nn, setIsDocumentModelSelectionSettingsEnabled as nr, useDragNode as nt, StaticPackageManager as o, hasRevisionConflict as oa, useIsRelationalProcessorsEnabled as oi, addIsDriveAnalyticsEnabledEventHandler as on, setIsExternalPackagesEnabled as or, addSetSelectedDriveOnPopStateEventHandler as ot, useVetraPackageManager as p, showPHModal as pa, useRenownUrl as pi, addIsPublicDrivesEnabledEventHandler as pn, setLocalDrivesEnabled as pr, addSelectedNodeIdEventHandler as pt, useSync as q, signStampedAction as qi, setIsAddPublicDrivesEnabled as qn, useIsDeleteCloudDrivesEnabled as qr, addIsAddCloudDrivesEnabledEventHandler as qt, GraphQLReactorProvider as r, buildPulledDocument as ra, useIsExternalRelationalProcessorsEnabled as ri, addIsDeletePublicDrivesEnabledEventHandler as rn, setIsDriveAnalyticsEnabled as rr, useDropNode as rt, packageFromDocumentModels as s, screamingSnakeToCamel as sa, useIsSentryTracingEnabled as si, addIsEditorDebugModeEnabledEventHandler as sn, setIsExternalProcessorsEnabled as sr, setSelectedDrive as st, useDocumentModelModuleById as t, revisionMapFromRevisionsList as ta, useIsExternalPackagesEnabled as ti, addIsDeleteCloudDrivesEnabledEventHandler as tn, setIsDiffAnalyticsEnabled as tr, addDraggingNodeEventHandler as tt, commonGlobalEventHandlerFunctions as u, setPHModal as ua, useRenownAdapters as ui, addIsExternalProcessorsEnabledEventHandler as un, setIsPublicDrivesEnabled as ur, useSelectedDriveId as ut, addSelectedTimelineRevisionEventHandler as v, addFolder$1 as va, useSentryRelease as vi, addRenownAdaptersEventHandler as vn, setRenownUrl as vr, useDrives as vt, useSelectedNode as w, renameDriveNode as wa, addAllowedDocumentTypesEventHandler as wi, addSentryDsnEventHandler as wn, setStudioMode as wr, extractNodeIdFromSlug as wt, addSelectedTimelineItemEventHandler as x, exportFile as xa, useVersion as xi, addRenownUrlEventHandler as xn, setSentryDsn as xr, extractDriveIdFromSlug as xt, setSelectedTimelineRevision as y, copyNode$1 as ya, useStudioMode as yi, addRenownChainIdEventHandler as yn, setRequiresHardRefresh as yr, createUrlWithPreservedParams as yt, addReactorClientModuleEventHandler as z, isGraphQLReactorClient as zi, setDisabledEditors as zn, useIsAddCloudDrivesEnabled as zr, addBasePathEventHandler as zt };
2592
+
2593
+ //# sourceMappingURL=document-model-modules-B2_aAWc7.js.map