@powerhousedao/powerhouse-vetra-packages 6.2.3-dev.10 → 6.2.3-dev.11

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 (114) hide show
  1. package/dist/browser/assets/{entry-DvpdFGdw.js → entry-4ObkElbc.js} +2 -2
  2. package/dist/browser/assets/{projection-entry-QU4xTPM_.js → projection-entry-DRGRQCSu.js} +8 -8
  3. package/dist/browser/{button-CuO8Gh3v.js → button-sZQCXeCo.js} +131 -24
  4. package/dist/browser/button-sZQCXeCo.js.map +1 -0
  5. package/dist/browser/chunk-CRPLlQ3x.js +28 -0
  6. package/dist/browser/{dist-BAJ5nRDl.js → dist-D3_ER0Dn.js} +2 -399
  7. package/dist/browser/dist-D3_ER0Dn.js.map +1 -0
  8. package/dist/browser/document-models/index.js +2 -1
  9. package/dist/browser/{documents-J_l59mSV.js → documents-C-lAnv6o.js} +604 -735
  10. package/dist/browser/documents-C-lAnv6o.js.map +1 -0
  11. package/dist/browser/editor-BO_s5gTQ.js +3679 -0
  12. package/dist/browser/editor-BO_s5gTQ.js.map +1 -0
  13. package/dist/browser/{editor-D_gIraSB.js → editor-DNV-46lY.js} +5 -5
  14. package/dist/browser/{editor-D_gIraSB.js.map → editor-DNV-46lY.js.map} +1 -1
  15. package/dist/browser/editors/document-model-editor/module.js +1 -1
  16. package/dist/browser/editors/generic-drive-explorer/index.js +4 -5
  17. package/dist/browser/editors/generic-drive-explorer/index.js.map +1 -1
  18. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  19. package/dist/browser/folder-view-CzItU0hn.js +957 -0
  20. package/dist/browser/folder-view-CzItU0hn.js.map +1 -0
  21. package/dist/browser/{graphql-editor-C9wxFf0b.js → graphql-editor-BMhHl2XP.js} +7 -9
  22. package/dist/browser/{graphql-editor-C9wxFf0b.js.map → graphql-editor-BMhHl2XP.js.map} +1 -1
  23. package/dist/{node/hooks-D0DcS3MV.mjs → browser/hooks-Bh1JCohS.js} +2 -2
  24. package/dist/browser/{hooks-KKcNp2X0.js.map → hooks-Bh1JCohS.js.map} +1 -1
  25. package/dist/browser/index.js +120 -20
  26. package/dist/browser/index.js.map +1 -1
  27. package/dist/browser/{json-editor-BIGVi54h.js → json-editor-DBhkG5TF.js} +3 -4
  28. package/dist/browser/{json-editor-BIGVi54h.js.map → json-editor-DBhkG5TF.js.map} +1 -1
  29. package/dist/browser/{parser-CkF6Qt8V.js → parser-BBzK7bLd.js} +1 -1
  30. package/dist/browser/{parser-CkF6Qt8V.js.map → parser-BBzK7bLd.js.map} +1 -1
  31. package/dist/browser/{schema-context-ZyeclQwy.js → schema-context-p2bhyog_.js} +3 -3
  32. package/dist/browser/{schema-context-ZyeclQwy.js.map → schema-context-p2bhyog_.js.map} +1 -1
  33. package/dist/browser/src-CVV6HzQZ-D-OQvEkh.js +5151 -0
  34. package/dist/browser/src-CVV6HzQZ-D-OQvEkh.js.map +1 -0
  35. package/dist/browser/state-schemas-DuA5rB1e.js +694 -0
  36. package/dist/browser/state-schemas-DuA5rB1e.js.map +1 -0
  37. package/dist/browser/tslib.es6-CeIASJ2O.js +32 -0
  38. package/dist/browser/tslib.es6-CeIASJ2O.js.map +1 -0
  39. package/dist/node/{button-Da7CxMn7.mjs → button-5bnYEAVq.mjs} +130 -23
  40. package/dist/node/button-5bnYEAVq.mjs.map +1 -0
  41. package/dist/node/chunk-17FXJ3dL.mjs +31 -0
  42. package/dist/node/{dist-CzYOpeXN.mjs → dist-Bf_PIbO7.mjs} +2 -399
  43. package/dist/node/dist-Bf_PIbO7.mjs.map +1 -0
  44. package/dist/node/document-models/index.mjs +2 -1
  45. package/dist/node/documents-XAQfHX5Q.mjs +17 -0
  46. package/dist/node/documents-XAQfHX5Q.mjs.map +1 -0
  47. package/dist/node/editor-BiiLqEe9.mjs +3679 -0
  48. package/dist/node/editor-BiiLqEe9.mjs.map +1 -0
  49. package/dist/node/{editor-CJSAZpIG.mjs → editor-Cp2TC5MJ.mjs} +5 -5
  50. package/dist/node/{editor-CJSAZpIG.mjs.map → editor-Cp2TC5MJ.mjs.map} +1 -1
  51. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  52. package/dist/node/editors/generic-drive-explorer/index.mjs +4 -5
  53. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  54. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  55. package/dist/node/folder-view-m_rH84Nz.mjs +962 -0
  56. package/dist/node/folder-view-m_rH84Nz.mjs.map +1 -0
  57. package/dist/node/{graphql-BfAoPeWM.mjs → graphql-BvV3tC1U.mjs} +2 -2
  58. package/dist/node/{graphql-BfAoPeWM.mjs.map → graphql-BvV3tC1U.mjs.map} +1 -1
  59. package/dist/node/{graphql-editor-CnK5kIk9.mjs → graphql-editor-BhF6KN6y.mjs} +6 -7
  60. package/dist/node/{graphql-editor-CnK5kIk9.mjs.map → graphql-editor-BhF6KN6y.mjs.map} +1 -1
  61. package/dist/{browser/hooks-KKcNp2X0.js → node/hooks-Di3FASx-.mjs} +2 -2
  62. package/dist/node/{hooks-D0DcS3MV.mjs.map → hooks-Di3FASx-.mjs.map} +1 -1
  63. package/dist/node/index.mjs +142 -21
  64. package/dist/node/index.mjs.map +1 -1
  65. package/dist/node/{json-editor-j8_JGfcP.mjs → json-editor-Cqc0zuz0.mjs} +3 -4
  66. package/dist/node/{json-editor-j8_JGfcP.mjs.map → json-editor-Cqc0zuz0.mjs.map} +1 -1
  67. package/dist/node/{schema-context-DL8jhi_d.mjs → schema-context-mHmP3Cl6.mjs} +3 -3
  68. package/dist/node/{schema-context-DL8jhi_d.mjs.map → schema-context-mHmP3Cl6.mjs.map} +1 -1
  69. package/dist/node/{connect-D3-HufsW.mjs → src-CVV6HzQZ-CvqjXbXk.mjs} +1829 -11022
  70. package/dist/node/src-CVV6HzQZ-CvqjXbXk.mjs.map +1 -0
  71. package/dist/node/state-schemas-DXG02fMh.mjs +695 -0
  72. package/dist/node/state-schemas-DXG02fMh.mjs.map +1 -0
  73. package/dist/node/{main-7sul-YJl.mjs → tslib.es6-DdiHgz9e.mjs} +3 -203
  74. package/dist/node/tslib.es6-DdiHgz9e.mjs.map +1 -0
  75. package/package.json +7 -7
  76. package/dist/browser/button-CuO8Gh3v.js.map +0 -1
  77. package/dist/browser/connect-kwnl2v6o.js +0 -14328
  78. package/dist/browser/connect-kwnl2v6o.js.map +0 -1
  79. package/dist/browser/dist-B4FWbuEM.js +0 -4148
  80. package/dist/browser/dist-B4FWbuEM.js.map +0 -1
  81. package/dist/browser/dist-BAJ5nRDl.js.map +0 -1
  82. package/dist/browser/dist-D0tSbK8B.js +0 -4721
  83. package/dist/browser/dist-D0tSbK8B.js.map +0 -1
  84. package/dist/browser/document-drive-fcQ4o8i3.js +0 -8320
  85. package/dist/browser/document-drive-fcQ4o8i3.js.map +0 -1
  86. package/dist/browser/documents-J_l59mSV.js.map +0 -1
  87. package/dist/browser/editor-CbJkIqg_.js +0 -1809
  88. package/dist/browser/editor-CbJkIqg_.js.map +0 -1
  89. package/dist/browser/folder-view-CGcqEbak.js +0 -232
  90. package/dist/browser/folder-view-CGcqEbak.js.map +0 -1
  91. package/dist/browser/lib-BWPfFpyy.js +0 -209
  92. package/dist/browser/lib-BWPfFpyy.js.map +0 -1
  93. package/dist/browser/printer-CEYr4JOg.js +0 -604
  94. package/dist/browser/printer-CEYr4JOg.js.map +0 -1
  95. package/dist/browser/state-schemas-C9Nb7S5z.js +0 -298
  96. package/dist/browser/state-schemas-C9Nb7S5z.js.map +0 -1
  97. package/dist/node/button-Da7CxMn7.mjs.map +0 -1
  98. package/dist/node/connect-D3-HufsW.mjs.map +0 -1
  99. package/dist/node/dist-CzYOpeXN.mjs.map +0 -1
  100. package/dist/node/dist-D5Xp9PwJ.mjs +0 -4729
  101. package/dist/node/dist-D5Xp9PwJ.mjs.map +0 -1
  102. package/dist/node/dist-DT7jI9ol.mjs +0 -4148
  103. package/dist/node/dist-DT7jI9ol.mjs.map +0 -1
  104. package/dist/node/document-drive-DuGBBYw5.mjs +0 -8337
  105. package/dist/node/document-drive-DuGBBYw5.mjs.map +0 -1
  106. package/dist/node/documents-DCf53bzO.mjs +0 -747
  107. package/dist/node/documents-DCf53bzO.mjs.map +0 -1
  108. package/dist/node/editor-D8SL0ydm.mjs +0 -1809
  109. package/dist/node/editor-D8SL0ydm.mjs.map +0 -1
  110. package/dist/node/folder-view-ChtWc33j.mjs +0 -232
  111. package/dist/node/folder-view-ChtWc33j.mjs.map +0 -1
  112. package/dist/node/main-7sul-YJl.mjs.map +0 -1
  113. package/dist/node/state-schemas-DURvYjxG.mjs +0 -299
  114. package/dist/node/state-schemas-DURvYjxG.mjs.map +0 -1
