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