@@ -1,4721 +0,0 @@
1
- import { A as __toESM, D as __commonJSMin, r as pascalCase, t as capitalCase } from "./dist-B4FWbuEM.js";
2
- import { A as createPresignedHeader, D as buildSignedAction, E as baseSaveToFileHandle, G as replayDocumentVersioned, N as createZip, T as baseLoadFromInputVersioned, _ as UnsupportedDocumentModelVersionError, a as getDescendants, c as isFileNode, ct as validateInitialState, d as moveNode, dt as zipEntries, et as setName, f as updateNode, ft as generateId, i as generateNodesCopy, l as isFolderNode, lt as validateModules, m as logger, n as copyNode, o as getNextCopyNumber, s as handleTargetNameCollisions, t as addFolder, ut as validateStateSchemaName, w as baseLoadFromInput, x as assertAuthPreservedOnDuplicate } from "./document-drive-fcQ4o8i3.js";
3
- import { a as SyncStatus, o as DriveCollectionId, s as ModuleNotFoundError, t as gql } from "./lib-BWPfFpyy.js";
4
- import { c as Kind, t as parse } from "./parser-CkF6Qt8V.js";
5
- import "./printer-CEYr4JOg.js";
6
- import { createContext, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
7
- import "react/jsx-runtime";
8
- //#region ../reactor-browser/dist/make-ph-event-functions-DBq3iWYn.js
9
- const isServer$1 = typeof window === "undefined";
10
- function makePHEventFunctions(key) {
11
- const setEventName = `ph:set${capitalCase(key)}`;
12
- const updateEventName = `ph:${key}Updated`;
13
- function setValue(value) {
14
- if (isServer$1) return;
15
- const event = new CustomEvent(setEventName, { detail: { [key]: value } });
16
- window.dispatchEvent(event);
17
- }
18
- function dispatchUpdatedEvent() {
19
- if (isServer$1) return;
20
- const event = new CustomEvent(updateEventName);
21
- window.dispatchEvent(event);
22
- }
23
- function handleSetValueEvent(event) {
24
- if (isServer$1) return;
25
- const value = event.detail[key];
26
- if (!window.ph) window.ph = {};
27
- window.ph[key] = value;
28
- dispatchUpdatedEvent();
29
- }
30
- function addEventHandler() {
31
- if (isServer$1) return;
32
- window.addEventListener(setEventName, handleSetValueEvent);
33
- }
34
- function subscribeToValue(onStoreChange) {
35
- if (isServer$1) return () => {};
36
- window.addEventListener(updateEventName, onStoreChange);
37
- return () => {
38
- window.removeEventListener(updateEventName, onStoreChange);
39
- };
40
- }
41
- function getSnapshot() {
42
- if (isServer$1) return;
43
- return window.ph?.[key];
44
- }
45
- function getServerSnapshot() {}
46
- function useValue() {
47
- return useSyncExternalStore(subscribeToValue, getSnapshot, getServerSnapshot);
48
- }
49
- return {
50
- useValue,
51
- setValue,
52
- addEventHandler
53
- };
54
- }
55
- //#endregion
56
- //#region ../reactor-browser/dist/document-by-id-B4FIzG1w.js
57
- async function queueActions(document, actionOrActions) {
58
- if (!document) throw new Error("No document provided");
59
- if (!actionOrActions) throw new Error("No actions provided");
60
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
61
- if (actions.length === 0) throw new Error("No actions provided");
62
- const reactorClient = window.ph?.reactorClient;
63
- if (!reactorClient) throw new Error("ReactorClient not initialized");
64
- return await reactorClient.execute(document.header.id, "main", actions);
65
- }
66
- async function queueOperations(documentId, operationOrOperations) {
67
- if (!documentId) throw new Error("No documentId provided");
68
- if (!operationOrOperations) throw new Error("No operations provided");
69
- const operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];
70
- if (operations.length === 0) throw new Error("No operations provided");
71
- const reactorClient = window.ph?.reactorClient;
72
- if (!reactorClient) throw new Error("ReactorClient not initialized");
73
- const actions = operations.map((op) => op.action);
74
- return await reactorClient.execute(documentId, "main", actions);
75
- }
76
- async function uploadOperations(documentId, allOperations, pushOperations, options) {
77
- const operationsLimit = options?.operationsLimit || 50;
78
- const onProgress = options?.onProgress;
79
- logger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(",")}, limit:${operationsLimit})`);
80
- const allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);
81
- const totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);
82
- let uploadedOperations = 0;
83
- for (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {
84
- logger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);
85
- const chunk = operations.slice(i, i + operationsLimit);
86
- const operation = chunk.at(-1);
87
- if (!operation) break;
88
- const scope = operation.action.scope;
89
- await pushOperations(documentId, chunk);
90
- uploadedOperations += chunk.length;
91
- if (onProgress) onProgress({
92
- stage: "uploading",
93
- progress: Math.round(uploadedOperations / totalOperations * 100),
94
- totalOperations,
95
- uploadedOperations
96
- });
97
- logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);
98
- }
99
- logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
100
- }
101
- async function signAction(action, document) {
102
- const renown = window.ph?.renown;
103
- if (!renown?.user) return action;
104
- if (!action.context?.signer) return action;
105
- const reactorClient = window.ph?.reactorClientModule?.client;
106
- if (!reactorClient) return action;
107
- const reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;
108
- const actionSigner = action.context.signer;
109
- return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
110
- }
111
- function addActionContext(action) {
112
- const renown = window.ph?.renown;
113
- if (!renown?.user) return action;
114
- return {
115
- context: { signer: {
116
- app: {
117
- name: "Connect",
118
- key: renown.did
119
- },
120
- user: {
121
- address: renown.user.address,
122
- networkId: renown.user.networkId,
123
- chainId: renown.user.chainId
124
- },
125
- signatures: []
126
- } },
127
- ...action
128
- };
129
- }
130
- async function makeSignedActionWithContext(action, document) {
131
- if (!action) {
132
- logger.error("No action found");
133
- return;
134
- }
135
- if (!document) {
136
- logger.error("No document found");
137
- return;
138
- }
139
- return addActionContext(await signAction(action, document));
140
- }
141
- async function makeSignedActionsWithContext(actionOrActions, document) {
142
- if (!actionOrActions) {
143
- logger.error("No actions found");
144
- return;
145
- }
146
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
147
- return (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);
148
- }
149
- async function getDocument(documentId) {
150
- try {
151
- return await window.ph?.reactorClient?.get(documentId);
152
- } catch (error) {
153
- logger.debug(`Failed to get document with id ${documentId}:`, error);
154
- return;
155
- }
156
- }
157
- function getActionErrors(result, actions) {
158
- return actions.reduce((errors, a) => {
159
- const scopeOperations = result.operations[a.scope];
160
- if (!scopeOperations) return errors;
161
- const op = scopeOperations.findLast((op) => op.action.id === a.id);
162
- if (op?.error) errors.push(new Error(op.error));
163
- return errors;
164
- }, new Array());
165
- }
166
- async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
167
- const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
168
- if (!document) {
169
- logger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);
170
- return;
171
- }
172
- const signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);
173
- if (!signedActionsWithContext) {
174
- logger.error("No signed actions with context found");
175
- return;
176
- }
177
- const result = await queueActions(document, signedActionsWithContext);
178
- if (onErrors && result) {
179
- const errors = getActionErrors(result, signedActionsWithContext);
180
- if (errors.length) onErrors(errors);
181
- }
182
- if (onSuccess && result) onSuccess(result);
183
- return result;
184
- }
185
- /**
186
- * The reactor's `DocumentChangeType` members, typed as the enum so they can be
187
- * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
188
- * TypeScript string enum is nominal, so no string literal is assignable to it
189
- * without one - and the two checks above are what make it safe.
190
- */
191
- const DOCUMENT_CHANGE_TYPE = {
192
- Created: "created",
193
- Deleted: "deleted",
194
- Updated: "updated",
195
- ParentAdded: "parent_added",
196
- ParentRemoved: "parent_removed",
197
- ChildAdded: "child_added",
198
- ChildRemoved: "child_removed"
199
- };
200
- const documentEventFunctions = makePHEventFunctions("documentCache");
201
- /** Returns all documents in the reactor. */
202
- const useDocumentCache = documentEventFunctions.useValue;
203
- documentEventFunctions.setValue;
204
- documentEventFunctions.addEventHandler;
205
- /**
206
- * Retrieves a document from the reactor and subscribes to changes using React Suspense.
207
- * This hook will suspend rendering while the document is loading.
208
- * @param id - The document ID to retrieve, or null/undefined to skip retrieval
209
- * @returns The document if found, or undefined if id is null/undefined
210
- */
211
- function useDocument(id) {
212
- const documentCache = useDocumentCache();
213
- const document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);
214
- return document ? use(document) : void 0;
215
- }
216
- /**
217
- * Returns a function to retrieve a document from the cache.
218
- * The returned function fetches and returns a document by ID.
219
- * @returns A function that takes a document ID and returns a Promise of the document
220
- */
221
- function useGetDocument() {
222
- const documentCache = useDocumentCache();
223
- return useCallback((id) => {
224
- if (!documentCache) return Promise.reject(/* @__PURE__ */ new Error("Document cache not initialized"));
225
- return documentCache.get(id);
226
- }, [documentCache]);
227
- }
228
- function useDispatch(document) {
229
- /**
230
- * Dispatches actions to the document.
231
- * @param actionOrActions - The action or actions to dispatch.
232
- * @param onErrors - Callback invoked with any errors that occurred during action execution.
233
- */
234
- function dispatch(actionOrActions, onErrors, onSuccess) {
235
- dispatchActions(actionOrActions, document, onErrors, onSuccess).catch((error) => {
236
- logger.error("Failed to dispatch actions: @error", error);
237
- });
238
- }
239
- return [document, dispatch];
240
- }
241
- /** Returns a document by id. */
242
- function useDocumentById(id) {
243
- const document = useDocument(id);
244
- const [, dispatch] = useDispatch(document);
245
- return [document, dispatch];
246
- }
247
- //#endregion
248
- //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
249
- let base64;
250
- if (typeof window !== "undefined") if (window.btoa) base64 = function(input) {
251
- return btoa(unescape(encodeURIComponent(input)));
252
- };
253
- else base64 = function(input) {
254
- const str = unescape(encodeURIComponent(input + ""));
255
- let output = "";
256
- for (let block, charCode, idx = 0, map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; str.charAt(idx | 0) || (map = "=", idx % 1); output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {
257
- charCode = str.charCodeAt(idx += 3 / 4);
258
- /* c8 ignore next 3 */
259
- if (charCode > 255) throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
260
- block = block << 8 | charCode;
261
- }
262
- return output;
263
- };
264
- else base64 = function(input) {
265
- return Buffer.from(input).toString("base64");
266
- };
267
- function slug(string, opts) {
268
- let result = slugify(string, opts);
269
- if ((opts && opts.fallback !== void 0 ? opts.fallback : slug.defaults.fallback) === true && result === "") result = slugify(base64(string), opts);
270
- return result;
271
- }
272
- const locales = {
273
- bg: {
274
- Й: "Y",
275
- й: "y",
276
- X: "H",
277
- x: "h",
278
- Ц: "Ts",
279
- ц: "ts",
280
- Щ: "Sht",
281
- щ: "sht",
282
- Ъ: "A",
283
- ъ: "a",
284
- Ь: "Y",
285
- ь: "y"
286
- },
287
- de: {
288
- Ä: "AE",
289
- ä: "ae",
290
- Ö: "OE",
291
- ö: "oe",
292
- Ü: "UE",
293
- ü: "ue"
294
- },
295
- sr: {
296
- đ: "dj",
297
- Đ: "DJ"
298
- },
299
- uk: {
300
- И: "Y",
301
- и: "y",
302
- Й: "Y",
303
- й: "y",
304
- Ц: "Ts",
305
- ц: "ts",
306
- Х: "Kh",
307
- х: "kh",
308
- Щ: "Shch",
309
- щ: "shch",
310
- Г: "H",
311
- г: "h"
312
- }
313
- };
314
- let defaultLocale = {};
315
- function slugify(string, opts) {
316
- if (typeof string !== "string") throw new Error("slug() requires a string argument, received " + typeof string);
317
- if (!string.isWellFormed()) throw new Error("slug() received a malformed string with lone surrogates");
318
- if (typeof opts === "string") opts = { replacement: opts };
319
- opts = opts ? Object.assign({}, opts) : {};
320
- opts.mode = opts.mode || slug.defaults.mode;
321
- const defaults = slug.defaults.modes[opts.mode];
322
- const keys = [
323
- "replacement",
324
- "multicharmap",
325
- "charmap",
326
- "remove",
327
- "lower",
328
- "trim"
329
- ];
330
- for (let key, i = 0, l = keys.length; i < l; i++) {
331
- key = keys[i];
332
- opts[key] = key in opts ? opts[key] : defaults[key];
333
- }
334
- const localeMap = locales[opts.locale] || defaultLocale;
335
- let lengths = [];
336
- for (const key in opts.multicharmap) {
337
- if (!Object.prototype.hasOwnProperty.call(opts.multicharmap, key)) continue;
338
- const len = key.length;
339
- if (lengths.indexOf(len) === -1) lengths.push(len);
340
- }
341
- lengths = lengths.sort(function(a, b) {
342
- return b - a;
343
- });
344
- const disallowedChars = opts.mode === "rfc3986" ? /[^\w\s\-.~]/ : /[^A-Za-z0-9\s]/;
345
- let result = "";
346
- for (let char, i = 0, l = string.length; i < l; i++) {
347
- char = string[i];
348
- let matchedMultichar = false;
349
- for (let j = 0; j < lengths.length; j++) {
350
- const len = lengths[j];
351
- const str = string.substr(i, len);
352
- if (opts.multicharmap[str]) {
353
- i += len - 1;
354
- char = opts.multicharmap[str];
355
- matchedMultichar = true;
356
- break;
357
- }
358
- }
359
- if (!matchedMultichar) if (localeMap[char]) char = localeMap[char];
360
- else if (opts.charmap[char]) char = opts.charmap[char].replace(opts.replacement, " ");
361
- else if (char.includes(opts.replacement)) char = char.replace(opts.replacement, " ");
362
- else char = char.replace(disallowedChars, "");
363
- result += char;
364
- }
365
- if (opts.remove) result = result.replace(opts.remove, "");
366
- if (opts.trim) result = result.trim();
367
- result = result.replace(/\s+/g, opts.replacement);
368
- if (opts.lower) result = result.toLowerCase();
369
- return result;
370
- }
371
- const initialMulticharmap = {
372
- फ़: "Fi",
373
- ग़: "Ghi",
374
- ख़: "Khi",
375
- क़: "Qi",
376
- ड़: "ugDha",
377
- ढ़: "ugDhha",
378
- य़: "Yi",
379
- ज़: "Za",
380
- בִי: "i",
381
- בֵ: "e",
382
- בֵי: "e",
383
- בֶ: "e",
384
- בַ: "a",
385
- בָ: "a",
386
- בֹ: "o",
387
- וֹ: "o",
388
- בֻ: "u",
389
- וּ: "u",
390
- בּ: "b",
391
- כּ: "k",
392
- ךּ: "k",
393
- פּ: "p",
394
- שׁ: "sh",
395
- שׂ: "s",
396
- בְ: "e",
397
- חֱ: "e",
398
- חֲ: "a",
399
- חֳ: "o",
400
- בִ: "i"
401
- };
402
- const initialCharmap = {
403
- À: "A",
404
- Á: "A",
405
- Â: "A",
406
- Ã: "A",
407
- Ä: "A",
408
- Å: "A",
409
- Æ: "AE",
410
- Ç: "C",
411
- È: "E",
412
- É: "E",
413
- Ê: "E",
414
- Ë: "E",
415
- Ì: "I",
416
- Í: "I",
417
- Î: "I",
418
- Ï: "I",
419
- Ð: "D",
420
- Ñ: "N",
421
- Ò: "O",
422
- Ó: "O",
423
- Ô: "O",
424
- Õ: "O",
425
- Ö: "O",
426
- Ő: "O",
427
- Ø: "O",
428
- Ō: "O",
429
- Ù: "U",
430
- Ú: "U",
431
- Û: "U",
432
- Ü: "U",
433
- Ű: "U",
434
- Ý: "Y",
435
- Þ: "TH",
436
- ß: "ss",
437
- à: "a",
438
- á: "a",
439
- â: "a",
440
- ã: "a",
441
- ä: "a",
442
- å: "a",
443
- æ: "ae",
444
- ç: "c",
445
- è: "e",
446
- é: "e",
447
- ê: "e",
448
- ë: "e",
449
- ì: "i",
450
- í: "i",
451
- î: "i",
452
- ï: "i",
453
- ð: "d",
454
- ñ: "n",
455
- ò: "o",
456
- ó: "o",
457
- ô: "o",
458
- õ: "o",
459
- ö: "o",
460
- ő: "o",
461
- ø: "o",
462
- ō: "o",
463
- Œ: "OE",
464
- œ: "oe",
465
- ù: "u",
466
- ú: "u",
467
- û: "u",
468
- ü: "u",
469
- ű: "u",
470
- ý: "y",
471
- þ: "th",
472
- ÿ: "y",
473
- ẞ: "SS",
474
- α: "a",
475
- β: "b",
476
- γ: "g",
477
- δ: "d",
478
- ε: "e",
479
- ζ: "z",
480
- η: "h",
481
- θ: "th",
482
- ι: "i",
483
- κ: "k",
484
- λ: "l",
485
- μ: "m",
486
- ν: "n",
487
- ξ: "3",
488
- ο: "o",
489
- π: "p",
490
- ρ: "r",
491
- σ: "s",
492
- τ: "t",
493
- υ: "y",
494
- φ: "f",
495
- χ: "x",
496
- ψ: "ps",
497
- ω: "w",
498
- ά: "a",
499
- έ: "e",
500
- ί: "i",
501
- ό: "o",
502
- ύ: "y",
503
- ή: "h",
504
- ώ: "w",
505
- ς: "s",
506
- ϊ: "i",
507
- ΰ: "y",
508
- ϋ: "y",
509
- ΐ: "i",
510
- Α: "A",
511
- Β: "B",
512
- Γ: "G",
513
- Δ: "D",
514
- Ε: "E",
515
- Ζ: "Z",
516
- Η: "H",
517
- Θ: "Th",
518
- Ι: "I",
519
- Κ: "K",
520
- Λ: "L",
521
- Μ: "M",
522
- Ν: "N",
523
- Ξ: "3",
524
- Ο: "O",
525
- Π: "P",
526
- Ρ: "R",
527
- Σ: "S",
528
- Τ: "T",
529
- Υ: "Y",
530
- Φ: "F",
531
- Χ: "X",
532
- Ψ: "PS",
533
- Ω: "W",
534
- Ά: "A",
535
- Έ: "E",
536
- Ί: "I",
537
- Ό: "O",
538
- Ύ: "Y",
539
- Ή: "H",
540
- Ώ: "W",
541
- Ϊ: "I",
542
- Ϋ: "Y",
543
- ş: "s",
544
- Ş: "S",
545
- ı: "i",
546
- İ: "I",
547
- ğ: "g",
548
- Ğ: "G",
549
- а: "a",
550
- б: "b",
551
- в: "v",
552
- г: "g",
553
- д: "d",
554
- е: "e",
555
- ё: "yo",
556
- ж: "zh",
557
- з: "z",
558
- и: "i",
559
- й: "j",
560
- к: "k",
561
- л: "l",
562
- м: "m",
563
- н: "n",
564
- о: "o",
565
- п: "p",
566
- р: "r",
567
- с: "s",
568
- т: "t",
569
- у: "u",
570
- ф: "f",
571
- х: "h",
572
- ц: "c",
573
- ч: "ch",
574
- ш: "sh",
575
- щ: "sh",
576
- ъ: "u",
577
- ы: "y",
578
- ь: "",
579
- э: "e",
580
- ю: "yu",
581
- я: "ya",
582
- А: "A",
583
- Б: "B",
584
- В: "V",
585
- Г: "G",
586
- Д: "D",
587
- Е: "E",
588
- Ё: "Yo",
589
- Ж: "Zh",
590
- З: "Z",
591
- И: "I",
592
- Й: "J",
593
- К: "K",
594
- Л: "L",
595
- М: "M",
596
- Н: "N",
597
- О: "O",
598
- П: "P",
599
- Р: "R",
600
- С: "S",
601
- Т: "T",
602
- У: "U",
603
- Ф: "F",
604
- Х: "H",
605
- Ц: "C",
606
- Ч: "Ch",
607
- Ш: "Sh",
608
- Щ: "Sh",
609
- Ъ: "U",
610
- Ы: "Y",
611
- Ь: "",
612
- Э: "E",
613
- Ю: "Yu",
614
- Я: "Ya",
615
- Є: "Ye",
616
- І: "I",
617
- Ї: "Yi",
618
- Ґ: "G",
619
- є: "ye",
620
- і: "i",
621
- ї: "yi",
622
- ґ: "g",
623
- č: "c",
624
- ď: "d",
625
- ě: "e",
626
- ň: "n",
627
- ř: "r",
628
- š: "s",
629
- ť: "t",
630
- ů: "u",
631
- ž: "z",
632
- Č: "C",
633
- Ď: "D",
634
- Ě: "E",
635
- Ň: "N",
636
- Ř: "R",
637
- Š: "S",
638
- Ť: "T",
639
- Ů: "U",
640
- Ž: "Z",
641
- ľ: "l",
642
- ĺ: "l",
643
- ŕ: "r",
644
- Ľ: "L",
645
- Ĺ: "L",
646
- Ŕ: "R",
647
- ą: "a",
648
- ć: "c",
649
- ę: "e",
650
- ł: "l",
651
- ń: "n",
652
- ś: "s",
653
- ź: "z",
654
- ż: "z",
655
- Ą: "A",
656
- Ć: "C",
657
- Ę: "E",
658
- Ł: "L",
659
- Ń: "N",
660
- Ś: "S",
661
- Ź: "Z",
662
- Ż: "Z",
663
- ā: "a",
664
- ē: "e",
665
- ģ: "g",
666
- ī: "i",
667
- ķ: "k",
668
- ļ: "l",
669
- ņ: "n",
670
- ū: "u",
671
- Ā: "A",
672
- Ē: "E",
673
- Ģ: "G",
674
- Ī: "I",
675
- Ķ: "K",
676
- Ļ: "L",
677
- Ņ: "N",
678
- Ū: "U",
679
- أ: "a",
680
- إ: "i",
681
- ب: "b",
682
- ت: "t",
683
- ث: "th",
684
- ج: "g",
685
- ح: "h",
686
- خ: "kh",
687
- د: "d",
688
- ذ: "th",
689
- ر: "r",
690
- ز: "z",
691
- س: "s",
692
- ش: "sh",
693
- ص: "s",
694
- ض: "d",
695
- ط: "t",
696
- ظ: "th",
697
- ع: "aa",
698
- غ: "gh",
699
- ف: "f",
700
- ق: "k",
701
- ك: "k",
702
- ل: "l",
703
- م: "m",
704
- ن: "n",
705
- ه: "h",
706
- و: "o",
707
- ي: "y",
708
- ء: "aa",
709
- ة: "a",
710
- آ: "a",
711
- ا: "a",
712
- پ: "p",
713
- ژ: "zh",
714
- گ: "g",
715
- چ: "ch",
716
- ک: "k",
717
- ی: "i",
718
- ė: "e",
719
- į: "i",
720
- ų: "u",
721
- Ė: "E",
722
- Į: "I",
723
- Ų: "U",
724
- ț: "t",
725
- Ț: "T",
726
- ţ: "t",
727
- Ţ: "T",
728
- ș: "s",
729
- Ș: "S",
730
- ă: "a",
731
- Ă: "A",
732
- Ạ: "A",
733
- Ả: "A",
734
- Ầ: "A",
735
- Ấ: "A",
736
- Ậ: "A",
737
- Ẩ: "A",
738
- Ẫ: "A",
739
- Ằ: "A",
740
- Ắ: "A",
741
- Ặ: "A",
742
- Ẳ: "A",
743
- Ẵ: "A",
744
- Ẹ: "E",
745
- Ẻ: "E",
746
- Ẽ: "E",
747
- Ề: "E",
748
- Ế: "E",
749
- Ệ: "E",
750
- Ể: "E",
751
- Ễ: "E",
752
- Ị: "I",
753
- Ỉ: "I",
754
- Ĩ: "I",
755
- Ọ: "O",
756
- Ỏ: "O",
757
- Ồ: "O",
758
- Ố: "O",
759
- Ộ: "O",
760
- Ổ: "O",
761
- Ỗ: "O",
762
- Ơ: "O",
763
- Ờ: "O",
764
- Ớ: "O",
765
- Ợ: "O",
766
- Ở: "O",
767
- Ỡ: "O",
768
- Ụ: "U",
769
- Ủ: "U",
770
- Ũ: "U",
771
- Ư: "U",
772
- Ừ: "U",
773
- Ứ: "U",
774
- Ự: "U",
775
- Ử: "U",
776
- Ữ: "U",
777
- Ỳ: "Y",
778
- Ỵ: "Y",
779
- Ỷ: "Y",
780
- Ỹ: "Y",
781
- Đ: "D",
782
- ạ: "a",
783
- ả: "a",
784
- ầ: "a",
785
- ấ: "a",
786
- ậ: "a",
787
- ẩ: "a",
788
- ẫ: "a",
789
- ằ: "a",
790
- ắ: "a",
791
- ặ: "a",
792
- ẳ: "a",
793
- ẵ: "a",
794
- ẹ: "e",
795
- ẻ: "e",
796
- ẽ: "e",
797
- ề: "e",
798
- ế: "e",
799
- ệ: "e",
800
- ể: "e",
801
- ễ: "e",
802
- ị: "i",
803
- ỉ: "i",
804
- ĩ: "i",
805
- ọ: "o",
806
- ỏ: "o",
807
- ồ: "o",
808
- ố: "o",
809
- ộ: "o",
810
- ổ: "o",
811
- ỗ: "o",
812
- ơ: "o",
813
- ờ: "o",
814
- ớ: "o",
815
- ợ: "o",
816
- ở: "o",
817
- ỡ: "o",
818
- ụ: "u",
819
- ủ: "u",
820
- ũ: "u",
821
- ư: "u",
822
- ừ: "u",
823
- ứ: "u",
824
- ự: "u",
825
- ử: "u",
826
- ữ: "u",
827
- ỳ: "y",
828
- ỵ: "y",
829
- ỷ: "y",
830
- ỹ: "y",
831
- đ: "d",
832
- Ә: "AE",
833
- ә: "ae",
834
- Ғ: "GH",
835
- ғ: "gh",
836
- Қ: "KH",
837
- қ: "kh",
838
- Ң: "NG",
839
- ң: "ng",
840
- Ү: "UE",
841
- ү: "ue",
842
- Ұ: "U",
843
- ұ: "u",
844
- Һ: "H",
845
- һ: "h",
846
- Ө: "OE",
847
- ө: "oe",
848
- ђ: "dj",
849
- ј: "j",
850
- љ: "lj",
851
- њ: "nj",
852
- ћ: "c",
853
- џ: "dz",
854
- Ђ: "Dj",
855
- Ј: "j",
856
- Љ: "Lj",
857
- Њ: "Nj",
858
- Ћ: "C",
859
- Џ: "Dz",
860
- nj: "nj",
861
- lj: "lj",
862
- Nj: "NJ",
863
- Lj: "LJ",
864
- अ: "a",
865
- आ: "aa",
866
- ए: "e",
867
- ई: "ii",
868
- ऍ: "ei",
869
- ऎ: "ae",
870
- ऐ: "ai",
871
- इ: "i",
872
- ओ: "o",
873
- ऑ: "oi",
874
- ऒ: "oii",
875
- ऊ: "uu",
876
- औ: "ou",
877
- उ: "u",
878
- ब: "B",
879
- भ: "Bha",
880
- च: "Ca",
881
- छ: "Chha",
882
- ड: "Da",
883
- ढ: "Dha",
884
- फ: "Fa",
885
- ग: "Ga",
886
- घ: "Gha",
887
- ग़: "Ghi",
888
- ह: "Ha",
889
- ज: "Ja",
890
- झ: "Jha",
891
- क: "Ka",
892
- ख: "Kha",
893
- ख़: "Khi",
894
- ल: "L",
895
- ळ: "Li",
896
- ऌ: "Li",
897
- ऴ: "Lii",
898
- ॡ: "Lii",
899
- म: "Ma",
900
- न: "Na",
901
- ङ: "Na",
902
- ञ: "Nia",
903
- ण: "Nae",
904
- ऩ: "Ni",
905
- ॐ: "oms",
906
- प: "Pa",
907
- क़: "Qi",
908
- र: "Ra",
909
- ऋ: "Ri",
910
- ॠ: "Ri",
911
- ऱ: "Ri",
912
- स: "Sa",
913
- श: "Sha",
914
- ष: "Shha",
915
- ट: "Ta",
916
- त: "Ta",
917
- ठ: "Tha",
918
- द: "Tha",
919
- थ: "Tha",
920
- ध: "Thha",
921
- ड़: "ugDha",
922
- ढ़: "ugDhha",
923
- व: "Va",
924
- य: "Ya",
925
- य़: "Yi",
926
- ज़: "Za",
927
- ə: "e",
928
- Ə: "E",
929
- ა: "a",
930
- ბ: "b",
931
- გ: "g",
932
- დ: "d",
933
- ე: "e",
934
- ვ: "v",
935
- ზ: "z",
936
- თ: "t",
937
- ი: "i",
938
- კ: "k",
939
- ლ: "l",
940
- მ: "m",
941
- ნ: "n",
942
- ო: "o",
943
- პ: "p",
944
- ჟ: "zh",
945
- რ: "r",
946
- ს: "s",
947
- ტ: "t",
948
- უ: "u",
949
- ფ: "p",
950
- ქ: "k",
951
- ღ: "gh",
952
- ყ: "q",
953
- შ: "sh",
954
- ჩ: "ch",
955
- ც: "ts",
956
- ძ: "dz",
957
- წ: "ts",
958
- ჭ: "ch",
959
- ხ: "kh",
960
- ჯ: "j",
961
- ჰ: "h",
962
- ב: "v",
963
- גּ: "g",
964
- ג: "g",
965
- ד: "d",
966
- דּ: "d",
967
- ה: "h",
968
- ו: "v",
969
- ז: "z",
970
- ח: "h",
971
- ט: "t",
972
- י: "y",
973
- כ: "kh",
974
- ך: "kh",
975
- ל: "l",
976
- מ: "m",
977
- ם: "m",
978
- נ: "n",
979
- ן: "n",
980
- ס: "s",
981
- פ: "f",
982
- ף: "f",
983
- ץ: "ts",
984
- צ: "ts",
985
- ק: "k",
986
- ר: "r",
987
- תּ: "t",
988
- ת: "t"
989
- };
990
- slug.charmap = Object.assign({}, initialCharmap);
991
- slug.multicharmap = Object.assign({}, initialMulticharmap);
992
- slug.defaults = {
993
- charmap: slug.charmap,
994
- mode: "pretty",
995
- modes: {
996
- rfc3986: {
997
- replacement: "-",
998
- remove: null,
999
- lower: true,
1000
- charmap: slug.charmap,
1001
- multicharmap: slug.multicharmap,
1002
- trim: true
1003
- },
1004
- pretty: {
1005
- replacement: "-",
1006
- remove: null,
1007
- lower: true,
1008
- charmap: slug.charmap,
1009
- multicharmap: slug.multicharmap,
1010
- trim: true
1011
- }
1012
- },
1013
- multicharmap: slug.multicharmap,
1014
- fallback: true
1015
- };
1016
- slug.reset = function() {
1017
- slug.defaults.modes.rfc3986.charmap = slug.defaults.modes.pretty.charmap = slug.charmap = slug.defaults.charmap = Object.assign({}, initialCharmap);
1018
- slug.defaults.modes.rfc3986.multicharmap = slug.defaults.modes.pretty.multicharmap = slug.multicharmap = slug.defaults.multicharmap = Object.assign({}, initialMulticharmap);
1019
- defaultLocale = "";
1020
- };
1021
- slug.extend = function(customMap) {
1022
- const keys = Object.keys(customMap);
1023
- const multi = {};
1024
- const single = {};
1025
- for (let i = 0; i < keys.length; i++) if (keys[i].length > 1) multi[keys[i]] = customMap[keys[i]];
1026
- else single[keys[i]] = customMap[keys[i]];
1027
- Object.assign(slug.charmap, single);
1028
- Object.assign(slug.multicharmap, multi);
1029
- };
1030
- slug.setLocale = function(locale) {
1031
- defaultLocale = locales[locale] || {};
1032
- };
1033
- var UnsupportedDocumentTypeError = class extends Error {
1034
- constructor(documentType) {
1035
- super(`Document type ${documentType} is not supported`);
1036
- this.name = "UnsupportedDocumentTypeError";
1037
- }
1038
- static isError(error) {
1039
- return Error.isError(error) && error.name === "UnsupportedDocumentTypeError";
1040
- }
1041
- };
1042
- var DocumentModelNotFoundError = class extends Error {
1043
- documentType;
1044
- name = "DocumentModelNotFoundError";
1045
- constructor(documentType) {
1046
- super(`Document model module for type ${documentType} not found`);
1047
- this.documentType = documentType;
1048
- }
1049
- static isError(error) {
1050
- return Error.isError(error) && error.name === "DocumentModelNotFoundError";
1051
- }
1052
- };
1053
- var DocumentTypeMismatchError = class extends Error {
1054
- constructor(documentId, expectedType, actualType) {
1055
- super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
1056
- }
1057
- };
1058
- var NoSelectedDocumentError = class extends Error {
1059
- constructor() {
1060
- super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
1061
- }
1062
- };
1063
- function resolveUrlPathname(path) {
1064
- return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
1065
- }
1066
- /** Returns the current path without the base path */
1067
- function getPathWithoutBase(path) {
1068
- const basePath = window.ph?.basePath ?? "/";
1069
- return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
1070
- }
1071
- /** Makes a URL component for a node. */
1072
- function makeNodeSlug(node) {
1073
- if (!node) return "";
1074
- const nodeName = node.name;
1075
- if (!nodeName) return slug(node.id);
1076
- return slug(`${nodeName}-${node.id}`);
1077
- }
1078
- /** Extracts the node slug from a path.
1079
- *
1080
- * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
1081
- */
1082
- function extractNodeSlugFromPath(path) {
1083
- const currentPath = getPathWithoutBase(path);
1084
- return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
1085
- }
1086
- /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
1087
- function findUuid(input) {
1088
- if (!input) return void 0;
1089
- 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];
1090
- }
1091
- function extractNodeIdFromSlug(nodeSlug) {
1092
- return findUuid(nodeSlug);
1093
- }
1094
- /** Extracts the drive slug from a path.
1095
- * Used for extracting drive ids from drive slugs in the URL.
1096
- * Expects the path to be in the format `/d/<drive-slug>`.
1097
- */
1098
- function extractDriveSlugFromPath(path) {
1099
- const currentPath = getPathWithoutBase(path);
1100
- return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
1101
- }
1102
- /**
1103
- * Creates a URL string with the given pathname while preserving existing query parameters.
1104
- */
1105
- function createUrlWithPreservedParams(pathname) {
1106
- const search = window.location.search;
1107
- return search ? `${pathname}${search}` : pathname;
1108
- }
1109
- const drivesEventFunctions = makePHEventFunctions("drives");
1110
- /** Returns all of the drives in the reactor */
1111
- const useDrives = drivesEventFunctions.useValue;
1112
- /** Sets the drives in the reactor */
1113
- const setDrives = drivesEventFunctions.setValue;
1114
- drivesEventFunctions.addEventHandler;
1115
- const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
1116
- const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
1117
- const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
1118
- selectedNodeIdEventFunctions.addEventHandler;
1119
- /** Sets the selected node (file or folder). */
1120
- function setSelectedNode(nodeOrNodeSlug) {
1121
- const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
1122
- setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
1123
- const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
1124
- if (!driveSlugFromPath) return;
1125
- if (!nodeSlug) {
1126
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
1127
- if (pathname === window.location.pathname) return;
1128
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1129
- return;
1130
- }
1131
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
1132
- if (pathname === window.location.pathname) return;
1133
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1134
- }
1135
- const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
1136
- /** Returns the selected drive id */
1137
- const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
1138
- /** Sets the selected drive id */
1139
- const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
1140
- selectedDriveIdEventFunctions.addEventHandler;
1141
- /** Returns the selected drive, or undefined if no drive is selected */
1142
- function useSelectedDriveSafe() {
1143
- const selectedDriveId = useSelectedDriveId();
1144
- const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
1145
- const [drive, dispatch] = useDispatch(selectedDrive);
1146
- if (!selectedDrive) return [void 0, void 0];
1147
- return [drive, dispatch];
1148
- }
1149
- function setSelectedDrive(driveOrDriveSlug) {
1150
- const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
1151
- const drives = window.ph?.drives;
1152
- const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
1153
- if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
1154
- if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
1155
- deferDriveSelection(driveSlug);
1156
- return;
1157
- }
1158
- cancelPendingDriveSelection();
1159
- setSelectedDriveId(driveId);
1160
- if (!driveId) {
1161
- const pathname = resolveUrlPathname("/");
1162
- if (pathname === window.location.pathname) return;
1163
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1164
- return;
1165
- }
1166
- const pathname = resolveUrlPathname(`/d/${driveSlug}`);
1167
- if (pathname === window.location.pathname) return;
1168
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1169
- }
1170
- const DEFERRED_DRIVE_TICK_MS = 2e3;
1171
- const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
1172
- function isInitialSyncInFlight() {
1173
- const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
1174
- if (!remotes?.length) return false;
1175
- return remotes.some((remote) => {
1176
- try {
1177
- const snapshot = remote.channel.getConnectionState();
1178
- return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
1179
- } catch {
1180
- return false;
1181
- }
1182
- });
1183
- }
1184
- let pendingHandler;
1185
- let pendingTimeout;
1186
- function cancelPendingDriveSelection() {
1187
- if (pendingHandler) {
1188
- window.removeEventListener("ph:drivesUpdated", pendingHandler);
1189
- pendingHandler = void 0;
1190
- }
1191
- if (pendingTimeout) {
1192
- clearTimeout(pendingTimeout);
1193
- pendingTimeout = void 0;
1194
- }
1195
- }
1196
- function deferDriveSelection(driveSlug) {
1197
- cancelPendingDriveSelection();
1198
- const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
1199
- const handler = () => {
1200
- if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
1201
- cancelPendingDriveSelection();
1202
- setSelectedDrive(driveSlug);
1203
- setSelectedNode(nodeSlug);
1204
- };
1205
- pendingHandler = handler;
1206
- window.addEventListener("ph:drivesUpdated", handler);
1207
- const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
1208
- const scheduleTick = () => {
1209
- pendingTimeout = setTimeout(() => {
1210
- if (Date.now() < deadline && isInitialSyncInFlight()) {
1211
- scheduleTick();
1212
- return;
1213
- }
1214
- cancelPendingDriveSelection();
1215
- const pathname = resolveUrlPathname("/");
1216
- if (pathname === window.location.pathname) return;
1217
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
1218
- }, DEFERRED_DRIVE_TICK_MS);
1219
- };
1220
- scheduleTick();
1221
- }
1222
- /** Sorts nodes by name. */
1223
- function sortNodesByName(nodes) {
1224
- return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
1225
- }
1226
- /** Returns whether a node is a file. */
1227
- function isFileNodeKind(node) {
1228
- if (!node) return false;
1229
- return node.kind.toUpperCase() === "FILE";
1230
- }
1231
- /** Returns whether a node is a folder. */
1232
- function isFolderNodeKind(node) {
1233
- if (!node) return false;
1234
- return node.kind.toUpperCase() === "FOLDER";
1235
- }
1236
- /** Returns the nodes in the selected drive. */
1237
- function useNodesInSelectedDrive() {
1238
- const [selectedDrive] = useSelectedDriveSafe();
1239
- return selectedDrive?.state.global.nodes;
1240
- }
1241
- /** Returns the folder nodes in the selected drive. */
1242
- function useFolderNodesInSelectedDrive() {
1243
- return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
1244
- }
1245
- /** Returns the selected node. */
1246
- function useSelectedNode() {
1247
- const selectedNodeId = useSelectedNodeId();
1248
- return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
1249
- }
1250
- const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
1251
- const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
1252
- const EMPTY_VETRA_PACKAGES = [];
1253
- const noPackageManagerUnsubscribe = () => {};
1254
- /**
1255
- * Returns all of the Vetra packages loaded by the Connect instance.
1256
- *
1257
- * The snapshot and subscription must keep stable identity while no package
1258
- * manager is registered: `useSyncExternalStore` loops when the snapshot
1259
- * changes on every read, which a fresh `[]` does.
1260
- */
1261
- const useVetraPackages = () => {
1262
- const packageManager = useVetraPackageManager();
1263
- return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : noPackageManagerUnsubscribe, () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES);
1264
- };
1265
- vetraPackageManagerFunctions.addEventHandler;
1266
- function useDocumentModelModules() {
1267
- 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);
1268
- }
1269
- /**
1270
- * Resolves a document model module by document type, mirroring the registry's
1271
- * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
1272
- * LATEST version of the type wins (`version ?? 1` as each module's default),
1273
- * with `version` given only an exact match is returned. The reactor resolves
1274
- * modules the same way when a document is created, so metadata read through
1275
- * this hook and the version a creation actually uses cannot disagree.
1276
- */
1277
- function useDocumentModelModuleById(id, version) {
1278
- const documentModelModules = useDocumentModelModules();
1279
- if (!id || !documentModelModules) return void 0;
1280
- let latestModule;
1281
- let latestVersion = -1;
1282
- for (const module of documentModelModules) {
1283
- if (module.documentModel.global.id !== id) continue;
1284
- const moduleVersion = module.version ?? 1;
1285
- if (version !== void 0) {
1286
- if (moduleVersion === version) return module;
1287
- continue;
1288
- }
1289
- if (moduleVersion > latestVersion) {
1290
- latestVersion = moduleVersion;
1291
- latestModule = module;
1292
- }
1293
- }
1294
- return latestModule;
1295
- }
1296
- Error;
1297
- JSON;
1298
- //#endregion
1299
- //#region ../reactor-browser/dist/client-D4bkR4pH.js
1300
- let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
1301
- DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
1302
- DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
1303
- DocumentChangeType["Created"] = "CREATED";
1304
- DocumentChangeType["Deleted"] = "DELETED";
1305
- DocumentChangeType["ParentAdded"] = "PARENT_ADDED";
1306
- DocumentChangeType["ParentRemoved"] = "PARENT_REMOVED";
1307
- DocumentChangeType["Updated"] = "UPDATED";
1308
- return DocumentChangeType;
1309
- }({});
1310
- let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
1311
- PropagationMode["Cascade"] = "CASCADE";
1312
- PropagationMode["Orphan"] = "ORPHAN";
1313
- return PropagationMode;
1314
- }({});
1315
- const PhDocumentFieldsFragmentDoc = gql`
1316
- fragment PHDocumentFields on PHDocument {
1317
- id
1318
- slug
1319
- name
1320
- documentType
1321
- state
1322
- revisionsList {
1323
- scope
1324
- revision
1325
- }
1326
- createdAtUtcIso
1327
- lastModifiedAtUtcIso
1328
- }
1329
- `;
1330
- const DocumentRelationshipFieldsFragmentDoc = gql`
1331
- fragment DocumentRelationshipFields on DocumentRelationship {
1332
- sourceId
1333
- targetId
1334
- relationshipType
1335
- metadata
1336
- createdAt
1337
- updatedAt
1338
- }
1339
- `;
1340
- gql`
1341
- query GetDocumentModels($namespace: String, $paging: PagingInput) {
1342
- documentModels(namespace: $namespace, paging: $paging) {
1343
- items {
1344
- id
1345
- name
1346
- namespace
1347
- version
1348
- specification
1349
- }
1350
- totalCount
1351
- hasNextPage
1352
- hasPreviousPage
1353
- cursor
1354
- }
1355
- }
1356
- `;
1357
- const GetDocumentDocument = gql`
1358
- query GetDocument($identifier: String!, $view: ViewFilterInput) {
1359
- document(identifier: $identifier, view: $view) {
1360
- document {
1361
- ...PHDocumentFields
1362
- }
1363
- childIds
1364
- }
1365
- }
1366
- ${PhDocumentFieldsFragmentDoc}
1367
- `;
1368
- const GetDocumentWithOperationsDocument = gql`
1369
- query GetDocumentWithOperations(
1370
- $identifier: String!
1371
- $view: ViewFilterInput
1372
- $operationsFilter: DocumentOperationsFilterInput
1373
- $operationsPaging: PagingInput
1374
- ) {
1375
- document(identifier: $identifier, view: $view) {
1376
- document {
1377
- ...PHDocumentFields
1378
- operations(filter: $operationsFilter, paging: $operationsPaging) {
1379
- items {
1380
- index
1381
- timestampUtcMs
1382
- hash
1383
- skip
1384
- error
1385
- deniedReason
1386
- id
1387
- action {
1388
- id
1389
- type
1390
- timestampUtcMs
1391
- input
1392
- scope
1393
- context {
1394
- signer {
1395
- user {
1396
- address
1397
- networkId
1398
- chainId
1399
- }
1400
- app {
1401
- name
1402
- key
1403
- }
1404
- signatures
1405
- }
1406
- }
1407
- }
1408
- }
1409
- totalCount
1410
- hasNextPage
1411
- hasPreviousPage
1412
- cursor
1413
- }
1414
- }
1415
- childIds
1416
- }
1417
- }
1418
- ${PhDocumentFieldsFragmentDoc}
1419
- `;
1420
- gql`
1421
- query GetDocumentOutgoingRelationships(
1422
- $sourceIdentifier: String!
1423
- $relationshipType: String!
1424
- $view: ViewFilterInput
1425
- $paging: PagingInput
1426
- ) {
1427
- documentOutgoingRelationships(
1428
- sourceIdentifier: $sourceIdentifier
1429
- relationshipType: $relationshipType
1430
- view: $view
1431
- paging: $paging
1432
- ) {
1433
- items {
1434
- ...PHDocumentFields
1435
- }
1436
- totalCount
1437
- hasNextPage
1438
- hasPreviousPage
1439
- cursor
1440
- }
1441
- }
1442
- ${PhDocumentFieldsFragmentDoc}
1443
- `;
1444
- gql`
1445
- query GetDocumentIncomingRelationships(
1446
- $targetIdentifier: String!
1447
- $relationshipType: String!
1448
- $view: ViewFilterInput
1449
- $paging: PagingInput
1450
- ) {
1451
- documentIncomingRelationships(
1452
- targetIdentifier: $targetIdentifier
1453
- relationshipType: $relationshipType
1454
- view: $view
1455
- paging: $paging
1456
- ) {
1457
- items {
1458
- ...PHDocumentFields
1459
- }
1460
- totalCount
1461
- hasNextPage
1462
- hasPreviousPage
1463
- cursor
1464
- }
1465
- }
1466
- ${PhDocumentFieldsFragmentDoc}
1467
- `;
1468
- gql`
1469
- query GetDocumentOutgoingRelationshipEdges(
1470
- $sourceIdentifier: String!
1471
- $relationshipType: String
1472
- $view: ViewFilterInput
1473
- $paging: PagingInput
1474
- ) {
1475
- documentOutgoingRelationshipEdges(
1476
- sourceIdentifier: $sourceIdentifier
1477
- relationshipType: $relationshipType
1478
- view: $view
1479
- paging: $paging
1480
- ) {
1481
- items {
1482
- ...DocumentRelationshipFields
1483
- }
1484
- totalCount
1485
- hasNextPage
1486
- hasPreviousPage
1487
- cursor
1488
- }
1489
- }
1490
- ${DocumentRelationshipFieldsFragmentDoc}
1491
- `;
1492
- gql`
1493
- query GetDocumentIncomingRelationshipEdges(
1494
- $targetIdentifier: String!
1495
- $relationshipType: String
1496
- $view: ViewFilterInput
1497
- $paging: PagingInput
1498
- ) {
1499
- documentIncomingRelationshipEdges(
1500
- targetIdentifier: $targetIdentifier
1501
- relationshipType: $relationshipType
1502
- view: $view
1503
- paging: $paging
1504
- ) {
1505
- items {
1506
- ...DocumentRelationshipFields
1507
- }
1508
- totalCount
1509
- hasNextPage
1510
- hasPreviousPage
1511
- cursor
1512
- }
1513
- }
1514
- ${DocumentRelationshipFieldsFragmentDoc}
1515
- `;
1516
- gql`
1517
- query FindDocuments(
1518
- $search: SearchFilterInput
1519
- $view: ViewFilterInput
1520
- $paging: PagingInput
1521
- ) {
1522
- findDocuments(search: $search, view: $view, paging: $paging) {
1523
- items {
1524
- ...PHDocumentFields
1525
- }
1526
- totalCount
1527
- hasNextPage
1528
- hasPreviousPage
1529
- cursor
1530
- }
1531
- }
1532
- ${PhDocumentFieldsFragmentDoc}
1533
- `;
1534
- const GetDocumentOperationsDocument = gql`
1535
- query GetDocumentOperations(
1536
- $filter: OperationsFilterInput!
1537
- $paging: PagingInput
1538
- ) {
1539
- documentOperations(filter: $filter, paging: $paging) {
1540
- items {
1541
- index
1542
- timestampUtcMs
1543
- hash
1544
- skip
1545
- error
1546
- deniedReason
1547
- id
1548
- action {
1549
- id
1550
- type
1551
- timestampUtcMs
1552
- input
1553
- scope
1554
- context {
1555
- signer {
1556
- user {
1557
- address
1558
- networkId
1559
- chainId
1560
- }
1561
- app {
1562
- name
1563
- key
1564
- }
1565
- signatures
1566
- }
1567
- }
1568
- }
1569
- }
1570
- totalCount
1571
- hasNextPage
1572
- hasPreviousPage
1573
- cursor
1574
- }
1575
- }
1576
- `;
1577
- gql`
1578
- query GetJobStatus($jobId: String!) {
1579
- jobStatus(jobId: $jobId) {
1580
- id
1581
- status
1582
- result
1583
- error
1584
- createdAt
1585
- completedAt
1586
- }
1587
- }
1588
- `;
1589
- gql`
1590
- query EvaluateActions(
1591
- $documentIdentifier: String!
1592
- $branch: String
1593
- $candidates: [ActionCandidateInput!]!
1594
- ) {
1595
- evaluateActions(
1596
- documentIdentifier: $documentIdentifier
1597
- branch: $branch
1598
- candidates: $candidates
1599
- ) {
1600
- evaluations {
1601
- decision
1602
- reason
1603
- }
1604
- allAllowed
1605
- anyAllowed
1606
- allDenied
1607
- anyDenied
1608
- }
1609
- }
1610
- `;
1611
- gql`
1612
- mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
1613
- createDocument(document: $document, parentIdentifier: $parentIdentifier) {
1614
- ...PHDocumentFields
1615
- }
1616
- }
1617
- ${PhDocumentFieldsFragmentDoc}
1618
- `;
1619
- gql`
1620
- mutation CreateEmptyDocument(
1621
- $documentType: String!
1622
- $parentIdentifier: String
1623
- ) {
1624
- createEmptyDocument(
1625
- documentType: $documentType
1626
- parentIdentifier: $parentIdentifier
1627
- ) {
1628
- ...PHDocumentFields
1629
- }
1630
- }
1631
- ${PhDocumentFieldsFragmentDoc}
1632
- `;
1633
- gql`
1634
- mutation MutateDocument(
1635
- $documentIdentifier: String!
1636
- $actions: [ActionInput!]!
1637
- $branch: String
1638
- ) {
1639
- mutateDocument: execute(
1640
- documentIdentifier: $documentIdentifier
1641
- actions: $actions
1642
- branch: $branch
1643
- ) {
1644
- ...PHDocumentFields
1645
- }
1646
- }
1647
- ${PhDocumentFieldsFragmentDoc}
1648
- `;
1649
- gql`
1650
- mutation MutateDocumentAsync(
1651
- $documentIdentifier: String!
1652
- $actions: [ActionInput!]!
1653
- $branch: String
1654
- ) {
1655
- mutateDocumentAsync: executeAsync(
1656
- documentIdentifier: $documentIdentifier
1657
- actions: $actions
1658
- branch: $branch
1659
- ) {
1660
- id
1661
- status
1662
- result
1663
- error
1664
- createdAt
1665
- completedAt
1666
- }
1667
- }
1668
- `;
1669
- gql`
1670
- mutation RenameDocument(
1671
- $documentIdentifier: String!
1672
- $name: String!
1673
- $branch: String
1674
- ) {
1675
- renameDocument(
1676
- documentIdentifier: $documentIdentifier
1677
- name: $name
1678
- branch: $branch
1679
- ) {
1680
- ...PHDocumentFields
1681
- }
1682
- }
1683
- ${PhDocumentFieldsFragmentDoc}
1684
- `;
1685
- gql`
1686
- mutation SetPreferredEditor(
1687
- $documentIdentifier: String!
1688
- $preferredEditor: String
1689
- $branch: String
1690
- ) {
1691
- setPreferredEditor(
1692
- documentIdentifier: $documentIdentifier
1693
- preferredEditor: $preferredEditor
1694
- branch: $branch
1695
- ) {
1696
- ...PHDocumentFields
1697
- }
1698
- }
1699
- ${PhDocumentFieldsFragmentDoc}
1700
- `;
1701
- gql`
1702
- mutation AddRelationship(
1703
- $sourceIdentifier: String!
1704
- $targetIdentifier: String!
1705
- $relationshipType: String!
1706
- $metadata: JSONObject
1707
- $branch: String
1708
- ) {
1709
- addRelationship(
1710
- sourceIdentifier: $sourceIdentifier
1711
- targetIdentifier: $targetIdentifier
1712
- relationshipType: $relationshipType
1713
- metadata: $metadata
1714
- branch: $branch
1715
- ) {
1716
- ...PHDocumentFields
1717
- }
1718
- }
1719
- ${PhDocumentFieldsFragmentDoc}
1720
- `;
1721
- gql`
1722
- mutation UpdateRelationship(
1723
- $sourceIdentifier: String!
1724
- $targetIdentifier: String!
1725
- $relationshipType: String!
1726
- $metadata: JSONObject
1727
- $branch: String
1728
- ) {
1729
- updateRelationship(
1730
- sourceIdentifier: $sourceIdentifier
1731
- targetIdentifier: $targetIdentifier
1732
- relationshipType: $relationshipType
1733
- metadata: $metadata
1734
- branch: $branch
1735
- ) {
1736
- ...PHDocumentFields
1737
- }
1738
- }
1739
- ${PhDocumentFieldsFragmentDoc}
1740
- `;
1741
- gql`
1742
- mutation RemoveRelationship(
1743
- $sourceIdentifier: String!
1744
- $targetIdentifier: String!
1745
- $relationshipType: String!
1746
- $branch: String
1747
- ) {
1748
- removeRelationship(
1749
- sourceIdentifier: $sourceIdentifier
1750
- targetIdentifier: $targetIdentifier
1751
- relationshipType: $relationshipType
1752
- branch: $branch
1753
- ) {
1754
- ...PHDocumentFields
1755
- }
1756
- }
1757
- ${PhDocumentFieldsFragmentDoc}
1758
- `;
1759
- gql`
1760
- mutation MoveRelationship(
1761
- $sourceParentIdentifier: String!
1762
- $targetParentIdentifier: String!
1763
- $targetIdentifier: String!
1764
- $relationshipType: String!
1765
- $branch: String
1766
- ) {
1767
- moveRelationship(
1768
- sourceParentIdentifier: $sourceParentIdentifier
1769
- targetParentIdentifier: $targetParentIdentifier
1770
- targetIdentifier: $targetIdentifier
1771
- relationshipType: $relationshipType
1772
- branch: $branch
1773
- ) {
1774
- source {
1775
- ...PHDocumentFields
1776
- }
1777
- target {
1778
- ...PHDocumentFields
1779
- }
1780
- }
1781
- }
1782
- ${PhDocumentFieldsFragmentDoc}
1783
- `;
1784
- gql`
1785
- mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {
1786
- deleteDocument(identifier: $identifier, propagate: $propagate)
1787
- }
1788
- `;
1789
- gql`
1790
- mutation DeleteDocuments(
1791
- $identifiers: [String!]!
1792
- $propagate: PropagationMode
1793
- ) {
1794
- deleteDocuments(identifiers: $identifiers, propagate: $propagate)
1795
- }
1796
- `;
1797
- gql`
1798
- subscription DocumentChanges(
1799
- $search: SearchFilterInput
1800
- $view: ViewFilterInput
1801
- ) {
1802
- documentChanges(search: $search, view: $view) {
1803
- type
1804
- documents {
1805
- ...PHDocumentFields
1806
- }
1807
- context {
1808
- parentId
1809
- childId
1810
- }
1811
- }
1812
- }
1813
- ${PhDocumentFieldsFragmentDoc}
1814
- `;
1815
- gql`
1816
- subscription JobChanges($jobId: String!) {
1817
- jobChanges(jobId: $jobId) {
1818
- jobId
1819
- status
1820
- result
1821
- error
1822
- }
1823
- }
1824
- `;
1825
- gql`
1826
- query PollSyncEnvelopes(
1827
- $channelId: String!
1828
- $outboxAck: Int!
1829
- $outboxLatest: Int!
1830
- ) {
1831
- pollSyncEnvelopes(
1832
- channelId: $channelId
1833
- outboxAck: $outboxAck
1834
- outboxLatest: $outboxLatest
1835
- ) {
1836
- envelopes {
1837
- type
1838
- channelMeta {
1839
- id
1840
- }
1841
- operations {
1842
- operation {
1843
- index
1844
- timestampUtcMs
1845
- hash
1846
- skip
1847
- error
1848
- deniedReason
1849
- id
1850
- action {
1851
- id
1852
- type
1853
- timestampUtcMs
1854
- input
1855
- scope
1856
- context {
1857
- signer {
1858
- user {
1859
- address
1860
- networkId
1861
- chainId
1862
- }
1863
- app {
1864
- name
1865
- key
1866
- }
1867
- signatures
1868
- }
1869
- }
1870
- }
1871
- }
1872
- context {
1873
- documentId
1874
- documentType
1875
- scope
1876
- branch
1877
- }
1878
- }
1879
- cursor {
1880
- remoteName
1881
- cursorOrdinal
1882
- lastSyncedAtUtcMs
1883
- }
1884
- key
1885
- dependsOn
1886
- }
1887
- ackOrdinal
1888
- deadLetters {
1889
- documentId
1890
- error
1891
- errorType
1892
- }
1893
- hasMore
1894
- }
1895
- }
1896
- `;
1897
- gql`
1898
- mutation TouchChannel($input: TouchChannelInput!) {
1899
- touchChannel(input: $input) {
1900
- success
1901
- ackOrdinal
1902
- }
1903
- }
1904
- `;
1905
- gql`
1906
- mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
1907
- pushSyncEnvelopes(envelopes: $envelopes)
1908
- }
1909
- `;
1910
- /** Get the source string from a GraphQL document (string or DocumentNode). */
1911
- function getDocumentSource(doc) {
1912
- return typeof doc === "string" ? doc : doc.loc?.source.body ?? "";
1913
- }
1914
- /**
1915
- * Extract the inner selection set of a named field from a GraphQL document source.
1916
- * Returns the `{ ... }` block including braces.
1917
- */
1918
- function extractSelectionSet(doc, fieldName, fallback) {
1919
- const source = getDocumentSource(doc);
1920
- return new RegExp(`${fieldName}\\([^)]*\\)\\s*(\\{[\\s\\S]*\\})\\s*\\}`).exec(source)?.[1] ?? fallback;
1921
- }
1922
- /**
1923
- * Extract the query body and any fragment definitions from a GraphQL document.
1924
- * Returns { body, fragments } where body is the content inside the query `{ ... }`
1925
- * and fragments are any trailing fragment definitions.
1926
- */
1927
- function extractQueryParts(doc, fallbackBody) {
1928
- const source = getDocumentSource(doc);
1929
- const queryMatch = /^[^{]*\{([\s\S]*?)\}\s*(fragment[\s\S]*)?$/.exec(source);
1930
- return {
1931
- body: queryMatch?.[1]?.trim() ?? fallbackBody,
1932
- fragments: queryMatch?.[2]?.trim() ?? ""
1933
- };
1934
- }
1935
- extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
1936
- extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
1937
- //#endregion
1938
- //#region ../reactor-browser/dist/renown-BHxwP7xU.js
1939
- const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
1940
- const RenownInitialUserContext = createContext({ state: "unknown" });
1941
- /** First-render auth as a three-state value; use this to skip a spinner when anonymous. */
1942
- function useRenownInitialAuth() {
1943
- return useContext(RenownInitialUserContext);
1944
- }
1945
- function useRenownInitialUser() {
1946
- const initial = useRenownInitialAuth();
1947
- return initial.state === "authenticated" ? initial.user : void 0;
1948
- }
1949
- const renownEventFunctions = makePHEventFunctions("renown");
1950
- renownEventFunctions.addEventHandler;
1951
- /** Returns the renown instance */
1952
- const useRenown = renownEventFunctions.useValue;
1953
- renownEventFunctions.setValue;
1954
- function jsonEqual(a, b) {
1955
- if (a === b) return true;
1956
- if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false;
1957
- if (Array.isArray(a) !== Array.isArray(b)) return false;
1958
- const ra = a;
1959
- const rb = b;
1960
- const keys = Object.keys(ra).filter((k) => ra[k] !== void 0);
1961
- if (keys.length !== Object.keys(rb).filter((k) => rb[k] !== void 0).length) return false;
1962
- return keys.every((k) => jsonEqual(ra[k], rb[k]));
1963
- }
1964
- function sameUser(a, b) {
1965
- return jsonEqual(a, b);
1966
- }
1967
- function resolveInstanceUser(instance, seed) {
1968
- const restored = instance.user;
1969
- if (restored) return sameUser(seed, restored) ? seed : restored;
1970
- return instance.status === "initial" ? void 0 : seed;
1971
- }
1972
- /** Returns the current user from the renown instance, subscribing to user events */
1973
- function useUser() {
1974
- const renown = useRenown();
1975
- const initialUser = useRenownInitialUser();
1976
- const instance = renown ? renown : void 0;
1977
- const [tracked, setTracked] = useState(() => ({
1978
- instance,
1979
- user: instance ? resolveInstanceUser(instance, initialUser) : initialUser
1980
- }));
1981
- const current = tracked.instance === instance ? tracked : {
1982
- instance,
1983
- user: instance ? resolveInstanceUser(instance, tracked.user ?? initialUser) : tracked.user
1984
- };
1985
- useEffect(() => {
1986
- if (current !== tracked) setTracked(current);
1987
- }, [current, tracked]);
1988
- useEffect(() => {
1989
- if (!instance) return;
1990
- return instance.on("user", (user) => setTracked((prev) => ({
1991
- instance,
1992
- user: sameUser(prev.user, user) ? prev.user : user
1993
- })));
1994
- }, [instance]);
1995
- return instance ? current.user : initialUser ?? current.user;
1996
- }
1997
- //#endregion
1998
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
1999
- function e$8(e, t, n) {
2000
- let r = (n) => e(n, ...t);
2001
- return n === void 0 ? r : Object.assign(r, {
2002
- lazy: n,
2003
- lazyArgs: t
2004
- });
2005
- }
2006
- //#endregion
2007
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js
2008
- function t$5(t, n, r) {
2009
- let i = t.length - n.length;
2010
- if (i === 0) return t(...n);
2011
- if (i === 1) return e$8(t, n, r);
2012
- throw Error(`Wrong number of arguments`);
2013
- }
2014
- //#endregion
2015
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/allPass.js
2016
- function t$4(...t) {
2017
- return t$5(n$4, t);
2018
- }
2019
- const n$4 = (e, t) => t.every((t) => t(e));
2020
- //#endregion
2021
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/conditional-CTEJD5TX.js
2022
- function e$7(e, t, n) {
2023
- return e(n[0]) ? (e) => t(e, ...n) : t(...n);
2024
- }
2025
- function t$3(...t) {
2026
- return e$7(r, n$3, t);
2027
- }
2028
- function n$3(e, ...t) {
2029
- for (let n of t) {
2030
- if (typeof n == `function`) return n(e);
2031
- let [t, r] = n;
2032
- if (t(e)) return r(e);
2033
- }
2034
- throw Error(`conditional: data failed for all cases`);
2035
- }
2036
- function r(e) {
2037
- if (!Array.isArray(e)) return !1;
2038
- let [t, n, ...r] = e;
2039
- return typeof t == `function` && t.length <= 1 && typeof n == `function` && n.length <= 1 && r.length === 0;
2040
- }
2041
- //#endregion
2042
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/constant.js
2043
- function e$6(e) {
2044
- return () => e;
2045
- }
2046
- //#endregion
2047
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js
2048
- function t$2(...t) {
2049
- return t$5(n$2, t);
2050
- }
2051
- const n$2 = (e, t) => e.length >= t;
2052
- //#endregion
2053
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js
2054
- const e$5 = Symbol(`funnel/voidReducer`), t$1 = () => e$5;
2055
- function n$1(n, { triggerAt: r = `end`, minQuietPeriodMs: i, maxBurstDurationMs: a, minGapMs: o, reducer: s = t$1 }) {
2056
- let c, l, u, d, f = () => {
2057
- let t = u;
2058
- t !== void 0 && (u = void 0, t === e$5 ? n() : n(t), o !== void 0 && (l = setTimeout(p, o)));
2059
- }, p = () => {
2060
- clearTimeout(l), l = void 0, c === void 0 && f();
2061
- }, m = () => {
2062
- clearTimeout(c), c = void 0, d = void 0, l === void 0 && f();
2063
- };
2064
- return {
2065
- call: (...e) => {
2066
- let t = c === void 0 && l === void 0;
2067
- if ((r !== `start` || t) && (u = s(u, ...e)), !(c === void 0 && !t)) {
2068
- if (i !== void 0 || a !== void 0 || o === void 0) {
2069
- clearTimeout(c);
2070
- let e = Date.now();
2071
- d ??= e;
2072
- let t = a === void 0 ? i ?? 0 : Math.min(i ?? a, Math.max(0, a - (e - d)));
2073
- c = setTimeout(m, t);
2074
- }
2075
- r !== `end` && t && f();
2076
- }
2077
- },
2078
- cancel: () => {
2079
- clearTimeout(c), c = void 0, d = void 0, clearTimeout(l), l = void 0, u = void 0;
2080
- },
2081
- flush: () => {
2082
- m(), p();
2083
- },
2084
- get isIdle() {
2085
- return c === void 0 && l === void 0;
2086
- }
2087
- };
2088
- }
2089
- //#endregion
2090
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js
2091
- function e$4(e) {
2092
- return e !== void 0;
2093
- }
2094
- //#endregion
2095
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isNot.js
2096
- function e$3(e) {
2097
- return (t) => !e(t);
2098
- }
2099
- //#endregion
2100
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isStrictEqual.js
2101
- function t(...t) {
2102
- return t$5(n, t);
2103
- }
2104
- const n = (e, t) => e === t || Object.is(e, t);
2105
- //#endregion
2106
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isString.js
2107
- function e$2(e) {
2108
- return typeof e == `string`;
2109
- }
2110
- //#endregion
2111
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isTruthy.js
2112
- function e$1(e) {
2113
- return !!e;
2114
- }
2115
- //#endregion
2116
- //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/once.js
2117
- function e(e) {
2118
- let t = !1, n;
2119
- return () => (t ||= (n = e(), !0), n);
2120
- }
2121
- var CloseCode = /* @__PURE__ */ ((CloseCode2) => {
2122
- CloseCode2[CloseCode2["InternalServerError"] = 4500] = "InternalServerError";
2123
- CloseCode2[CloseCode2["InternalClientError"] = 4005] = "InternalClientError";
2124
- CloseCode2[CloseCode2["BadRequest"] = 4400] = "BadRequest";
2125
- CloseCode2[CloseCode2["BadResponse"] = 4004] = "BadResponse";
2126
- CloseCode2[CloseCode2["Unauthorized"] = 4401] = "Unauthorized";
2127
- CloseCode2[CloseCode2["Forbidden"] = 4403] = "Forbidden";
2128
- CloseCode2[CloseCode2["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
2129
- CloseCode2[CloseCode2["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
2130
- CloseCode2[CloseCode2["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
2131
- CloseCode2[CloseCode2["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
2132
- CloseCode2[CloseCode2["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
2133
- return CloseCode2;
2134
- })(CloseCode || {});
2135
- var MessageType = /* @__PURE__ */ ((MessageType2) => {
2136
- MessageType2["ConnectionInit"] = "connection_init";
2137
- MessageType2["ConnectionAck"] = "connection_ack";
2138
- MessageType2["Ping"] = "ping";
2139
- MessageType2["Pong"] = "pong";
2140
- MessageType2["Subscribe"] = "subscribe";
2141
- MessageType2["Next"] = "next";
2142
- MessageType2["Error"] = "error";
2143
- MessageType2["Complete"] = "complete";
2144
- return MessageType2;
2145
- })(MessageType || {});
2146
- Error;
2147
- //#endregion
2148
- //#region ../reactor-browser/dist/document-operations-Cm4EtaZs.js
2149
- const modalEventFunctions = makePHEventFunctions("modal");
2150
- modalEventFunctions.useValue;
2151
- /** Sets the current modal */
2152
- const setPHModal = modalEventFunctions.setValue;
2153
- modalEventFunctions.addEventHandler;
2154
- /** Shows a modal */
2155
- function showPHModal(modal) {
2156
- setPHModal(modal);
2157
- }
2158
- /** Shows the delete node modal */
2159
- function showDeleteNodeModal(nodeOrId) {
2160
- setPHModal({
2161
- type: "deleteItem",
2162
- id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2163
- });
2164
- }
2165
- function isDocumentTypeSupported(documentType, supportedDocuments) {
2166
- if (!supportedDocuments?.length) return true;
2167
- return supportedDocuments.some((pattern) => {
2168
- if (pattern.endsWith("/*")) {
2169
- const prefix = pattern.slice(0, -2);
2170
- return documentType.startsWith(prefix + "/");
2171
- }
2172
- if (pattern.endsWith("*") && !pattern.endsWith("/*")) {
2173
- const prefix = pattern.slice(0, -1);
2174
- return documentType.startsWith(prefix);
2175
- }
2176
- return pattern === documentType;
2177
- });
2178
- }
2179
- function getUserPermissions() {
2180
- const user = window.ph?.renown?.user;
2181
- const allowList = window.ph?.allowList;
2182
- if (!allowList) return {
2183
- isAllowedToCreateDocuments: true,
2184
- isAllowedToEditDocuments: true
2185
- };
2186
- return {
2187
- isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
2188
- isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2189
- };
2190
- }
2191
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2192
- /** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */
2193
- async function isDocumentInLocation(reactorClient, document, driveId, parentFolder) {
2194
- const drive = await reactorClient.get(driveId);
2195
- const nodeById = drive.state.global.nodes.find((node) => node.id === document.header.id);
2196
- if (nodeById && nodeById.parentFolder === (parentFolder ?? null)) return {
2197
- isDuplicate: true,
2198
- duplicateType: "id",
2199
- nodeId: nodeById.id
2200
- };
2201
- const nodeByNameAndType = drive.state.global.nodes.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType && node.parentFolder === (parentFolder ?? null));
2202
- if (nodeByNameAndType) return {
2203
- isDuplicate: true,
2204
- duplicateType: "name",
2205
- nodeId: nodeByNameAndType.id
2206
- };
2207
- return { isDuplicate: false };
2208
- }
2209
- function getDocumentTypeIcon(document) {
2210
- switch (document.header.documentType) {
2211
- case "powerhouse/document-model": return "document-model";
2212
- case "powerhouse/app": return "app";
2213
- case "powerhouse/document-editor": return "editor";
2214
- case "powerhouse/subgraph": return "subgraph";
2215
- case "powerhouse/package": return "package";
2216
- case "powerhouse/processor": {
2217
- const processorType = document.state.global?.type;
2218
- if (processorType === "analytics") return "analytics-processor";
2219
- if (processorType === "relational") return "relational-processor";
2220
- if (processorType === "codegen") return "codegen-processor";
2221
- return;
2222
- }
2223
- default: return;
2224
- }
2225
- }
2226
- async function downloadFile(document, fileName) {
2227
- try {
2228
- const data = await createZip(document);
2229
- const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
2230
- const link = window.document.createElement("a");
2231
- link.style.display = "none";
2232
- link.href = URL.createObjectURL(blob);
2233
- link.download = fileName;
2234
- window.document.body.appendChild(link);
2235
- link.click();
2236
- window.document.body.removeChild(link);
2237
- } catch (e) {
2238
- logger.error(e instanceof Error ? e.message : String(e));
2239
- }
2240
- }
2241
- async function getDocumentExtension(document) {
2242
- const documentType = document.header.documentType;
2243
- let rawExtension;
2244
- if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2245
- else {
2246
- const reactorClient = window.ph?.reactorClientModule?.client;
2247
- if (reactorClient) {
2248
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2249
- rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
2250
- }
2251
- }
2252
- return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
2253
- }
2254
- /**
2255
- * Fetches all operations for a document using cursor-based pagination.
2256
- * The reactor client handles multi-scope cursors transparently via
2257
- * composite cursors, so all scopes are fetched in a single paginated stream.
2258
- */
2259
- async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2260
- const scopes = Object.keys(document.state);
2261
- const operations = {};
2262
- for (const scope of scopes) operations[scope] = [];
2263
- let cursor = "";
2264
- do {
2265
- const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
2266
- cursor,
2267
- limit: pageSize
2268
- });
2269
- for (const op of page.results) {
2270
- const scope = op.action.scope ?? "global";
2271
- if (operations[scope]) operations[scope].push(op);
2272
- }
2273
- cursor = page.nextCursor ?? "";
2274
- } while (cursor);
2275
- return operations;
2276
- }
2277
- function extractInitialState(documentScopeOps) {
2278
- const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
2279
- if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
2280
- const input = upgradeOp.action.input;
2281
- const initialState = input.initialState ?? input.state;
2282
- if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
2283
- return initialState;
2284
- }
2285
- function filterDomainOperations(operations) {
2286
- return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2287
- }
2288
- function countOperations(operations) {
2289
- let total = 0;
2290
- for (const ops of Object.values(operations)) total += ops?.length ?? 0;
2291
- return total;
2292
- }
2293
- /**
2294
- * Split an imported document's domain operations at its mid-history upgrade
2295
- * boundaries, so the caller can re-dispatch each upgrade between segments.
2296
- *
2297
- * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
2298
- * path and must not be repeated. A later upgrade must be: it is where the
2299
- * reducer version changes, and dropping it replays everything after it through
2300
- * the module the document was created with.
2301
- */
2302
- function splitAtUpgradeBoundaries(operations) {
2303
- const upgrades = (operations.document ?? []).filter((op) => op.action.type === "UPGRADE_DOCUMENT").filter((op) => op.action.input.fromVersion > 0).sort((a, b) => a.index - b.index);
2304
- const domain = filterDomainOperations(operations);
2305
- if (upgrades.length === 0) return [{ operations: domain }];
2306
- const segments = [];
2307
- const consumed = /* @__PURE__ */ new Map();
2308
- const take = (until) => {
2309
- const slice = {};
2310
- for (const [scope, ops] of Object.entries(domain)) {
2311
- if (!ops) continue;
2312
- const from = consumed.get(scope) ?? 0;
2313
- const stop = Math.max(from, until(scope, ops));
2314
- const chunk = ops.slice(from, stop);
2315
- if (chunk.length > 0) slice[scope] = chunk;
2316
- consumed.set(scope, stop);
2317
- }
2318
- return slice;
2319
- };
2320
- for (const upgrade of upgrades) {
2321
- const input = upgrade.action.input;
2322
- const slice = take((scope, ops) => boundary(upgrade, scope, ops));
2323
- segments.push({
2324
- operations: slice,
2325
- upgradeTo: input.toVersion
2326
- });
2327
- }
2328
- const tail = take((_scope, ops) => ops.length);
2329
- if (countOperations(tail) > 0) segments.push({ operations: tail });
2330
- return segments;
2331
- }
2332
- /**
2333
- * How many of a scope's operations precede an upgrade. Must stay identical to
2334
- * the boundary computation in `replayDocumentVersioned` — snapshots compare
2335
- * against operation indices, not array positions, and the timestamp fallback
2336
- * excludes the upgrade's own instant.
2337
- */
2338
- function boundary(upgrade, scope, ops) {
2339
- const snapshot = upgrade.action.input.revision;
2340
- if (snapshot !== void 0) {
2341
- const revision = snapshot[scope] ?? 0;
2342
- let count = 0;
2343
- for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
2344
- return count;
2345
- }
2346
- for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
2347
- return ops.length;
2348
- }
2349
- async function exportFile(document, suggestedName) {
2350
- const reactorClient = window.ph?.reactorClient;
2351
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2352
- const operations = await fetchDocumentOperations(reactorClient, document);
2353
- const initialState = extractInitialState(operations["document"] ?? []);
2354
- const documentWithOps = {
2355
- ...document,
2356
- operations,
2357
- initialState
2358
- };
2359
- const extension = await getDocumentExtension(documentWithOps);
2360
- const baseName = suggestedName || documentWithOps.header.name || "Untitled";
2361
- const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
2362
- if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
2363
- try {
2364
- const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
2365
- await baseSaveToFileHandle(documentWithOps, fileHandle);
2366
- return fileHandle;
2367
- } catch (e) {
2368
- if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
2369
- }
2370
- }
2371
- /**
2372
- * Loads a document file and replays it with version-aware reducers from the registry.
2373
- * Falls back to single-version legacy replay when no upgrade manifest is registered for
2374
- * the document type.
2375
- */
2376
- async function loadFile(path) {
2377
- const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2378
- const reactorClient = window.ph?.reactorClientModule?.client;
2379
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2380
- const documentType = baseDocument.header.documentType;
2381
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2382
- const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
2383
- if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
2384
- const reducers = {};
2385
- for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
2386
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2387
- let upgradeManifest;
2388
- if (registry) try {
2389
- upgradeManifest = registry.getUpgradeManifest(documentType);
2390
- } catch {}
2391
- return baseLoadFromInputVersioned(path, {
2392
- reducers,
2393
- upgradeManifest
2394
- });
2395
- }
2396
- async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
2397
- const { isAllowedToCreateDocuments } = getUserPermissions();
2398
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2399
- const reactorClient = window.ph?.reactorClientModule?.client;
2400
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2401
- let documentModelModule;
2402
- if (documentModelVersion !== void 0) {
2403
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2404
- const module = documentModelModules.find((m) => m.documentModel.global.id === documentType && (m.version ?? 1) === documentModelVersion);
2405
- if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
2406
- documentModelModule = module;
2407
- } else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2408
- const newDocument = document ?? documentModelModule.utils.createDocument();
2409
- if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
2410
- newDocument.header.name = name;
2411
- if (preferredEditor) newDocument.header.meta = {
2412
- ...newDocument.header.meta,
2413
- preferredEditor
2414
- };
2415
- let newDoc;
2416
- try {
2417
- newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2418
- } catch (e) {
2419
- logger.error("Error adding document: @error", e);
2420
- throw new Error("There was an error adding document", { cause: e });
2421
- }
2422
- return {
2423
- id: newDoc.header.id,
2424
- name: newDoc.header.name,
2425
- documentType,
2426
- parentFolder: parentFolder ?? null,
2427
- kind: "file"
2428
- };
2429
- }
2430
- /**
2431
- * How many ids an import will try before giving up. The check before the create
2432
- * catches an id that is already taken; this bound covers the window between the
2433
- * two, where a create can still lose to a claim made in the meantime.
2434
- */
2435
- const IMPORT_ID_ATTEMPTS = 3;
2436
- /** True when this error, or anything it wraps, is a taken document id. */
2437
- function isDocumentAlreadyExists(error) {
2438
- let current = error;
2439
- while (current instanceof Error) {
2440
- if (current.name === "DocumentAlreadyExistsError") return true;
2441
- current = current.cause;
2442
- }
2443
- return false;
2444
- }
2445
- /**
2446
- * Creates the imported document under an id that is free, retrying on a
2447
- * collision.
2448
- *
2449
- * The check cannot stand on its own: it answers for the moment it ran, and the
2450
- * create that follows can still land on an id claimed in between. The store
2451
- * rejects that create as DocumentAlreadyExistsError, which is not retryable
2452
- * under the same id and is resolved by minting another one. A create that
2453
- * fails leaves the drive untouched, so a retry has nothing to clean up.
2454
- */
2455
- async function createImportedDocument(reactor, document, driveId, name, parentFolder) {
2456
- let documentId = await reactor.isDocumentIdTaken(document.header.id) ? generateId() : document.header.id;
2457
- for (let attempt = 1;; attempt++) {
2458
- const header = createPresignedHeader(documentId, document.header.documentType);
2459
- header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2460
- header.meta = document.header.meta;
2461
- header.name = name || document.header.name;
2462
- const initialDocument = {
2463
- ...document,
2464
- header,
2465
- state: document.initialState,
2466
- operations: Object.keys(document.operations).reduce((acc, key) => {
2467
- acc[key] = [];
2468
- return acc;
2469
- }, {})
2470
- };
2471
- try {
2472
- const fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2473
- if (!fileNode) throw new Error("There was an error adding file");
2474
- return {
2475
- documentId,
2476
- fileNode
2477
- };
2478
- } catch (error) {
2479
- if (!isDocumentAlreadyExists(error) || attempt === IMPORT_ID_ATTEMPTS) throw error;
2480
- logger.warn(`Document id ${documentId} was taken between the check and the create; importing under a new id`);
2481
- documentId = generateId();
2482
- }
2483
- }
2484
- }
2485
- async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
2486
- logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2487
- const reactor = window.ph?.reactorClientModule?.client;
2488
- if (!reactor) {
2489
- onProgress?.({
2490
- stage: "failed",
2491
- progress: 100,
2492
- error: "ReactorClient not initialized"
2493
- });
2494
- throw new Error("ReactorClient not initialized");
2495
- }
2496
- const { isAllowedToCreateDocuments } = getUserPermissions();
2497
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2498
- try {
2499
- onProgress?.({
2500
- stage: "loading",
2501
- progress: 0
2502
- });
2503
- let document;
2504
- try {
2505
- document = await loadFile(file);
2506
- } catch (loadError) {
2507
- if (UnsupportedDocumentModelVersionError.isError(loadError)) {
2508
- showPHModal({
2509
- type: "documentVersionUnsupported",
2510
- documentType: loadError.documentType,
2511
- requiredVersion: loadError.requiredVersion,
2512
- availableVersions: loadError.availableVersions
2513
- });
2514
- onProgress?.({
2515
- stage: "failed",
2516
- progress: 100,
2517
- error: loadError.message
2518
- });
2519
- return;
2520
- }
2521
- const discoveryService = window.ph?.packageDiscoveryService;
2522
- if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
2523
- retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict).catch((retryError) => {
2524
- logger.error("Import retry after discovery failed: @error", retryError);
2525
- onProgress?.({
2526
- stage: "failed",
2527
- progress: 100,
2528
- error: retryError instanceof Error ? retryError.message : String(retryError)
2529
- });
2530
- });
2531
- return;
2532
- }
2533
- throw loadError;
2534
- }
2535
- const duplicateCheck = await isDocumentInLocation(reactor, document, driveId, parentFolder);
2536
- if (duplicateCheck.isDuplicate && !resolveConflict) {
2537
- onProgress?.({
2538
- stage: "conflict",
2539
- progress: 0,
2540
- duplicateType: duplicateCheck.duplicateType
2541
- });
2542
- return;
2543
- }
2544
- const documentType = getDocumentTypeIcon(document);
2545
- if (documentType) onProgress?.({
2546
- stage: "loading",
2547
- progress: 10,
2548
- documentType
2549
- });
2550
- else onProgress?.({
2551
- stage: "loading",
2552
- progress: 10
2553
- });
2554
- if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {
2555
- onProgress?.({
2556
- stage: "unsupported-document-type",
2557
- progress: 100,
2558
- error: `Document type ${document.header.documentType} is not supported`
2559
- });
2560
- throw new UnsupportedDocumentTypeError(document.header.documentType);
2561
- }
2562
- await reactor.getDocumentModelModule(document.header.documentType);
2563
- onProgress?.({
2564
- stage: "initializing",
2565
- progress: 10
2566
- });
2567
- const created = await createImportedDocument(reactor, document, driveId, name, parentFolder);
2568
- const documentId = created.documentId;
2569
- const fileNode = created.fileNode;
2570
- onProgress?.({
2571
- stage: "initializing",
2572
- progress: 20
2573
- });
2574
- await reactor.get(documentId);
2575
- console.log("Document created, starting upload of operations");
2576
- const segments = splitAtUpgradeBoundaries(document.operations);
2577
- const totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);
2578
- let uploadedBefore = 0;
2579
- for (const segment of segments) {
2580
- await uploadOperations(documentId, segment.operations, queueOperations, { onProgress: (uploadProgress) => {
2581
- if (uploadProgress.uploadedOperations === void 0) return;
2582
- const uploaded = uploadedBefore + uploadProgress.uploadedOperations;
2583
- const uploadPercent = totalOperations > 0 ? uploaded / totalOperations : 0;
2584
- onProgress?.({
2585
- stage: "uploading",
2586
- progress: 20 + Math.round(uploadPercent * 80),
2587
- totalOperations,
2588
- uploadedOperations: uploaded
2589
- });
2590
- } });
2591
- uploadedBefore += countOperations(segment.operations);
2592
- if (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);
2593
- }
2594
- onProgress?.({
2595
- stage: "complete",
2596
- progress: 100,
2597
- fileNode
2598
- });
2599
- return fileNode;
2600
- } catch (error) {
2601
- if (!UnsupportedDocumentTypeError.isError(error)) {
2602
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
2603
- onProgress?.({
2604
- stage: "failed",
2605
- progress: 100,
2606
- error: errorMessage
2607
- });
2608
- }
2609
- throw error;
2610
- }
2611
- }
2612
- async function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
2613
- if (!discoveryService) return;
2614
- try {
2615
- await discoveryService.load(documentType);
2616
- } catch {
2617
- onProgress?.({
2618
- stage: "unsupported-document-type",
2619
- progress: 100,
2620
- error: `Document type ${documentType} is not supported`
2621
- });
2622
- return;
2623
- }
2624
- await addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
2625
- }
2626
- async function addFolder$1(driveId, name, parentFolder) {
2627
- const { isAllowedToCreateDocuments } = getUserPermissions();
2628
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2629
- const reactorClient = window.ph?.reactorClient;
2630
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2631
- await reactorClient.get(driveId);
2632
- const folderId = generateId();
2633
- const node = (await reactorClient.execute(driveId, "main", [addFolder({
2634
- id: folderId,
2635
- name,
2636
- parentFolder
2637
- })])).state.global.nodes.find((node) => node.id === folderId);
2638
- if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2639
- return node;
2640
- }
2641
- async function renameNode(driveId, nodeId, name) {
2642
- const { isAllowedToCreateDocuments } = getUserPermissions();
2643
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2644
- const reactorClient = window.ph?.reactorClient;
2645
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2646
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2647
- const node = (await reactorClient.execute(driveId, "main", [updateNode({
2648
- id: nodeId,
2649
- name
2650
- })])).state.global.nodes.find((n) => n.id === nodeId);
2651
- if (!node) throw new Error("There was an error renaming node in the drive");
2652
- return node;
2653
- }
2654
- async function renameDriveNode(driveId, nodeId, name) {
2655
- const { isAllowedToCreateDocuments } = getUserPermissions();
2656
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2657
- const reactorClient = window.ph?.reactorClient;
2658
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2659
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2660
- await reactorClient.execute(driveId, "main", [updateNode({
2661
- id: nodeId,
2662
- name
2663
- })]);
2664
- return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2665
- }
2666
- async function moveNodeById(args) {
2667
- const { driveId, srcId, targetId } = args;
2668
- if (!driveId || !srcId) return;
2669
- const { isAllowedToCreateDocuments } = getUserPermissions();
2670
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2671
- const reactorClient = window.ph?.reactorClient;
2672
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2673
- const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2674
- if (t(targetParentFolder, srcId)) return;
2675
- return await reactorClient.execute(driveId, "main", [moveNode({
2676
- srcFolder: srcId,
2677
- targetParentFolder
2678
- })]);
2679
- }
2680
- async function moveNode$1(driveId, src, target) {
2681
- const { isAllowedToCreateDocuments } = getUserPermissions();
2682
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2683
- const reactorClient = window.ph?.reactorClient;
2684
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2685
- return await reactorClient.execute(driveId, "main", [moveNode({
2686
- srcFolder: src.id,
2687
- targetParentFolder: target?.id
2688
- })]);
2689
- }
2690
- /**
2691
- * Duplicates a document under a new id using version-aware replay.
2692
- * Falls back gracefully when no upgrade manifest is registered for the document type.
2693
- */
2694
- async function _duplicateDocument(reactor, document, newId = generateId()) {
2695
- const documentType = document.header.documentType;
2696
- const { results: allModules } = await reactor.getDocumentModelModules();
2697
- const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2698
- const reducers = {};
2699
- for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2700
- if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2701
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2702
- let upgradeManifest;
2703
- if (registry) try {
2704
- upgradeManifest = registry.getUpgradeManifest(documentType);
2705
- } catch {}
2706
- const config = {
2707
- reducers,
2708
- upgradeManifest
2709
- };
2710
- const header = createPresignedHeader(newId, documentType);
2711
- const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2712
- assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2713
- return duplicated;
2714
- }
2715
- async function copyNode$1(driveId, src, target) {
2716
- const reactor = window.ph?.reactorClientModule?.client;
2717
- if (!reactor) return;
2718
- const { isAllowedToCreateDocuments } = getUserPermissions();
2719
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2720
- const drive = await reactor.get(driveId);
2721
- const copyNodesInput = generateNodesCopy({
2722
- srcId: src.id,
2723
- targetParentFolder: target?.id,
2724
- targetName: src.name
2725
- }, () => generateId(), drive.state.global.nodes);
2726
- const resolvedNamesMap = /* @__PURE__ */ new Map();
2727
- for (const copyNodeInput of copyNodesInput) {
2728
- const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2729
- if (node) {
2730
- const resolvedName = handleTargetNameCollisions({
2731
- nodes: drive.state.global.nodes,
2732
- srcName: copyNodeInput.targetName || node.name,
2733
- srcKind: isFileNode(node) ? "file" : "folder",
2734
- targetParentFolder: copyNodeInput.targetParentFolder || null
2735
- });
2736
- resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2737
- }
2738
- }
2739
- const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2740
- const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2741
- return node !== void 0 && isFileNode(node);
2742
- });
2743
- for (const fileNodeToCopy of fileNodesToCopy) try {
2744
- const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2745
- const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2746
- if (resolvedName) duplicatedDocument.header.name = resolvedName;
2747
- await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2748
- } catch (e) {
2749
- logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2750
- }
2751
- return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2752
- }
2753
- gql`
2754
- mutation MutateDocumentWithOperations(
2755
- $documentIdentifier: String!
2756
- $actions: [ActionInput!]!
2757
- $sinceRevision: Int
2758
- $scopes: [String!]
2759
- $branch: String
2760
- ) {
2761
- mutateDocument: execute(
2762
- documentIdentifier: $documentIdentifier
2763
- actions: $actions
2764
- branch: $branch
2765
- ) {
2766
- ...PHDocumentFields
2767
- operations(
2768
- filter: {
2769
- sinceRevision: $sinceRevision
2770
- scopes: $scopes
2771
- branch: $branch
2772
- }
2773
- ) {
2774
- items {
2775
- ...ReactorOperationFields
2776
- }
2777
- }
2778
- }
2779
- }
2780
- ${PhDocumentFieldsFragmentDoc}
2781
- ${gql`
2782
- fragment ReactorOperationFields on ReactorOperation {
2783
- index
2784
- timestampUtcMs
2785
- hash
2786
- skip
2787
- error
2788
- deniedReason
2789
- id
2790
- action {
2791
- id
2792
- type
2793
- timestampUtcMs
2794
- input
2795
- scope
2796
- context {
2797
- signer {
2798
- user {
2799
- address
2800
- networkId
2801
- chainId
2802
- }
2803
- app {
2804
- name
2805
- key
2806
- }
2807
- signatures
2808
- }
2809
- }
2810
- }
2811
- }
2812
- `}
2813
- `;
2814
- DocumentChangeType.Created, DOCUMENT_CHANGE_TYPE.Created, DocumentChangeType.Deleted, DOCUMENT_CHANGE_TYPE.Deleted, DocumentChangeType.Updated, DOCUMENT_CHANGE_TYPE.Updated, DocumentChangeType.ParentAdded, DOCUMENT_CHANGE_TYPE.ParentAdded, DocumentChangeType.ParentRemoved, DOCUMENT_CHANGE_TYPE.ParentRemoved, DocumentChangeType.ChildAdded, DOCUMENT_CHANGE_TYPE.ChildAdded, DocumentChangeType.ChildRemoved, DOCUMENT_CHANGE_TYPE.ChildRemoved;
2815
- PropagationMode.Cascade, PropagationMode.Orphan;
2816
- const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2817
- /** Sets whether external controls are enabled for a given editor. */
2818
- const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2819
- /** Gets whether external controls are enabled for a given editor. */
2820
- const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2821
- isExternalControlsEnabledEventFunctions.addEventHandler;
2822
- const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2823
- /** Sets whether drag and drop is enabled for a given app. */
2824
- const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2825
- /** Gets whether drag and drop is enabled for a given app. */
2826
- const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2827
- isDragAndDropEnabledEventFunctions.addEventHandler;
2828
- const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2829
- /** Sets the allowed document types for a given app. */
2830
- const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2831
- /** Defines the document types a drive supports.
2832
- *
2833
- * Defaults to all of the document types registered in the reactor.
2834
- */
2835
- function useAllowedDocumentTypes() {
2836
- return allowedDocumentTypesEventFunctions.useValue();
2837
- }
2838
- allowedDocumentTypesEventFunctions.addEventHandler;
2839
- const phAppConfigSetters = {
2840
- allowedDocumentTypes: setAllowedDocumentTypes,
2841
- isDragAndDropEnabled: setIsDragAndDropEnabled
2842
- };
2843
- const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
2844
- const phAppConfigHooks = {
2845
- allowedDocumentTypes: useAllowedDocumentTypes,
2846
- isDragAndDropEnabled: useIsDragAndDropEnabled
2847
- };
2848
- const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
2849
- const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
2850
- const { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions("version");
2851
- const { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions("requiresHardRefresh");
2852
- const { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions("warnOutdatedApp");
2853
- const { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions("studioMode");
2854
- const { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions("basePath");
2855
- const { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions("versionCheckInterval");
2856
- const { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions("cliVersion");
2857
- const { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions("fileUploadOperationsChunkSize");
2858
- const { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions("isDocumentModelSelectionSettingsEnabled");
2859
- const { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions("gaTrackingId");
2860
- const { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions("defaultDrivesUrl");
2861
- const { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions("drivesPreserveStrategy");
2862
- const { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
2863
- const { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions("isAddDriveEnabled");
2864
- const { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions("isPublicDrivesEnabled");
2865
- const { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions("isAddPublicDrivesEnabled");
2866
- const { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions("isDeletePublicDrivesEnabled");
2867
- const { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions("isCloudDrivesEnabled");
2868
- const { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions("isAddCloudDrivesEnabled");
2869
- const { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteCloudDrivesEnabled");
2870
- const { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
2871
- const { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions("isAddLocalDrivesEnabled");
2872
- const { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteLocalDrivesEnabled");
2873
- const { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions("isEditorDebugModeEnabled");
2874
- const { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions("isEditorReadModeEnabled");
2875
- const { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled");
2876
- const { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions("isDiffAnalyticsEnabled");
2877
- const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions("isDriveAnalyticsEnabled");
2878
- const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
2879
- const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
2880
- const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
2881
- const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
2882
- const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
2883
- const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
2884
- const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
2885
- const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
2886
- const { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions("isSentryTracingEnabled");
2887
- const { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions("isExternalProcessorsEnabled");
2888
- const { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions("isExternalPackagesEnabled");
2889
- const enabledEditorsEventFunctions = makePHEventFunctions("enabledEditors");
2890
- /** Sets the enabled editors for Connect. */
2891
- const setEnabledEditors = enabledEditorsEventFunctions.setValue;
2892
- /** Gets the enabled editors for Connect. */
2893
- const useEnabledEditors = enabledEditorsEventFunctions.useValue;
2894
- enabledEditorsEventFunctions.addEventHandler;
2895
- const disabledEditorsEventFunctions = makePHEventFunctions("disabledEditors");
2896
- /** Sets the disabled editors for Connect. */
2897
- const setDisabledEditors = disabledEditorsEventFunctions.setValue;
2898
- /** Gets the disabled editors for Connect. */
2899
- const useDisabledEditors = disabledEditorsEventFunctions.useValue;
2900
- disabledEditorsEventFunctions.addEventHandler;
2901
- const isRelationalProcessorsEnabled = makePHEventFunctions("isRelationalProcessorsEnabled");
2902
- /** Sets the isRelationalProcessorsEnabled for Connect. */
2903
- const setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;
2904
- /** Gets the isRelationalProcessorsEnabled for Connect. */
2905
- const useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;
2906
- isRelationalProcessorsEnabled.addEventHandler;
2907
- const isExternalRelationalProcessorsEnabled = makePHEventFunctions("isExternalRelationalProcessorsEnabled");
2908
- /** Sets the isExternalRelationalProcessorsEnabled for Connect. */
2909
- const setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;
2910
- /** Gets the isExternalRelationalProcessorsEnabled for Connect. */
2911
- const useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;
2912
- isExternalRelationalProcessorsEnabled.addEventHandler;
2913
- const isAnalyticsEnabledEventFunctions = makePHEventFunctions("isAnalyticsEnabled");
2914
- /** Sets the isAnalyticsEnabled for Connect. */
2915
- const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;
2916
- /** Gets the isAnalyticsEnabled for Connect. */
2917
- const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;
2918
- isAnalyticsEnabledEventFunctions.addEventHandler;
2919
- const isAnalyticsExternalProcessorsEnabled = makePHEventFunctions("isAnalyticsExternalProcessorsEnabled");
2920
- /** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */
2921
- const setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;
2922
- /** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */
2923
- const useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;
2924
- isAnalyticsExternalProcessorsEnabled.addEventHandler;
2925
- const analyticsDatabaseNameEventFunctions = makePHEventFunctions("analyticsDatabaseName");
2926
- /** Sets the analytics database name for Connect. */
2927
- const setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;
2928
- /** Gets the analytics database name for Connect. */
2929
- const useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;
2930
- analyticsDatabaseNameEventFunctions.addEventHandler;
2931
- const logLevelEventFunctions = makePHEventFunctions("logLevel");
2932
- /** Sets the log level for Connect. */
2933
- const setLogLevel = logLevelEventFunctions.setValue;
2934
- /** Gets the log level for Connect. */
2935
- const useLogLevel = logLevelEventFunctions.useValue;
2936
- logLevelEventFunctions.addEventHandler;
2937
- const allowListEventFunctions = makePHEventFunctions("allowList");
2938
- /** Sets the allow list for Connect. */
2939
- const setAllowList = allowListEventFunctions.setValue;
2940
- /** Gets the allow list for Connect. */
2941
- const useAllowList = allowListEventFunctions.useValue;
2942
- allowListEventFunctions.addEventHandler;
2943
- const nonUserConfigSetters = {
2944
- routerBasename: setRouterBasename,
2945
- version: setVersion,
2946
- requiresHardRefresh: setRequiresHardRefresh,
2947
- warnOutdatedApp: setWarnOutdatedApp,
2948
- studioMode: setStudioMode,
2949
- basePath: setBasePath,
2950
- versionCheckInterval: setVersionCheckInterval,
2951
- cliVersion: setCliVersion,
2952
- fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,
2953
- isDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,
2954
- gaTrackingId: setGaTrackingId,
2955
- defaultDrivesUrl: setDefaultDrivesUrl,
2956
- drivesPreserveStrategy: setDrivesPreserveStrategy,
2957
- isLocalDrivesEnabled: setIsLocalDrivesEnabled,
2958
- isAddDriveEnabled: setIsAddDriveEnabled,
2959
- isPublicDrivesEnabled: setIsPublicDrivesEnabled,
2960
- isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,
2961
- isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,
2962
- isCloudDrivesEnabled: setIsCloudDrivesEnabled,
2963
- isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,
2964
- isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,
2965
- isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,
2966
- isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,
2967
- isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,
2968
- isEditorReadModeEnabled: setIsEditorReadModeEnabled,
2969
- isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,
2970
- isExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,
2971
- isAnalyticsEnabled: setIsAnalyticsEnabled,
2972
- analyticsDatabaseName: setAnalyticsDatabaseName,
2973
- isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,
2974
- isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,
2975
- isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,
2976
- isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,
2977
- renownUrl: setRenownUrl,
2978
- renownNetworkId: setRenownNetworkId,
2979
- renownChainId: setRenownChainId,
2980
- switchboardUrl: setSwitchboardUrl,
2981
- renownAdapters: setRenownAdapters,
2982
- sentryRelease: setSentryRelease,
2983
- sentryDsn: setSentryDsn,
2984
- sentryEnv: setSentryEnv,
2985
- isSentryTracingEnabled: setIsSentryTracingEnabled,
2986
- isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,
2987
- isExternalPackagesEnabled: setIsExternalPackagesEnabled,
2988
- allowList: setAllowList,
2989
- logLevel: setLogLevel,
2990
- disabledEditors: setDisabledEditors,
2991
- enabledEditors: setEnabledEditors
2992
- };
2993
- const phGlobalConfigSetters = {
2994
- ...phAppConfigSetters,
2995
- ...phDocumentEditorConfigSetters,
2996
- ...nonUserConfigSetters
2997
- };
2998
- const nonUserConfigHooks = {
2999
- routerBasename: useRouterBasename,
3000
- version: useVersion,
3001
- requiresHardRefresh: useRequiresHardRefresh,
3002
- warnOutdatedApp: useWarnOutdatedApp,
3003
- studioMode: useStudioMode,
3004
- basePath: useBasePath,
3005
- versionCheckInterval: useVersionCheckInterval,
3006
- cliVersion: useCliVersion,
3007
- fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,
3008
- isDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,
3009
- gaTrackingId: useGaTrackingId,
3010
- defaultDrivesUrl: useDefaultDrivesUrl,
3011
- drivesPreserveStrategy: useDrivesPreserveStrategy,
3012
- isAddDriveEnabled: useIsAddDriveEnabled,
3013
- isPublicDrivesEnabled: useIsPublicDrivesEnabled,
3014
- isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,
3015
- isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,
3016
- isCloudDrivesEnabled: useIsCloudDrivesEnabled,
3017
- isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,
3018
- isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,
3019
- isLocalDrivesEnabled: useIsLocalDrivesEnabled,
3020
- isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,
3021
- isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,
3022
- isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,
3023
- isEditorReadModeEnabled: useIsEditorReadModeEnabled,
3024
- isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,
3025
- isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,
3026
- isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,
3027
- renownUrl: useRenownUrl,
3028
- renownNetworkId: useRenownNetworkId,
3029
- renownChainId: useRenownChainId,
3030
- switchboardUrl: useSwitchboardUrl,
3031
- renownAdapters: useRenownAdapters,
3032
- sentryRelease: useSentryRelease,
3033
- sentryDsn: useSentryDsn,
3034
- sentryEnv: useSentryEnv,
3035
- isSentryTracingEnabled: useIsSentryTracingEnabled,
3036
- isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,
3037
- isExternalPackagesEnabled: useIsExternalPackagesEnabled,
3038
- allowList: useAllowList,
3039
- isAnalyticsEnabled: useIsAnalyticsEnabled,
3040
- isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,
3041
- isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,
3042
- isExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,
3043
- analyticsDatabaseName: useAnalyticsDatabaseName,
3044
- logLevel: useLogLevel,
3045
- disabledEditors: useDisabledEditors,
3046
- enabledEditors: useEnabledEditors
3047
- };
3048
- ({
3049
- ...phAppConfigHooks,
3050
- ...phDocumentEditorConfigHooks,
3051
- ...nonUserConfigHooks
3052
- });
3053
- const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
3054
- attachmentServiceEventFunctions.useValue;
3055
- attachmentServiceEventFunctions.setValue;
3056
- attachmentServiceEventFunctions.addEventHandler;
3057
- const featuresEventFunctions = makePHEventFunctions("features");
3058
- featuresEventFunctions.useValue;
3059
- featuresEventFunctions.setValue;
3060
- featuresEventFunctions.addEventHandler;
3061
- function useDropTarget() {
3062
- const [isDropTarget, setIsDropTarget] = useState(false);
3063
- const isDragAndDropEnabled = useIsDragAndDropEnabled();
3064
- const targetSetter = n$1(() => setIsDropTarget(true), {
3065
- triggerAt: "start",
3066
- minQuietPeriodMs: 100
3067
- });
3068
- const targetUnsetter = n$1(() => setIsDropTarget(false), {
3069
- triggerAt: "start",
3070
- minQuietPeriodMs: 100
3071
- });
3072
- function setTarget() {
3073
- if (!isDragAndDropEnabled) return;
3074
- targetUnsetter.cancel();
3075
- targetSetter.call();
3076
- }
3077
- function unsetTarget() {
3078
- if (!isDragAndDropEnabled) return;
3079
- targetSetter.cancel();
3080
- targetUnsetter.call();
3081
- }
3082
- return {
3083
- isDropTarget,
3084
- setTarget,
3085
- unsetTarget
3086
- };
3087
- }
3088
- const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3089
- const useDraggingNode = draggingNodeEventFunctions.useValue;
3090
- const setDraggingNode = draggingNodeEventFunctions.setValue;
3091
- draggingNodeEventFunctions.addEventHandler;
3092
- const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3093
- reducer: (_, newNode) => newNode,
3094
- triggerAt: "start",
3095
- minQuietPeriodMs: 100
3096
- });
3097
- const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3098
- triggerAt: "start",
3099
- minQuietPeriodMs: 100
3100
- });
3101
- function setDragging(node) {
3102
- draggingNodeUnsetter.cancel();
3103
- draggingNodeSetter.call(node);
3104
- }
3105
- function unsetDragging() {
3106
- draggingNodeSetter.cancel();
3107
- draggingNodeUnsetter.call();
3108
- }
3109
- const isNodeDrag = (params) => t$3(params, [({ srcId }) => e$3(e$1)(srcId), e$6(false)], [({ driveId }) => e$3(e$1)(driveId), e$6(false)], [({ driveId, srcId }) => t(driveId, srcId), e$6(false)], e$6(true));
3110
- function useDragNode(args) {
3111
- const { srcId, parentId } = args;
3112
- const driveId = useSelectedDriveId();
3113
- const draggingNodeId = useDraggingNode()?.srcId;
3114
- const params = {
3115
- driveId,
3116
- srcId,
3117
- parentId
3118
- };
3119
- const draggable = isNodeDrag(params);
3120
- const isDragging = t$4({
3121
- srcId,
3122
- draggingNodeId
3123
- }, [
3124
- () => draggable,
3125
- ({ srcId }) => e$2(srcId),
3126
- ({ draggingNodeId }) => e$2(draggingNodeId),
3127
- ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3128
- ]);
3129
- const onDragStart = () => {
3130
- if (!draggable) return;
3131
- setDragging(params);
3132
- };
3133
- const onDragEnd = () => {
3134
- if (!draggable) return;
3135
- unsetDragging();
3136
- };
3137
- return {
3138
- isDragging,
3139
- draggable,
3140
- onDragStart,
3141
- onDragEnd
3142
- };
3143
- }
3144
- const isNodeDrop = (params) => t$3(params, [({ srcId }) => e$3(e$1)(srcId), e$6(false)], [({ driveId }) => e$3(e$4)(driveId), e$6(false)], [({ srcId, targetId }) => t(srcId, targetId), e$6(false)], [({ driveId, parentId, targetId }) => e$3(e$1)(parentId) && t(targetId, driveId), e$6(false)], [({ targetId, parentId }) => t(targetId, parentId), e$6(false)], e$6(true));
3145
- function useDropNode(targetId) {
3146
- const driveId = useSelectedDriveId();
3147
- const { srcId, parentId } = useDraggingNode() ?? {};
3148
- const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3149
- const params = {
3150
- driveId,
3151
- parentId,
3152
- targetId,
3153
- srcId
3154
- };
3155
- function handleNodeDrop(event, cb) {
3156
- if (!isNodeDrop(params)) return;
3157
- event.preventDefault();
3158
- event.stopPropagation();
3159
- cb?.();
3160
- }
3161
- const onDragEnter = (event) => handleNodeDrop(event);
3162
- const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3163
- const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3164
- const onDrop = (event) => handleNodeDrop(event, e(() => {
3165
- unsetDragging();
3166
- unsetTarget();
3167
- moveNodeById(params).catch(console.error);
3168
- }));
3169
- return {
3170
- isDropTarget,
3171
- onDragEnter,
3172
- onDragOver,
3173
- onDragLeave,
3174
- onDrop
3175
- };
3176
- }
3177
- const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3178
- graphQLReactorClientEventFunctions.useValue;
3179
- graphQLReactorClientEventFunctions.setValue;
3180
- graphQLReactorClientEventFunctions.addEventHandler;
3181
- const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3182
- packageDiscoveryFunctions.useValue;
3183
- packageDiscoveryFunctions.setValue;
3184
- packageDiscoveryFunctions.addEventHandler;
3185
- const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3186
- const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3187
- /** Returns the reactor client module (in-process or worker-backed) */
3188
- const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3189
- reactorClientModuleEventFunctions.setValue;
3190
- reactorClientModuleEventFunctions.addEventHandler;
3191
- reactorClientEventFunctions.useValue;
3192
- reactorClientEventFunctions.setValue;
3193
- reactorClientEventFunctions.addEventHandler;
3194
- const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3195
- const useSyncList = () => {
3196
- return useSync()?.list() ?? [];
3197
- };
3198
- const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
3199
- const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3200
- revisionHistoryEventFunctions.useValue;
3201
- /** Sets revision history visibility */
3202
- const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3203
- revisionHistoryEventFunctions.addEventHandler;
3204
- /** Shows the revision history */
3205
- function showRevisionHistory() {
3206
- setRevisionHistoryVisible(true);
3207
- }
3208
- const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3209
- selectedTimelineItemEventFunctions.useValue;
3210
- selectedTimelineItemEventFunctions.setValue;
3211
- selectedTimelineItemEventFunctions.addEventHandler;
3212
- const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3213
- selectedTimelineRevisionEventFunctions.useValue;
3214
- selectedTimelineRevisionEventFunctions.setValue;
3215
- selectedTimelineRevisionEventFunctions.addEventHandler;
3216
- const toastEventFunctions = makePHEventFunctions("toast");
3217
- /** Returns the toast function */
3218
- const usePHToast = toastEventFunctions.useValue;
3219
- toastEventFunctions.setValue;
3220
- toastEventFunctions.addEventHandler;
3221
- //#endregion
3222
- //#region ../reactor-browser/dist/switchboard-CaXQ4-5Q.js
3223
- /** Returns a document of a specific type, throws an error if the found document has a different type */
3224
- function useDocumentOfType(documentId, documentType) {
3225
- const [document, dispatch] = useDocumentById(documentId);
3226
- const documentModelModule = useDocumentModelModuleById(documentType);
3227
- if (!documentId || !documentType) return [];
3228
- if (!document) throw new Error(`Document not found: ${documentId}`);
3229
- if (!documentModelModule) throw new ModuleNotFoundError(documentType);
3230
- if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3231
- return [document, dispatch];
3232
- }
3233
- /** Returns the selected document id */
3234
- function useSelectedDocumentId() {
3235
- const selectedNode = useSelectedNode();
3236
- return selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;
3237
- }
3238
- /** Returns the selected document. */
3239
- function useSelectedDocumentSafe() {
3240
- return useDocumentById(useSelectedDocumentId());
3241
- }
3242
- function useSelectedDocumentOfType(documentType) {
3243
- const documentId = useSelectedDocumentId();
3244
- if (!documentType) return [];
3245
- if (!documentId) throw new NoSelectedDocumentError();
3246
- return useDocumentOfType(documentId, documentType);
3247
- }
3248
- //#endregion
3249
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
3250
- const normalizeDescriptors = (error) => {
3251
- CORE_ERROR_PROPS.forEach((propName) => {
3252
- normalizeDescriptor(error, propName);
3253
- });
3254
- };
3255
- const CORE_ERROR_PROPS = [
3256
- "name",
3257
- "message",
3258
- "stack",
3259
- "cause",
3260
- "errors"
3261
- ];
3262
- const normalizeDescriptor = (error, propName) => {
3263
- const descriptor = getDescriptor(error, propName);
3264
- if (descriptor === void 0) return;
3265
- if (isReadonlyGetter(descriptor)) {
3266
- setErrorProperty(error, propName, error[propName]);
3267
- return;
3268
- }
3269
- if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
3270
- };
3271
- const getDescriptor = (value, propName) => {
3272
- const descriptor = Object.getOwnPropertyDescriptor(value, propName);
3273
- if (descriptor !== void 0) return descriptor;
3274
- const prototype = Object.getPrototypeOf(value);
3275
- return prototype === null ? void 0 : getDescriptor(prototype, propName);
3276
- };
3277
- const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
3278
- const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
3279
- const setErrorProperty = (error, propName, value) => {
3280
- setErrorDescriptor(error, propName, { value });
3281
- };
3282
- const setErrorDescriptor = (error, propName, descriptor) => {
3283
- Object.defineProperty(error, propName, {
3284
- ...descriptor,
3285
- ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
3286
- enumerable: false,
3287
- configurable: true
3288
- });
3289
- };
3290
- //#endregion
3291
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
3292
- const normalizeAggregate = (error, recurse) => {
3293
- if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
3294
- else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
3295
- else if (error.errors !== void 0) deleteAggregateErrors(error);
3296
- };
3297
- const isDefined = (error) => error !== void 0;
3298
- const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
3299
- const deleteAggregateErrors = (error) => {
3300
- delete error.errors;
3301
- if (error.errors !== void 0) setErrorProperty(error, "errors", []);
3302
- };
3303
- //#endregion
3304
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
3305
- const normalizeCause = (error, recurse) => {
3306
- if (!("cause" in error)) return;
3307
- const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
3308
- if (cause === void 0) delete error.cause;
3309
- else setErrorProperty(error, "cause", cause);
3310
- };
3311
- //#endregion
3312
- //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
3313
- const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
3314
- const isInstanceOfError = (value) => {
3315
- try {
3316
- return value instanceof Error;
3317
- } catch {
3318
- return false;
3319
- }
3320
- };
3321
- const hasErrorTag = (value) => {
3322
- try {
3323
- return ERROR_TAGS.has(Object.prototype.toString.call(value));
3324
- } catch {
3325
- return false;
3326
- }
3327
- };
3328
- const ERROR_TAGS = new Set([
3329
- "[object Error]",
3330
- "[object DOMException]",
3331
- "[object DOMError]",
3332
- "[object Exception]"
3333
- ]);
3334
- //#endregion
3335
- //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
3336
- function isPlainObject(value) {
3337
- if (typeof value !== "object" || value === null) return false;
3338
- const prototype = Object.getPrototypeOf(value);
3339
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
3340
- }
3341
- //#endregion
3342
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
3343
- const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
3344
- const isNonConfigurableProp = (error, propName) => {
3345
- const descriptor = Object.getOwnPropertyDescriptor(error, propName);
3346
- return descriptor !== void 0 && !descriptor.configurable;
3347
- };
3348
- const isThrowingProp = (error, propName) => {
3349
- try {
3350
- error[propName];
3351
- return false;
3352
- } catch {
3353
- return true;
3354
- }
3355
- };
3356
- //#endregion
3357
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
3358
- const setStack = (error) => {
3359
- setErrorProperty(error, "stack", getStack(error.message, error.name));
3360
- };
3361
- const getStack = (message = "", name = "Error") => {
3362
- const { stack } = new (getErrorClass(name))(message);
3363
- return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
3364
- };
3365
- const getErrorClass = (name) => {
3366
- const descriptor = {
3367
- value: name,
3368
- enumerable: false,
3369
- writable: true,
3370
- configurable: true
3371
- };
3372
- const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
3373
- Object.defineProperty(StackError.prototype, "name", descriptor);
3374
- return StackError;
3375
- };
3376
- //#endregion
3377
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
3378
- const copyObject = (object) => {
3379
- const objectCopy = {};
3380
- for (const propName of getPropsToCopy(object)) try {
3381
- const value = object[propName];
3382
- const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
3383
- Object.defineProperty(objectCopy, propName, {
3384
- value,
3385
- enumerable,
3386
- configurable,
3387
- writable
3388
- });
3389
- } catch {}
3390
- return objectCopy;
3391
- };
3392
- const getPropsToCopy = (object) => {
3393
- const propNames = getOwnKeys(object);
3394
- for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
3395
- return propNames;
3396
- };
3397
- const getOwnKeys = (object) => {
3398
- try {
3399
- return Reflect.ownKeys(object);
3400
- } catch {
3401
- return [];
3402
- }
3403
- };
3404
- const isInheritedProp = (object, propName) => {
3405
- try {
3406
- return propName in object && !Object.hasOwn(object, propName);
3407
- } catch {
3408
- return false;
3409
- }
3410
- };
3411
- //#endregion
3412
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
3413
- const objectifyError = (object) => {
3414
- const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
3415
- const messageA = getMessage(message, objectA);
3416
- const error = newError(name, messageA);
3417
- if (message === messageA) assignObjectProps(error, objectA);
3418
- Object.entries({
3419
- name,
3420
- stack,
3421
- cause,
3422
- errors
3423
- }).forEach(([propName, propValue]) => {
3424
- setNewErrorProperty(error, propName, propValue);
3425
- });
3426
- if (stack === void 0) setStack(error);
3427
- return error;
3428
- };
3429
- const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
3430
- const safeJsonStringify = (object) => {
3431
- try {
3432
- return JSON.stringify(object);
3433
- } catch {
3434
- return safeStringify(object);
3435
- }
3436
- };
3437
- const safeStringify = (object) => {
3438
- try {
3439
- return String(object);
3440
- } catch {
3441
- return "Invalid error";
3442
- }
3443
- };
3444
- const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
3445
- const MESSAGE_MAX_SIZE = 1e3;
3446
- const newError = (name, message) => {
3447
- if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
3448
- if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
3449
- return new Error(message);
3450
- };
3451
- const NATIVE_ERRORS = {
3452
- Error,
3453
- ReferenceError,
3454
- TypeError,
3455
- SyntaxError,
3456
- RangeError,
3457
- URIError,
3458
- EvalError
3459
- };
3460
- const assignObjectProps = (error, object) => {
3461
- for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
3462
- };
3463
- const setNewErrorProperty = (error, propName, propValue) => {
3464
- if (propValue !== void 0) setErrorProperty(error, propName, propValue);
3465
- };
3466
- //#endregion
3467
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
3468
- const stringifyError = (value) => {
3469
- try {
3470
- const error = new Error(String(value));
3471
- setStack(error);
3472
- return error;
3473
- } catch (error_) {
3474
- return error_;
3475
- }
3476
- };
3477
- //#endregion
3478
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
3479
- const { toString: objectToString } = Object.prototype;
3480
- const createError = (value) => {
3481
- if (isErrorPlainObj(value)) return objectifyError(value);
3482
- if (!isErrorInstance(value)) return stringifyError(value);
3483
- if (isInvalidError(value)) return objectifyError(value);
3484
- return value;
3485
- };
3486
- const isErrorPlainObj = (value) => {
3487
- try {
3488
- return isPlainObject(value);
3489
- } catch {
3490
- return false;
3491
- }
3492
- };
3493
- const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
3494
- const isProxy = (value) => {
3495
- try {
3496
- return objectToString.call(value) === "[object Object]";
3497
- } catch {
3498
- return true;
3499
- }
3500
- };
3501
- const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
3502
- //#endregion
3503
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
3504
- const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
3505
- const recurseException = (error, parents, shallow) => {
3506
- if (parents.includes(error)) return;
3507
- const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
3508
- const errorA = createError(error);
3509
- normalizeProps(errorA, recurse);
3510
- return errorA;
3511
- };
3512
- const identity = (error) => error;
3513
- const normalizeProps = (error, recurse) => {
3514
- normalizeName(error);
3515
- normalizeMessage(error);
3516
- normalizeStack(error);
3517
- normalizeCause(error, recurse);
3518
- normalizeAggregate(error, recurse);
3519
- normalizeDescriptors(error);
3520
- };
3521
- const normalizeName = (error) => {
3522
- if (isDefinedString(error.name)) return;
3523
- const prototypeName = Object.getPrototypeOf(error).name;
3524
- setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
3525
- };
3526
- const normalizeMessage = (error) => {
3527
- if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
3528
- };
3529
- const normalizeStack = (error) => {
3530
- if (!isDefinedString(error.stack)) setStack(error);
3531
- };
3532
- const isDefinedString = (value) => typeof value === "string" && value !== "";
3533
- //#endregion
3534
- //#region ../reactor-browser/dist/index.js
3535
- var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3536
- var LZString = (function() {
3537
- var f = String.fromCharCode;
3538
- var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3539
- var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
3540
- var baseReverseDic = {};
3541
- function getBaseValue(alphabet, character) {
3542
- if (!baseReverseDic[alphabet]) {
3543
- baseReverseDic[alphabet] = {};
3544
- for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
3545
- }
3546
- return baseReverseDic[alphabet][character];
3547
- }
3548
- var LZString = {
3549
- compressToBase64: function(input) {
3550
- if (input == null) return "";
3551
- var res = LZString._compress(input, 6, function(a) {
3552
- return keyStrBase64.charAt(a);
3553
- });
3554
- switch (res.length % 4) {
3555
- default:
3556
- case 0: return res;
3557
- case 1: return res + "===";
3558
- case 2: return res + "==";
3559
- case 3: return res + "=";
3560
- }
3561
- },
3562
- decompressFromBase64: function(input) {
3563
- if (input == null) return "";
3564
- if (input == "") return null;
3565
- return LZString._decompress(input.length, 32, function(index) {
3566
- return getBaseValue(keyStrBase64, input.charAt(index));
3567
- });
3568
- },
3569
- compressToUTF16: function(input) {
3570
- if (input == null) return "";
3571
- return LZString._compress(input, 15, function(a) {
3572
- return f(a + 32);
3573
- }) + " ";
3574
- },
3575
- decompressFromUTF16: function(compressed) {
3576
- if (compressed == null) return "";
3577
- if (compressed == "") return null;
3578
- return LZString._decompress(compressed.length, 16384, function(index) {
3579
- return compressed.charCodeAt(index) - 32;
3580
- });
3581
- },
3582
- compressToUint8Array: function(uncompressed) {
3583
- var compressed = LZString.compress(uncompressed);
3584
- var buf = new Uint8Array(compressed.length * 2);
3585
- for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
3586
- var current_value = compressed.charCodeAt(i);
3587
- buf[i * 2] = current_value >>> 8;
3588
- buf[i * 2 + 1] = current_value % 256;
3589
- }
3590
- return buf;
3591
- },
3592
- decompressFromUint8Array: function(compressed) {
3593
- if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
3594
- else {
3595
- var buf = new Array(compressed.length / 2);
3596
- for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
3597
- var result = [];
3598
- buf.forEach(function(c) {
3599
- result.push(f(c));
3600
- });
3601
- return LZString.decompress(result.join(""));
3602
- }
3603
- },
3604
- compressToEncodedURIComponent: function(input) {
3605
- if (input == null) return "";
3606
- return LZString._compress(input, 6, function(a) {
3607
- return keyStrUriSafe.charAt(a);
3608
- });
3609
- },
3610
- decompressFromEncodedURIComponent: function(input) {
3611
- if (input == null) return "";
3612
- if (input == "") return null;
3613
- input = input.replace(/ /g, "+");
3614
- return LZString._decompress(input.length, 32, function(index) {
3615
- return getBaseValue(keyStrUriSafe, input.charAt(index));
3616
- });
3617
- },
3618
- compress: function(uncompressed) {
3619
- return LZString._compress(uncompressed, 16, function(a) {
3620
- return f(a);
3621
- });
3622
- },
3623
- _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
3624
- if (uncompressed == null) return "";
3625
- var i, value, context_dictionary = {}, context_dictionaryToCreate = {}, context_c = "", context_wc = "", context_w = "", context_enlargeIn = 2, context_dictSize = 3, context_numBits = 2, context_data = [], context_data_val = 0, context_data_position = 0, ii;
3626
- for (ii = 0; ii < uncompressed.length; ii += 1) {
3627
- context_c = uncompressed.charAt(ii);
3628
- if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
3629
- context_dictionary[context_c] = context_dictSize++;
3630
- context_dictionaryToCreate[context_c] = true;
3631
- }
3632
- context_wc = context_w + context_c;
3633
- if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
3634
- else {
3635
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3636
- if (context_w.charCodeAt(0) < 256) {
3637
- for (i = 0; i < context_numBits; i++) {
3638
- context_data_val = context_data_val << 1;
3639
- if (context_data_position == bitsPerChar - 1) {
3640
- context_data_position = 0;
3641
- context_data.push(getCharFromInt(context_data_val));
3642
- context_data_val = 0;
3643
- } else context_data_position++;
3644
- }
3645
- value = context_w.charCodeAt(0);
3646
- for (i = 0; i < 8; i++) {
3647
- context_data_val = context_data_val << 1 | value & 1;
3648
- if (context_data_position == bitsPerChar - 1) {
3649
- context_data_position = 0;
3650
- context_data.push(getCharFromInt(context_data_val));
3651
- context_data_val = 0;
3652
- } else context_data_position++;
3653
- value = value >> 1;
3654
- }
3655
- } else {
3656
- value = 1;
3657
- for (i = 0; i < context_numBits; i++) {
3658
- context_data_val = context_data_val << 1 | value;
3659
- if (context_data_position == bitsPerChar - 1) {
3660
- context_data_position = 0;
3661
- context_data.push(getCharFromInt(context_data_val));
3662
- context_data_val = 0;
3663
- } else context_data_position++;
3664
- value = 0;
3665
- }
3666
- value = context_w.charCodeAt(0);
3667
- for (i = 0; i < 16; i++) {
3668
- context_data_val = context_data_val << 1 | value & 1;
3669
- if (context_data_position == bitsPerChar - 1) {
3670
- context_data_position = 0;
3671
- context_data.push(getCharFromInt(context_data_val));
3672
- context_data_val = 0;
3673
- } else context_data_position++;
3674
- value = value >> 1;
3675
- }
3676
- }
3677
- context_enlargeIn--;
3678
- if (context_enlargeIn == 0) {
3679
- context_enlargeIn = Math.pow(2, context_numBits);
3680
- context_numBits++;
3681
- }
3682
- delete context_dictionaryToCreate[context_w];
3683
- } else {
3684
- value = context_dictionary[context_w];
3685
- for (i = 0; i < context_numBits; i++) {
3686
- context_data_val = context_data_val << 1 | value & 1;
3687
- if (context_data_position == bitsPerChar - 1) {
3688
- context_data_position = 0;
3689
- context_data.push(getCharFromInt(context_data_val));
3690
- context_data_val = 0;
3691
- } else context_data_position++;
3692
- value = value >> 1;
3693
- }
3694
- }
3695
- context_enlargeIn--;
3696
- if (context_enlargeIn == 0) {
3697
- context_enlargeIn = Math.pow(2, context_numBits);
3698
- context_numBits++;
3699
- }
3700
- context_dictionary[context_wc] = context_dictSize++;
3701
- context_w = String(context_c);
3702
- }
3703
- }
3704
- if (context_w !== "") {
3705
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3706
- if (context_w.charCodeAt(0) < 256) {
3707
- for (i = 0; i < context_numBits; i++) {
3708
- context_data_val = context_data_val << 1;
3709
- if (context_data_position == bitsPerChar - 1) {
3710
- context_data_position = 0;
3711
- context_data.push(getCharFromInt(context_data_val));
3712
- context_data_val = 0;
3713
- } else context_data_position++;
3714
- }
3715
- value = context_w.charCodeAt(0);
3716
- for (i = 0; i < 8; i++) {
3717
- context_data_val = context_data_val << 1 | value & 1;
3718
- if (context_data_position == bitsPerChar - 1) {
3719
- context_data_position = 0;
3720
- context_data.push(getCharFromInt(context_data_val));
3721
- context_data_val = 0;
3722
- } else context_data_position++;
3723
- value = value >> 1;
3724
- }
3725
- } else {
3726
- value = 1;
3727
- for (i = 0; i < context_numBits; i++) {
3728
- context_data_val = context_data_val << 1 | value;
3729
- if (context_data_position == bitsPerChar - 1) {
3730
- context_data_position = 0;
3731
- context_data.push(getCharFromInt(context_data_val));
3732
- context_data_val = 0;
3733
- } else context_data_position++;
3734
- value = 0;
3735
- }
3736
- value = context_w.charCodeAt(0);
3737
- for (i = 0; i < 16; i++) {
3738
- context_data_val = context_data_val << 1 | value & 1;
3739
- if (context_data_position == bitsPerChar - 1) {
3740
- context_data_position = 0;
3741
- context_data.push(getCharFromInt(context_data_val));
3742
- context_data_val = 0;
3743
- } else context_data_position++;
3744
- value = value >> 1;
3745
- }
3746
- }
3747
- context_enlargeIn--;
3748
- if (context_enlargeIn == 0) {
3749
- context_enlargeIn = Math.pow(2, context_numBits);
3750
- context_numBits++;
3751
- }
3752
- delete context_dictionaryToCreate[context_w];
3753
- } else {
3754
- value = context_dictionary[context_w];
3755
- for (i = 0; i < context_numBits; i++) {
3756
- context_data_val = context_data_val << 1 | value & 1;
3757
- if (context_data_position == bitsPerChar - 1) {
3758
- context_data_position = 0;
3759
- context_data.push(getCharFromInt(context_data_val));
3760
- context_data_val = 0;
3761
- } else context_data_position++;
3762
- value = value >> 1;
3763
- }
3764
- }
3765
- context_enlargeIn--;
3766
- if (context_enlargeIn == 0) {
3767
- context_enlargeIn = Math.pow(2, context_numBits);
3768
- context_numBits++;
3769
- }
3770
- }
3771
- value = 2;
3772
- for (i = 0; i < context_numBits; i++) {
3773
- context_data_val = context_data_val << 1 | value & 1;
3774
- if (context_data_position == bitsPerChar - 1) {
3775
- context_data_position = 0;
3776
- context_data.push(getCharFromInt(context_data_val));
3777
- context_data_val = 0;
3778
- } else context_data_position++;
3779
- value = value >> 1;
3780
- }
3781
- while (true) {
3782
- context_data_val = context_data_val << 1;
3783
- if (context_data_position == bitsPerChar - 1) {
3784
- context_data.push(getCharFromInt(context_data_val));
3785
- break;
3786
- } else context_data_position++;
3787
- }
3788
- return context_data.join("");
3789
- },
3790
- decompress: function(compressed) {
3791
- if (compressed == null) return "";
3792
- if (compressed == "") return null;
3793
- return LZString._decompress(compressed.length, 32768, function(index) {
3794
- return compressed.charCodeAt(index);
3795
- });
3796
- },
3797
- _decompress: function(length, resetValue, getNextValue) {
3798
- var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
3799
- val: getNextValue(0),
3800
- position: resetValue,
3801
- index: 1
3802
- };
3803
- for (i = 0; i < 3; i += 1) dictionary[i] = i;
3804
- bits = 0;
3805
- maxpower = Math.pow(2, 2);
3806
- power = 1;
3807
- while (power != maxpower) {
3808
- resb = data.val & data.position;
3809
- data.position >>= 1;
3810
- if (data.position == 0) {
3811
- data.position = resetValue;
3812
- data.val = getNextValue(data.index++);
3813
- }
3814
- bits |= (resb > 0 ? 1 : 0) * power;
3815
- power <<= 1;
3816
- }
3817
- switch (bits) {
3818
- case 0:
3819
- bits = 0;
3820
- maxpower = Math.pow(2, 8);
3821
- power = 1;
3822
- while (power != maxpower) {
3823
- resb = data.val & data.position;
3824
- data.position >>= 1;
3825
- if (data.position == 0) {
3826
- data.position = resetValue;
3827
- data.val = getNextValue(data.index++);
3828
- }
3829
- bits |= (resb > 0 ? 1 : 0) * power;
3830
- power <<= 1;
3831
- }
3832
- c = f(bits);
3833
- break;
3834
- case 1:
3835
- bits = 0;
3836
- maxpower = Math.pow(2, 16);
3837
- power = 1;
3838
- while (power != maxpower) {
3839
- resb = data.val & data.position;
3840
- data.position >>= 1;
3841
- if (data.position == 0) {
3842
- data.position = resetValue;
3843
- data.val = getNextValue(data.index++);
3844
- }
3845
- bits |= (resb > 0 ? 1 : 0) * power;
3846
- power <<= 1;
3847
- }
3848
- c = f(bits);
3849
- break;
3850
- case 2: return "";
3851
- }
3852
- dictionary[3] = c;
3853
- w = c;
3854
- result.push(c);
3855
- while (true) {
3856
- if (data.index > length) return "";
3857
- bits = 0;
3858
- maxpower = Math.pow(2, numBits);
3859
- power = 1;
3860
- while (power != maxpower) {
3861
- resb = data.val & data.position;
3862
- data.position >>= 1;
3863
- if (data.position == 0) {
3864
- data.position = resetValue;
3865
- data.val = getNextValue(data.index++);
3866
- }
3867
- bits |= (resb > 0 ? 1 : 0) * power;
3868
- power <<= 1;
3869
- }
3870
- switch (c = bits) {
3871
- case 0:
3872
- bits = 0;
3873
- maxpower = Math.pow(2, 8);
3874
- power = 1;
3875
- while (power != maxpower) {
3876
- resb = data.val & data.position;
3877
- data.position >>= 1;
3878
- if (data.position == 0) {
3879
- data.position = resetValue;
3880
- data.val = getNextValue(data.index++);
3881
- }
3882
- bits |= (resb > 0 ? 1 : 0) * power;
3883
- power <<= 1;
3884
- }
3885
- dictionary[dictSize++] = f(bits);
3886
- c = dictSize - 1;
3887
- enlargeIn--;
3888
- break;
3889
- case 1:
3890
- bits = 0;
3891
- maxpower = Math.pow(2, 16);
3892
- power = 1;
3893
- while (power != maxpower) {
3894
- resb = data.val & data.position;
3895
- data.position >>= 1;
3896
- if (data.position == 0) {
3897
- data.position = resetValue;
3898
- data.val = getNextValue(data.index++);
3899
- }
3900
- bits |= (resb > 0 ? 1 : 0) * power;
3901
- power <<= 1;
3902
- }
3903
- dictionary[dictSize++] = f(bits);
3904
- c = dictSize - 1;
3905
- enlargeIn--;
3906
- break;
3907
- case 2: return result.join("");
3908
- }
3909
- if (enlargeIn == 0) {
3910
- enlargeIn = Math.pow(2, numBits);
3911
- numBits++;
3912
- }
3913
- if (dictionary[c]) entry = dictionary[c];
3914
- else if (c === dictSize) entry = w + w.charAt(0);
3915
- else return null;
3916
- result.push(entry);
3917
- dictionary[dictSize++] = w + entry.charAt(0);
3918
- enlargeIn--;
3919
- w = entry;
3920
- if (enlargeIn == 0) {
3921
- enlargeIn = Math.pow(2, numBits);
3922
- numBits++;
3923
- }
3924
- }
3925
- }
3926
- };
3927
- return LZString;
3928
- })();
3929
- if (typeof define === "function" && define.amd) define(function() {
3930
- return LZString;
3931
- });
3932
- else if (typeof module !== "undefined" && module != null) module.exports = LZString;
3933
- else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
3934
- return LZString;
3935
- });
3936
- })))(), 1);
3937
- const sanitize = (segment) => segment.replace(/\//g, "-");
3938
- /**
3939
- * Name segments from the exported folder (exclusive) down to `node`
3940
- * (inclusive), in top-down order. `root === undefined` means the drive root:
3941
- * all ancestors. A node that IS the exported folder yields no segments.
3942
- */
3943
- function segmentsBelow(root, node, allNodes) {
3944
- const segments = [];
3945
- let current = node;
3946
- while (current && current.id !== root?.id) {
3947
- segments.push(sanitize(current.name));
3948
- const parentId = current.parentFolder;
3949
- current = parentId ? allNodes.find((n) => n.id === parentId) : void 0;
3950
- }
3951
- return segments.reverse();
3952
- }
3953
- /**
3954
- * Assemble the archive zip for a folder (or the whole drive when
3955
- * `folderNode` is undefined). Every folder in the subtree becomes a
3956
- * directory entry (empty folders survive); every file becomes a standard
3957
- * single-document zip named after the node (drive naming convention:
3958
- * `${name}.${extension}.phd`, ` (copy) N` on a same-folder collision).
3959
- *
3960
- * `fetchDocument` must return the document WITH its full operations and
3961
- * initialState (see downloadFolderZip).
3962
- */
3963
- async function buildFolderZip(drive, folderNode, fetchDocument, onProgress) {
3964
- const allNodes = drive.state.global.nodes;
3965
- const topName = sanitize(folderNode?.name ?? (drive.state.global.name || drive.header.name));
3966
- const subtree = folderNode ? [folderNode, ...getDescendants(folderNode, allNodes)] : allNodes;
3967
- const entries = { [topName + "/"]: new Uint8Array(0) };
3968
- for (const node of subtree) {
3969
- if (!isFolderNode(node)) continue;
3970
- const dir = [topName, ...segmentsBelow(folderNode, node, allNodes)].join("/");
3971
- entries[dir + "/"] = new Uint8Array(0);
3972
- }
3973
- const files = subtree.filter(isFileNode);
3974
- const failed = [];
3975
- const usedNamesByDir = /* @__PURE__ */ new Map();
3976
- let done = 0;
3977
- for (const node of files) try {
3978
- const doc = await fetchDocument(node.id);
3979
- const extension = await getDocumentExtension(doc);
3980
- const parent = node.parentFolder ? allNodes.find((n) => n.id === node.parentFolder) : void 0;
3981
- const dir = [topName, ...parent ? segmentsBelow(folderNode, parent, allNodes) : []].join("/");
3982
- let usedNames = usedNamesByDir.get(dir);
3983
- if (!usedNames) {
3984
- usedNames = /* @__PURE__ */ new Set();
3985
- usedNamesByDir.set(dir, usedNames);
3986
- }
3987
- const base = sanitize(node.name);
3988
- let candidate = base;
3989
- let count = getNextCopyNumber([...usedNames], base);
3990
- while (usedNames.has(candidate)) {
3991
- candidate = `${base} (copy) ${count}`;
3992
- count += 1;
3993
- }
3994
- usedNames.add(candidate);
3995
- const leaf = extension ? `${candidate}.${extension}.phd` : `${candidate}.phd`;
3996
- entries[`${dir}/${leaf}`] = await createZip(doc);
3997
- } catch {
3998
- failed.push(node.name);
3999
- } finally {
4000
- done += 1;
4001
- onProgress?.(done, files.length);
4002
- }
4003
- return {
4004
- zip: await zipEntries(entries),
4005
- archiveName: `${topName}.zip`,
4006
- entryCount: files.length - failed.length,
4007
- failed
4008
- };
4009
- }
4010
- /**
4011
- * Export a folder (or whole drive) to disk: fetches every document with its
4012
- * full operation history, builds the archive, and saves it via
4013
- * showSaveFilePicker (fallback: blob download), mirroring exportFile.
4014
- */
4015
- async function downloadFolderZip(drive, folderNode, onProgress) {
4016
- const reactorClient = window.ph?.reactorClient;
4017
- if (!reactorClient) throw new Error("ReactorClient not initialized");
4018
- const result = await buildFolderZip(drive, folderNode, async (id) => {
4019
- const doc = await reactorClient.get(id);
4020
- const operations = await fetchDocumentOperations(reactorClient, doc);
4021
- const initialState = extractInitialState(operations["document"] ?? []);
4022
- return {
4023
- ...doc,
4024
- operations,
4025
- initialState
4026
- };
4027
- }, onProgress);
4028
- if (!window.showSaveFilePicker) {
4029
- const blob = new Blob([new Uint8Array(result.zip)], { type: "application/zip" });
4030
- const link = window.document.createElement("a");
4031
- link.style.display = "none";
4032
- link.href = URL.createObjectURL(blob);
4033
- link.download = result.archiveName;
4034
- window.document.body.appendChild(link);
4035
- link.click();
4036
- window.document.body.removeChild(link);
4037
- return result;
4038
- }
4039
- try {
4040
- const writable = await (await window.showSaveFilePicker({ suggestedName: result.archiveName })).createWritable();
4041
- await writable.write(new Uint8Array(result.zip));
4042
- await writable.close();
4043
- } catch (e) {
4044
- if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
4045
- }
4046
- return result;
4047
- }
4048
- /** Document types that represent a "drive": a container of nodes. */
4049
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
4050
- function useAllowedDocumentModelModules() {
4051
- const documentModelModules = useDocumentModelModules();
4052
- const allowedDocumentTypes = useAllowedDocumentTypes();
4053
- if (!allowedDocumentTypes?.length) return documentModelModules;
4054
- return documentModelModules?.filter((module) => allowedDocumentTypes.includes(module.documentModel.global.id));
4055
- }
4056
- /** Returns the selected folder. */
4057
- function useSelectedFolder() {
4058
- const selectedNode = useSelectedNode();
4059
- if (isFolderNodeKind(selectedNode)) return selectedNode;
4060
- }
4061
- /** Returns the child nodes for the selected drive or folder. */
4062
- function useNodesInSelectedDriveOrFolder() {
4063
- const nodes = useNodesInSelectedDrive();
4064
- const selectedFolderId = useSelectedFolder()?.id;
4065
- if (!nodes) return [];
4066
- if (!selectedFolderId) return sortNodesByName(nodes.filter((n) => !n.parentFolder));
4067
- return sortNodesByName(nodes.filter((n) => n.parentFolder === selectedFolderId));
4068
- }
4069
- function callGlobalSetterForKey(key, value) {
4070
- const setter = phGlobalConfigSetters[key];
4071
- setter(value);
4072
- }
4073
- /** Sets the global drive config.
4074
- *
4075
- * Pass in a partial object of the global drive config to set.
4076
- */
4077
- function setPHAppConfig(config) {
4078
- for (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);
4079
- }
4080
- /** Sets the global document config.
4081
- *
4082
- * Pass in a partial object of the global document config to set.
4083
- */
4084
- function setPHDocumentEditorConfig(config) {
4085
- for (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);
4086
- }
4087
- /** Wrapper hook for setting the global app config.
4088
- *
4089
- * Automatically sets the global app config when the component mounts.
4090
- *
4091
- * Pass in a partial object of the global app config to set.
4092
- */
4093
- function useSetPHAppConfig(config) {
4094
- const [isInitialized, setIsInitialized] = useState(false);
4095
- useEffect(() => {
4096
- if (isInitialized) return;
4097
- setPHAppConfig(config);
4098
- setIsInitialized(true);
4099
- }, [config, isInitialized]);
4100
- }
4101
- /** Wrapper hook for setting the global document editor config.
4102
- *
4103
- * Automatically sets the global document editor config when the component mounts.
4104
- *
4105
- * Pass in a partial object of the global document editor config to set.
4106
- */
4107
- function useSetPHDocumentEditorConfig(config) {
4108
- const [isInitialized, setIsInitialized] = useState(false);
4109
- useEffect(() => {
4110
- if (isInitialized) return;
4111
- setPHDocumentEditorConfig(config);
4112
- setIsInitialized(true);
4113
- }, [config, isInitialized]);
4114
- }
4115
- /**
4116
- * Classifies a document's model version against the installed module
4117
- * versions. Pure logic, extracted for testing.
4118
- */
4119
- function getDocumentVersionStatus(documentVersion, availableVersions, hasUpgradePath) {
4120
- if (availableVersions.length === 0) return;
4121
- const sorted = [...availableVersions].sort((a, b) => a - b);
4122
- const latestVersion = sorted[sorted.length - 1];
4123
- if (documentVersion > latestVersion) return {
4124
- kind: "unsupported",
4125
- documentVersion,
4126
- availableVersions: sorted
4127
- };
4128
- if (documentVersion === latestVersion) return {
4129
- kind: "current",
4130
- documentVersion
4131
- };
4132
- return {
4133
- kind: "upgrade-available",
4134
- documentVersion,
4135
- latestVersion,
4136
- canUpgrade: hasUpgradePath(documentVersion, latestVersion)
4137
- };
4138
- }
4139
- /**
4140
- * Compares the given document's model version against the versions available
4141
- * from installed Vetra packages. Returns undefined while packages load or
4142
- * when the document type has no installed modules.
4143
- */
4144
- function useDocumentVersionStatus(document) {
4145
- const modules = useDocumentModelModules();
4146
- const registry = useModelRegistry();
4147
- if (!document || !modules) return;
4148
- const documentType = document.header.documentType;
4149
- return getDocumentVersionStatus(document.state.document.version || 1, modules.filter((m) => m.documentModel.global.id === documentType).map((m) => m.version ?? 1), (fromVersion, toVersion) => {
4150
- if (!registry) return false;
4151
- try {
4152
- registry.computeUpgradePath(documentType, fromVersion, toVersion);
4153
- return true;
4154
- } catch {
4155
- return false;
4156
- }
4157
- });
4158
- }
4159
- const validateDocument = (document) => {
4160
- const errors = [];
4161
- if (document.header.documentType !== "powerhouse/document-model") return errors;
4162
- const doc = document;
4163
- const specs = doc.state.global.specifications[0];
4164
- const initialStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {
4165
- const scope = scopeKey;
4166
- return [...acc, ...validateInitialState(specs.state[scope].initialValue, scope !== "global").map((err) => ({
4167
- ...err,
4168
- message: `${err.message}. Scope: ${scope}`,
4169
- details: {
4170
- ...err.details,
4171
- scope
4172
- }
4173
- }))];
4174
- }, []);
4175
- const schemaStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {
4176
- const scope = scopeKey;
4177
- const isGlobalScope = scope === "global";
4178
- return [...acc, ...validateStateSchemaName(specs.state[scope].schema, doc.state.global?.name || doc.header.name || "", !isGlobalScope ? scope : "", !isGlobalScope).map((err) => ({
4179
- ...err,
4180
- message: `${err.message}. Scope: ${scope}`,
4181
- details: {
4182
- ...err.details,
4183
- scope
4184
- }
4185
- }))];
4186
- }, []);
4187
- const modulesErrors = validateModules(specs.modules);
4188
- return [
4189
- ...initialStateErrors,
4190
- ...schemaStateErrors,
4191
- ...modulesErrors
4192
- ];
4193
- };
4194
- function defaultHandleError(error) {
4195
- console.error(`Failed to export document: ${error.message}`);
4196
- }
4197
- function handleDocumentValidation(document) {
4198
- if (t$2(validateDocument(document), 1)) return false;
4199
- return true;
4200
- }
4201
- function downloadDocument(document, handleError = defaultHandleError) {
4202
- if (!document) return;
4203
- if (!handleDocumentValidation(document)) {
4204
- showPHModal({
4205
- type: "downloadDocumentWithErrors",
4206
- documentId: document.header.id
4207
- });
4208
- return;
4209
- }
4210
- exportFile(document).catch((error) => handleError(normalizeException(error)));
4211
- }
4212
- function useDownloadDocument(id) {
4213
- const getDocument = useGetDocument();
4214
- const toast = usePHToast();
4215
- return async () => {
4216
- if (!id) return;
4217
- const handleError = (error) => toast?.(`Failed to export document: ${error.message}`);
4218
- try {
4219
- downloadDocument(await getDocument(id), handleError);
4220
- } catch (error) {
4221
- handleError(error);
4222
- }
4223
- };
4224
- }
4225
- /**
4226
- * Downloads the selected drive's folder (or the whole drive when no folder
4227
- * is given) as a single zip archive mirroring the folder tree.
4228
- */
4229
- function useDownloadFolder(folderNode) {
4230
- const [selectedDrive] = useSelectedDriveSafe();
4231
- const toast = usePHToast();
4232
- return async () => {
4233
- if (!selectedDrive) return;
4234
- const name = folderNode?.name ?? selectedDrive.header.name;
4235
- toast?.(`Downloading "${name}"…`);
4236
- try {
4237
- const { entryCount, failed } = await downloadFolderZip(selectedDrive, folderNode);
4238
- toast?.(failed.length ? `Downloaded ${entryCount} files (${failed.length} failed)` : `Downloaded ${entryCount} files`);
4239
- } catch (error) {
4240
- toast?.(`Failed to download "${name}": ${error.message}`);
4241
- }
4242
- };
4243
- }
4244
- /** An editor is a drive "app" if it targets any supported drive document type. */
4245
- function isDriveEditor(module) {
4246
- const driveTypes = DRIVE_DOCUMENT_TYPES;
4247
- return module.documentTypes.some((t) => driveTypes.includes(t));
4248
- }
4249
- function useEditorModules() {
4250
- return useVetraPackages().flatMap((pkg) => pkg.editors).filter((module) => !isDriveEditor(module));
4251
- }
4252
- function useEditorModulesForDocumentType(documentType) {
4253
- const editorModules = useEditorModules();
4254
- if (!documentType) return void 0;
4255
- return editorModules?.filter((module) => module.documentTypes.includes(documentType));
4256
- }
4257
- function preloadEditorModule(module) {
4258
- const Component = module.Component;
4259
- if (typeof Component.preload === "function") return Component.preload();
4260
- const payload = Component._payload;
4261
- const init = Component._init;
4262
- if (!payload || typeof init !== "function") return void 0;
4263
- try {
4264
- init(payload);
4265
- } catch (thrown) {
4266
- if (thrown && typeof thrown.then === "function") return thrown;
4267
- }
4268
- }
4269
- function useFolderById(id) {
4270
- return useFolderNodesInSelectedDrive()?.find((n) => n.id === id);
4271
- }
4272
- function resolveNode(driveId, node) {
4273
- return node?.id !== driveId ? node : void 0;
4274
- }
4275
- function useNodeActions() {
4276
- const [selectedDrive] = useSelectedDriveSafe();
4277
- const selectedFolder = useSelectedFolder();
4278
- const selectedParentFolder = useFolderById(useSelectedNode()?.parentFolder);
4279
- const selectedDriveId = selectedDrive?.header.id;
4280
- const drives = useDrives();
4281
- async function onAddFile(file, parent) {
4282
- if (!selectedDriveId) return;
4283
- return addFileWithProgress(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id, void 0, void 0, "duplicate");
4284
- }
4285
- async function onAddFolder(name, parent) {
4286
- if (!selectedDriveId) return;
4287
- return addFolder$1(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
4288
- }
4289
- async function onRenameNode(newName, node) {
4290
- if (!selectedDriveId) return;
4291
- if (!resolveNode(selectedDriveId, node)) {
4292
- console.error(`Node ${node.id} not found`);
4293
- return;
4294
- }
4295
- return await renameNode(selectedDriveId, node.id, newName);
4296
- }
4297
- async function onCopyNode(src, target) {
4298
- if (!selectedDriveId) return;
4299
- const resolvedSrc = resolveNode(selectedDriveId, src);
4300
- if (!resolvedSrc) {
4301
- console.error(`Node ${src.id} not found`);
4302
- return;
4303
- }
4304
- await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, target));
4305
- }
4306
- async function onMoveNode(src, target) {
4307
- if (!selectedDriveId) return;
4308
- const resolvedSrc = resolveNode(selectedDriveId, src);
4309
- if (!resolvedSrc) {
4310
- console.error(`Node ${src.id} not found`);
4311
- return;
4312
- }
4313
- const resolvedTarget = resolveNode(selectedDriveId, target);
4314
- if (!resolvedTarget?.id && !src.parentFolder || resolvedTarget?.id === src.parentFolder) return;
4315
- await moveNode$1(selectedDriveId, resolvedSrc, resolvedTarget);
4316
- }
4317
- async function onDuplicateNode(src) {
4318
- if (!selectedDriveId) return;
4319
- const resolvedSrc = resolveNode(selectedDriveId, src);
4320
- if (!resolvedSrc) {
4321
- console.error(`Node ${src.id} not found`);
4322
- return;
4323
- }
4324
- await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder));
4325
- }
4326
- async function onAddAndSelectNewFolder(name) {
4327
- if (!name) return;
4328
- if (!selectedDriveId) return;
4329
- const resolvedTarget = resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder);
4330
- if (!resolvedTarget) return;
4331
- const newFolder = await onAddFolder(name, resolvedTarget);
4332
- if (newFolder) setSelectedNode(newFolder);
4333
- }
4334
- async function onRenameDriveNodes(newName, nodeId) {
4335
- if (!drives) return;
4336
- const drivesWithNode = drives.filter((drive) => drive.state.global.nodes.some((n) => n.id === nodeId));
4337
- await Promise.all(drivesWithNode.map((drive) => renameDriveNode(drive.header.id, nodeId, newName)));
4338
- }
4339
- return {
4340
- onAddFile,
4341
- onAddFolder,
4342
- onRenameNode,
4343
- onCopyNode,
4344
- onMoveNode,
4345
- onDuplicateNode,
4346
- onAddAndSelectNewFolder,
4347
- onRenameDriveNodes
4348
- };
4349
- }
4350
- /** Returns a node in the selected drive by id. */
4351
- function useNodeById(id) {
4352
- return useNodesInSelectedDrive()?.find((n) => n.id === id);
4353
- }
4354
- /** Returns the path to a node in the selected drive */
4355
- function useNodePathById(id) {
4356
- const nodes = useNodesInSelectedDrive();
4357
- if (!nodes) return [];
4358
- const path = [];
4359
- let current = nodes.find((n) => n.id === id);
4360
- while (current) {
4361
- path.push(current);
4362
- if (!current.parentFolder) break;
4363
- current = nodes.find((n) => n.id === current?.parentFolder);
4364
- }
4365
- return path.reverse();
4366
- }
4367
- /** Returns the path to the currently selected node in the selected drive. */
4368
- function useSelectedNodePath() {
4369
- return useNodePathById(useSelectedNode()?.id);
4370
- }
4371
- function useNodeParentFolderById(id) {
4372
- return useFolderById(useNodeById(id)?.parentFolder);
4373
- }
4374
- function useParentFolderForSelectedNode() {
4375
- return useNodeParentFolderById(useSelectedNode()?.id);
4376
- }
4377
- const STORED_THEME_KEY = "ph:theme";
4378
- const UPDATE_STORED_THEME = "ph:updateStoredTheme";
4379
- const STORED_THEME_UPDATED = "ph:storedThemeUpdated";
4380
- const SYSTEM_THEME_UPDATED = "ph:systemThemeUpdated";
4381
- const isServer = typeof window === "undefined";
4382
- function setTheme(storedTheme) {
4383
- if (isServer) return;
4384
- const updateStoredThemeEvent = new CustomEvent(UPDATE_STORED_THEME, { detail: { storedTheme } });
4385
- window.dispatchEvent(updateStoredThemeEvent);
4386
- }
4387
- function getStoredTheme() {
4388
- if (isServer) return void 0;
4389
- return localStorage.getItem(STORED_THEME_KEY) ?? void 0;
4390
- }
4391
- function getPrefersDarkMediaQuery() {
4392
- if (isServer) return;
4393
- return window.matchMedia("(prefers-color-scheme: dark)");
4394
- }
4395
- function getPrefersDark() {
4396
- if (isServer) return false;
4397
- if (getPrefersDarkMediaQuery()?.matches) return true;
4398
- return false;
4399
- }
4400
- function getSystemTheme() {
4401
- if (isServer) return "light";
4402
- if (getPrefersDark()) return "dark";
4403
- return "light";
4404
- }
4405
- function toggleDark(isDark) {
4406
- if (isServer) return;
4407
- document.documentElement.classList.toggle("dark", isDark);
4408
- }
4409
- function subscribeToStoredTheme(onStoreChange) {
4410
- if (isServer) return () => {};
4411
- const handleStorage = (event) => {
4412
- if (event.key === STORED_THEME_KEY || event.key === null) onStoreChange();
4413
- };
4414
- window.addEventListener(STORED_THEME_UPDATED, onStoreChange);
4415
- window.addEventListener("storage", handleStorage);
4416
- return () => {
4417
- window.removeEventListener(STORED_THEME_UPDATED, onStoreChange);
4418
- window.removeEventListener("storage", handleStorage);
4419
- };
4420
- }
4421
- function subscribeToSystemTheme(onStoreChange) {
4422
- if (isServer) return () => {};
4423
- window.addEventListener(SYSTEM_THEME_UPDATED, onStoreChange);
4424
- return () => {
4425
- window.removeEventListener(SYSTEM_THEME_UPDATED, onStoreChange);
4426
- };
4427
- }
4428
- function useTheme() {
4429
- const storedTheme = useSyncExternalStore(subscribeToStoredTheme, () => getStoredTheme(), () => "system");
4430
- const systemTheme = useSyncExternalStore(subscribeToSystemTheme, () => getSystemTheme(), () => "light");
4431
- const isSystem = storedTheme === void 0 || storedTheme === "system";
4432
- const theme = isSystem ? systemTheme : storedTheme;
4433
- const isDark = theme === "dark";
4434
- useEffect(() => {
4435
- toggleDark(isDark);
4436
- }, [isDark]);
4437
- return {
4438
- theme,
4439
- isSystem,
4440
- setTheme
4441
- };
4442
- }
4443
- const syncStatusToUI = {
4444
- [SyncStatus.Synced]: "SUCCESS",
4445
- [SyncStatus.Outgoing]: "SYNCING",
4446
- [SyncStatus.Incoming]: "SYNCING",
4447
- [SyncStatus.OutgoingAndIncoming]: "SYNCING",
4448
- [SyncStatus.Error]: "ERROR"
4449
- };
4450
- async function getDrives(reactor) {
4451
- return (await Promise.all(DRIVE_DOCUMENT_TYPES.map((type) => reactor.find({ type })))).flatMap((r) => r.results);
4452
- }
4453
- function getSyncStatusSync(documentId, sharingType) {
4454
- if (sharingType === "LOCAL") return;
4455
- const syncManager = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
4456
- if (!syncManager) return;
4457
- const status = syncManager.getSyncStatus(documentId);
4458
- if (status === void 0) return;
4459
- return syncStatusToUI[status];
4460
- }
4461
- function getDocumentGraphqlQuery() {
4462
- const loc = GetDocumentWithOperationsDocument.loc;
4463
- if (!loc) throw new Error("GetDocumentWithOperationsDocument is misconfigured, loc is missing.");
4464
- return loc.source.body;
4465
- }
4466
- /**
4467
- * The base URL of the switchboard that serves a drive's GraphQL channel.
4468
- *
4469
- * The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the
4470
- * suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does
4471
- * not end with the suffix is unexpected — fall back to its origin.
4472
- */
4473
- function getSwitchboardBaseFromChannelUrl(channelUrl) {
4474
- if (channelUrl.endsWith("/graphql/r")) return channelUrl.slice(0, -10);
4475
- return new URL(channelUrl).origin;
4476
- }
4477
- /**
4478
- * The GraphQL name the switchboard exposes a document model under. Mirrors
4479
- * `getDocumentModelSchemaName` on the server (`create-schema.ts`): the root
4480
- * query field and the state type names are all derived from the model's
4481
- * `global.name`.
4482
- */
4483
- function getDocumentModelSchemaName(model) {
4484
- return pascalCase(model.documentModel.global.name.replaceAll("/", " "));
4485
- }
4486
- function buildStateTypeMap(definitions) {
4487
- const typeMap = /* @__PURE__ */ new Map();
4488
- for (const def of definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) typeMap.set(def.name.value, def);
4489
- return typeMap;
4490
- }
4491
- /**
4492
- * Recursively expands the fields of a state object type into a GraphQL
4493
- * selection. Objects expand their sub-selection (lists expand their item
4494
- * type); enums, scalars, and built-ins are leaves.
4495
- */
4496
- function expandStateFields(typeDef, typeMap) {
4497
- return (typeDef.fields ?? []).map((field) => {
4498
- const fieldName = field.name.value;
4499
- let typeNode = field.type;
4500
- if (typeNode.kind === Kind.NON_NULL_TYPE) typeNode = typeNode.type;
4501
- if (typeNode.kind === Kind.LIST_TYPE) {
4502
- let itemType = typeNode.type;
4503
- if (itemType.kind === Kind.NON_NULL_TYPE) itemType = itemType.type;
4504
- if (itemType.kind === Kind.LIST_TYPE) throw new Error(`Nested lists are not supported in state selections: ${fieldName}`);
4505
- if (itemType.kind !== Kind.NAMED_TYPE) return fieldName;
4506
- const itemTypeDef = typeMap.get(itemType.name.value);
4507
- if (!itemTypeDef) return fieldName;
4508
- return `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;
4509
- }
4510
- if (typeNode.kind !== Kind.NAMED_TYPE) return fieldName;
4511
- const typeDef = typeMap.get(typeNode.name.value);
4512
- if (!typeDef) return fieldName;
4513
- return `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;
4514
- }).join(" ");
4515
- }
4516
- /**
4517
- * Finds the root state object type in a state SDL. Root state types follow
4518
- * the `<Name>State` / `<Name>GlobalState` conventions, and are defined last
4519
- * by convention — the same resolution order the server uses
4520
- * (`extractRootTypeName` in `create-schema.ts`).
4521
- */
4522
- function findRootStateType(definitions, candidates) {
4523
- let lastObjectType = null;
4524
- for (const def of definitions) {
4525
- if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
4526
- if (candidates.includes(def.name.value)) return def;
4527
- lastObjectType = def;
4528
- }
4529
- if (!lastObjectType) throw new Error("No root state type found in the document model schema");
4530
- return lastObjectType;
4531
- }
4532
- /**
4533
- * Derives the subselection for the document's `global` state scope from the
4534
- * model's state SDL (e.g. `name total`), expanding object fields
4535
- * recursively. Throws when the schema is missing, unparseable, or has no
4536
- * root object type — the caller falls back to the generic document query.
4537
- */
4538
- function getDocumentStateSelection(model) {
4539
- const schema = model.documentModel.global.specifications.at(-1)?.state.global.schema;
4540
- if (!schema || !schema.trim()) throw new Error("Document model has no global state schema");
4541
- const ast = parse(schema);
4542
- const typeMap = buildStateTypeMap(ast.definitions);
4543
- const documentName = getDocumentModelSchemaName(model);
4544
- return expandStateFields(findRootStateType(ast.definitions, [`${documentName}State`, `${documentName}GlobalState`]), typeMap);
4545
- }
4546
- function getLocalStateSelection(localSchema, documentName) {
4547
- const ast = parse(localSchema);
4548
- const typeMap = buildStateTypeMap(ast.definitions);
4549
- return expandStateFields(findRootStateType(ast.definitions, [`${documentName}LocalState`]), typeMap);
4550
- }
4551
- /**
4552
- * Builds a query scoped to a document type's own subgraph root field,
4553
- * selecting the document and its full typed state. The shape mirrors what
4554
- * the switchboard generates per model (`generateNewApiSchema` in
4555
- * `create-schema.ts`): `<Name> { document(identifier:) { document { ...
4556
- * state { auth document global local } } } childIds }`.
4557
- */
4558
- function buildModelScopedQuery(model) {
4559
- const globalState = model.documentModel.global;
4560
- const documentName = getDocumentModelSchemaName(model);
4561
- const globalSelection = getDocumentStateSelection(model);
4562
- const localSchema = globalState.specifications.at(-1)?.state.local.schema ?? "";
4563
- const localSelection = localSchema.includes(`type ${documentName}LocalState`) ? getLocalStateSelection(localSchema, documentName) : null;
4564
- return [
4565
- "query GetDocument($identifier: String!) {",
4566
- ` ${documentName} {`,
4567
- " document(identifier: $identifier) {",
4568
- " document {",
4569
- " id",
4570
- " name",
4571
- " documentType",
4572
- " state {",
4573
- " auth",
4574
- " document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }",
4575
- ` global { ${globalSelection} }`,
4576
- ` ${localSelection ? `local { ${localSelection} }` : "local"}`,
4577
- " }",
4578
- " }",
4579
- " childIds",
4580
- " }",
4581
- " }",
4582
- "}"
4583
- ].join("\n");
4584
- }
4585
- function buildDocumentSubgraphQuery(documentType, identifier, model, authToken) {
4586
- let query;
4587
- if (model && model.documentModel.global.id === documentType) try {
4588
- query = buildModelScopedQuery(model);
4589
- } catch (error) {
4590
- console.warn("Could not derive a document-scoped query from the document model, falling back to the generic document query:", error);
4591
- query = getDocumentGraphqlQuery();
4592
- }
4593
- else query = getDocumentGraphqlQuery();
4594
- const variables = { identifier };
4595
- const headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;
4596
- const payload = {
4597
- document: query.trim(),
4598
- variables: JSON.stringify(variables, null, 2)
4599
- };
4600
- if (headers) payload.headers = JSON.stringify(headers);
4601
- return import_lz_string.default.compressToEncodedURIComponent(JSON.stringify(payload));
4602
- }
4603
- function buildDocumentSubgraphUrl(channelUrl, documentType, identifier, model, authToken) {
4604
- const encodedQuery = buildDocumentSubgraphQuery(documentType, identifier, model, authToken);
4605
- return `${getSwitchboardBaseFromChannelUrl(channelUrl)}/explorer?explorerURLState=${encodedQuery}`;
4606
- }
4607
- /**
4608
- * Hook that returns a function to generate a document's switchboard URL.
4609
- * Only returns a function for documents in remote drives.
4610
- * Returns null for local drives or when the document/drive cannot be determined.
4611
- *
4612
- * The returned function generates a fresh bearer token and builds the switchboard URL
4613
- * with authentication when called.
4614
- *
4615
- * @param document - The document to create a switchboard URL generator for
4616
- * @returns An async function that returns the switchboard URL, or null if not applicable
4617
- */
4618
- function useGetSwitchboardLink(document) {
4619
- const [drive] = useSelectedDriveSafe();
4620
- const remotes = useSyncList();
4621
- const documentModelModule = useDocumentModelModuleById(document?.header.documentType);
4622
- const isRemoteDrive = useMemo(() => {
4623
- if (!e$4(drive)) return false;
4624
- return remotes.some((remote) => remote.meta.collectionId.equals(DriveCollectionId.forDrive(drive.header.id)));
4625
- }, [remotes, drive]);
4626
- const remoteUrl = useMemo(() => {
4627
- if (!e$4(drive)) return null;
4628
- try {
4629
- const channelUrl = (remotes.find((remote) => remote.meta.collectionId.equals(DriveCollectionId.forDrive(drive.header.id)))?.channel)?.config.url;
4630
- if (typeof channelUrl === "string") return channelUrl;
4631
- return null;
4632
- } catch (error) {
4633
- console.error("Error determining remote URL:", error);
4634
- return null;
4635
- }
4636
- }, [remotes, drive]);
4637
- const renown = useRenown();
4638
- const user = useUser();
4639
- return useMemo(() => {
4640
- if (!isRemoteDrive || !document?.header.id || !remoteUrl) return null;
4641
- return async () => {
4642
- const token = user?.address ? await renown?.getBearerToken({
4643
- expiresIn: 600,
4644
- aud: remoteUrl
4645
- }) : void 0;
4646
- return buildDocumentSubgraphUrl(remoteUrl, document.header.documentType, document.header.id, documentModelModule, token);
4647
- };
4648
- }, [
4649
- isRemoteDrive,
4650
- remoteUrl,
4651
- document,
4652
- documentModelModule,
4653
- user,
4654
- renown
4655
- ]);
4656
- }
4657
- function useUserPermissions() {
4658
- const user = useUser();
4659
- const allowList = useAllowList();
4660
- if (!allowList) return {
4661
- isAllowedToCreateDocuments: true,
4662
- isAllowedToEditDocuments: true
4663
- };
4664
- return {
4665
- isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
4666
- isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
4667
- };
4668
- }
4669
- const DEFAULT_DEBOUNCE_DELAY_MS = 200;
4670
- const DEFAULT_IMMEDIATE_THRESHOLD_MS = 1e3;
4671
- async function _refreshReactorData(reactor) {
4672
- setDrives(await getDrives(reactor));
4673
- }
4674
- async function _refreshReactorDataClient(reactor) {
4675
- if (!reactor) return;
4676
- setDrives(await getDrives(reactor));
4677
- }
4678
- function createDebouncedRefreshReactorData(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {
4679
- let timeout = null;
4680
- let lastRefreshTime = 0;
4681
- return (reactor, immediate = false) => {
4682
- const now = Date.now();
4683
- const timeSinceLastRefresh = now - lastRefreshTime;
4684
- if (timeout !== null) clearTimeout(timeout);
4685
- if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {
4686
- lastRefreshTime = now;
4687
- return _refreshReactorData(reactor);
4688
- }
4689
- return new Promise((resolve) => {
4690
- timeout = setTimeout(() => {
4691
- lastRefreshTime = Date.now();
4692
- _refreshReactorData(reactor).then(resolve);
4693
- }, debounceDelayMs);
4694
- });
4695
- };
4696
- }
4697
- function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {
4698
- let timeout = null;
4699
- let lastRefreshTime = 0;
4700
- return (reactor, immediate = false) => {
4701
- const now = Date.now();
4702
- const timeSinceLastRefresh = now - lastRefreshTime;
4703
- if (timeout !== null) clearTimeout(timeout);
4704
- if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {
4705
- lastRefreshTime = now;
4706
- return _refreshReactorDataClient(reactor);
4707
- }
4708
- return new Promise((resolve) => {
4709
- timeout = setTimeout(() => {
4710
- lastRefreshTime = Date.now();
4711
- _refreshReactorDataClient(reactor).then(resolve);
4712
- }, debounceDelayMs);
4713
- });
4714
- };
4715
- }
4716
- createDebouncedRefreshReactorData();
4717
- createDebouncedRefreshReactorDataClient();
4718
- //#endregion
4719
- export { useDropNode as A, setSelectedNode as B, addDocument as C, showRevisionHistory as D, showPHModal as E, t$2 as F, useSelectedDriveSafe as H, t$5 as I, isFileNodeKind as L, useStudioMode as M, e$1 as N, useDisabledEditors as O, e$4 as P, isFolderNodeKind as R, useSelectedDocumentSafe as S, showDeleteNodeModal as T, useDocumentById as U, useSelectedDriveId as V, useSetPHAppConfig as _, useDownloadDocument as a, useUserPermissions as b, useEditorModulesForDocumentType as c, useNodeById as d, useNodeParentFolderById as f, useSelectedNodePath as g, useSelectedFolder as h, useDocumentVersionStatus as i, usePHToast as j, useDragNode as k, useGetSwitchboardLink as l, useParentFolderForSelectedNode as m, preloadEditorModule as n, useDownloadFolder as o, useNodesInSelectedDriveOrFolder as p, useAllowedDocumentModelModules as r, useEditorModules as s, getSyncStatusSync as t, useNodeActions as u, useSetPHDocumentEditorConfig as v, addFolder$1 as w, useSelectedDocumentOfType as x, useTheme as y, setSelectedDrive as z };
4720
-
4721
- //# sourceMappingURL=dist-D0tSbK8B.js.map