@powerhousedao/powerhouse-vetra-packages 6.1.0-dev.2 → 6.1.0-dev.21

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 (119) hide show
  1. package/dist/browser/assets/entry-Bzani6_n.js +313 -0
  2. package/dist/browser/assets/projection-entry-Bpu-8SnI.js +406 -0
  3. package/dist/browser/{dist-DOMEWT3x.js → connect-ZnLjvmRt.js} +13013 -10302
  4. package/dist/browser/connect-ZnLjvmRt.js.map +1 -0
  5. package/dist/browser/dist-C1nRM9t2.js +3768 -0
  6. package/dist/browser/dist-C1nRM9t2.js.map +1 -0
  7. package/dist/browser/{schemas-Bqem6NRm.js → dist-CXoKspdx.js} +131 -2
  8. package/dist/browser/dist-CXoKspdx.js.map +1 -0
  9. package/dist/browser/dist-D8H48e8N.js +2692 -0
  10. package/dist/browser/dist-D8H48e8N.js.map +1 -0
  11. package/dist/browser/{dist-CC1E3l2O.js → dist-DLFI75Zd.js} +37 -9
  12. package/dist/browser/dist-DLFI75Zd.js.map +1 -0
  13. package/dist/browser/{dist-DQgJ8n4d.js → document-drive-oqv68jDU.js} +432 -290
  14. package/dist/browser/document-drive-oqv68jDU.js.map +1 -0
  15. package/dist/browser/document-models/index.js +1 -1
  16. package/dist/browser/{documents-Bpu0aSLb.js → documents-D4ek7Ubv.js} +3 -3
  17. package/dist/browser/{documents-Bpu0aSLb.js.map → documents-D4ek7Ubv.js.map} +1 -1
  18. package/dist/browser/{editor-B3yz7YdR.js → editor-CoTq6fqT.js} +32 -31
  19. package/dist/browser/editor-CoTq6fqT.js.map +1 -0
  20. package/dist/browser/{editor-Dm_73jiz.js → editor-DC3bigBu.js} +5 -5
  21. package/dist/browser/{editor-Dm_73jiz.js.map → editor-DC3bigBu.js.map} +1 -1
  22. package/dist/browser/editors/document-model-editor/module.js +1 -1
  23. package/dist/browser/editors/generic-drive-explorer/index.js +6 -6
  24. package/dist/browser/editors/generic-drive-explorer/index.js.map +1 -1
  25. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  26. package/dist/browser/{folder-view-H2ov-zId.js → folder-view-DmYBf2pP.js} +13 -12
  27. package/dist/browser/folder-view-DmYBf2pP.js.map +1 -0
  28. package/dist/browser/{graphql-editor-CnaQ3XWx.js → graphql-editor-CiGd_Li7.js} +15 -7
  29. package/dist/browser/{graphql-editor-CnaQ3XWx.js.map → graphql-editor-CiGd_Li7.js.map} +1 -1
  30. package/dist/{node/hooks-Lbsf6g-v.mjs → browser/hooks-CORHBNHb.js} +6 -4
  31. package/dist/browser/{hooks-Beny0xpe.js.map → hooks-CORHBNHb.js.map} +1 -1
  32. package/dist/browser/index.js +2 -2
  33. package/dist/{node/json-editor-CVGgDVh2.mjs → browser/json-editor-sEqd5piI.js} +12 -4
  34. package/dist/browser/json-editor-sEqd5piI.js.map +1 -0
  35. package/dist/browser/{style-DYS_RFSN.js → linting-Dn6pXRkK.js} +7 -14
  36. package/dist/browser/linting-Dn6pXRkK.js.map +1 -0
  37. package/dist/browser/{parser-B0sh99Kk.js → parser-CkF6Qt8V.js} +1 -1
  38. package/dist/browser/{parser-B0sh99Kk.js.map → parser-CkF6Qt8V.js.map} +1 -1
  39. package/dist/browser/{schema-context-C0GpuR27.js → schema-context-DY-GEGnY.js} +4 -4
  40. package/dist/browser/schema-context-DY-GEGnY.js.map +1 -0
  41. package/dist/browser/state-schemas-DJmzG_M8.js +308 -0
  42. package/dist/browser/state-schemas-DJmzG_M8.js.map +1 -0
  43. package/dist/node/{dist-1kPMPFPD.mjs → connect-BLC4PXD9.mjs} +13953 -11229
  44. package/dist/node/connect-BLC4PXD9.mjs.map +1 -0
  45. package/dist/node/dist-BeZaEP6S.mjs +2692 -0
  46. package/dist/node/dist-BeZaEP6S.mjs.map +1 -0
  47. package/dist/node/dist-Bm05eoTg.mjs +3769 -0
  48. package/dist/node/dist-Bm05eoTg.mjs.map +1 -0
  49. package/dist/node/{tslib.es6-DwVpIYUS.mjs → dist-Cn3iExnV.mjs} +489 -3
  50. package/dist/node/dist-Cn3iExnV.mjs.map +1 -0
  51. package/dist/node/{schemas-Cb8uEF9u.mjs → dist-fA4EItr0.mjs} +131 -2
  52. package/dist/node/dist-fA4EItr0.mjs.map +1 -0
  53. package/dist/node/{dist-Bz4SgEHs.mjs → document-drive-sM33juXr.mjs} +432 -290
  54. package/dist/node/document-drive-sM33juXr.mjs.map +1 -0
  55. package/dist/node/document-models/index.mjs +1 -1
  56. package/dist/node/{documents-BWJpUm9f.mjs → documents-BFBPmyw1.mjs} +3 -3
  57. package/dist/node/{documents-BWJpUm9f.mjs.map → documents-BFBPmyw1.mjs.map} +1 -1
  58. package/dist/node/{editor-W8QOlGXD.mjs → editor-BFBa9nsO.mjs} +32 -31
  59. package/dist/node/editor-BFBa9nsO.mjs.map +1 -0
  60. package/dist/node/{editor-BaXuDsby.mjs → editor-BrS98lEH.mjs} +5 -5
  61. package/dist/node/{editor-BaXuDsby.mjs.map → editor-BrS98lEH.mjs.map} +1 -1
  62. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  63. package/dist/node/editors/generic-drive-explorer/index.mjs +6 -6
  64. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  65. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  66. package/dist/node/{folder-view-B0FNXbc0.mjs → folder-view-DHph3Yuu.mjs} +13 -12
  67. package/dist/node/folder-view-DHph3Yuu.mjs.map +1 -0
  68. package/dist/node/{graphql-Du2phcBf.mjs → graphql-DskHmkMe.mjs} +2 -2
  69. package/dist/node/{graphql-Du2phcBf.mjs.map → graphql-DskHmkMe.mjs.map} +1 -1
  70. package/dist/node/{graphql-editor-D1koK5kR.mjs → graphql-editor-CPq7oIbf.mjs} +14 -6
  71. package/dist/node/{graphql-editor-D1koK5kR.mjs.map → graphql-editor-CPq7oIbf.mjs.map} +1 -1
  72. package/dist/{browser/hooks-Beny0xpe.js → node/hooks-DJrjfVaS.mjs} +6 -4
  73. package/dist/node/{hooks-Lbsf6g-v.mjs.map → hooks-DJrjfVaS.mjs.map} +1 -1
  74. package/dist/node/index.mjs +2 -2
  75. package/dist/{browser/json-editor-h3cffF6X.js → node/json-editor-L32CP7TS.mjs} +12 -4
  76. package/dist/node/json-editor-L32CP7TS.mjs.map +1 -0
  77. package/dist/node/{style-CxHkfyna.mjs → linting-Dx50GuLN.mjs} +7 -14
  78. package/dist/node/linting-Dx50GuLN.mjs.map +1 -0
  79. package/dist/node/{schema-context-mLgEY1Hh.mjs → schema-context-CX5ml_9t.mjs} +4 -4
  80. package/dist/node/schema-context-CX5ml_9t.mjs.map +1 -0
  81. package/dist/node/state-schemas-XTTjQZOe.mjs +309 -0
  82. package/dist/node/state-schemas-XTTjQZOe.mjs.map +1 -0
  83. package/package.json +10 -10
  84. package/style.css +1 -0
  85. package/dist/browser/connect-CKdlDSUw.js +0 -9460
  86. package/dist/browser/connect-CKdlDSUw.js.map +0 -1
  87. package/dist/browser/dist-BXygvBtd.js +0 -132
  88. package/dist/browser/dist-BXygvBtd.js.map +0 -1
  89. package/dist/browser/dist-CC1E3l2O.js.map +0 -1
  90. package/dist/browser/dist-DOMEWT3x.js.map +0 -1
  91. package/dist/browser/dist-DQgJ8n4d.js.map +0 -1
  92. package/dist/browser/editor-B3yz7YdR.js.map +0 -1
  93. package/dist/browser/folder-view-H2ov-zId.js.map +0 -1
  94. package/dist/browser/json-editor-h3cffF6X.js.map +0 -1
  95. package/dist/browser/schema-context-C0GpuR27.js.map +0 -1
  96. package/dist/browser/schemas-Bqem6NRm.js.map +0 -1
  97. package/dist/browser/state-schemas-C5NPeV6-.js +0 -674
  98. package/dist/browser/state-schemas-C5NPeV6-.js.map +0 -1
  99. package/dist/browser/style-DYS_RFSN.js.map +0 -1
  100. package/dist/browser/tslib.es6-DRuVAsR8.js +0 -32
  101. package/dist/browser/tslib.es6-DRuVAsR8.js.map +0 -1
  102. package/dist/node/connect-SGvLzr5K.mjs +0 -9475
  103. package/dist/node/connect-SGvLzr5K.mjs.map +0 -1
  104. package/dist/node/dist-1kPMPFPD.mjs.map +0 -1
  105. package/dist/node/dist-BQTIepWC.mjs +0 -132
  106. package/dist/node/dist-BQTIepWC.mjs.map +0 -1
  107. package/dist/node/dist-Bz4SgEHs.mjs.map +0 -1
  108. package/dist/node/dist-Cay1iRRr.mjs +0 -491
  109. package/dist/node/dist-Cay1iRRr.mjs.map +0 -1
  110. package/dist/node/editor-W8QOlGXD.mjs.map +0 -1
  111. package/dist/node/folder-view-B0FNXbc0.mjs.map +0 -1
  112. package/dist/node/json-editor-CVGgDVh2.mjs.map +0 -1
  113. package/dist/node/schema-context-mLgEY1Hh.mjs.map +0 -1
  114. package/dist/node/schemas-Cb8uEF9u.mjs.map +0 -1
  115. package/dist/node/state-schemas-DAthoEEk.mjs +0 -675
  116. package/dist/node/state-schemas-DAthoEEk.mjs.map +0 -1
  117. package/dist/node/style-CxHkfyna.mjs.map +0 -1
  118. package/dist/node/tslib.es6-DwVpIYUS.mjs.map +0 -1
  119. package/dist/style.css +0 -906
@@ -0,0 +1,3768 @@
1
+ import { E as __commonJSMin, k as __toESM, t as capitalCase } from "./dist-CXoKspdx.js";
2
+ import { A as replayDocument, J as validateStateSchemaName, K as validateInitialState, S as createZip, Y as generateId, _ as baseSaveToFileHandle, a as handleTargetNameCollisions, c as moveNode, d as logger, g as baseLoadFromInput, i as generateNodesCopy, l as updateNode, n as copyNode, o as isFileNode, q as validateModules, r as driveDocumentModelModule, s as isFolderNode, t as addFolder$1, u as documentModelDocumentModelModule, v as buildSignedAction, y as createPresignedHeader, z as setName } from "./document-drive-oqv68jDU.js";
3
+ import { c as driveCollectionId, n as gql, o as SyncStatus, s as ModuleNotFoundError, t as reactorDriveDocumentModelModule } from "./dist-DLFI75Zd.js";
4
+ import { Children, cloneElement, forwardRef, isValidElement, use, useEffect, useMemo, useState, useSyncExternalStore } from "react";
5
+ import "react/jsx-runtime";
6
+ //#region ../reactor-browser/dist/make-ph-event-functions-DwiD1zH9.js
7
+ const isServer$1 = typeof window === "undefined";
8
+ function makePHEventFunctions(key) {
9
+ const setEventName = `ph:set${capitalCase(key)}`;
10
+ const updateEventName = `ph:${key}Updated`;
11
+ function setValue(value) {
12
+ if (isServer$1) return;
13
+ const event = new CustomEvent(setEventName, { detail: { [key]: value } });
14
+ window.dispatchEvent(event);
15
+ }
16
+ function dispatchUpdatedEvent() {
17
+ if (isServer$1) return;
18
+ const event = new CustomEvent(updateEventName);
19
+ window.dispatchEvent(event);
20
+ }
21
+ function handleSetValueEvent(event) {
22
+ if (isServer$1) return;
23
+ const value = event.detail[key];
24
+ if (!window.ph) window.ph = {};
25
+ window.ph[key] = value;
26
+ dispatchUpdatedEvent();
27
+ }
28
+ function addEventHandler() {
29
+ if (isServer$1) return;
30
+ window.addEventListener(setEventName, handleSetValueEvent);
31
+ }
32
+ function subscribeToValue(onStoreChange) {
33
+ if (isServer$1) return () => {};
34
+ window.addEventListener(updateEventName, onStoreChange);
35
+ return () => {
36
+ window.removeEventListener(updateEventName, onStoreChange);
37
+ };
38
+ }
39
+ function getSnapshot() {
40
+ if (isServer$1) return;
41
+ return window.ph?.[key];
42
+ }
43
+ function getServerSnapshot() {}
44
+ function useValue() {
45
+ return useSyncExternalStore(subscribeToValue, getSnapshot, getServerSnapshot);
46
+ }
47
+ return {
48
+ useValue,
49
+ setValue,
50
+ addEventHandler
51
+ };
52
+ }
53
+ //#endregion
54
+ //#region ../reactor-browser/dist/document-by-id-BrIy0iHX.js
55
+ async function queueActions(document, actionOrActions) {
56
+ if (!document) throw new Error("No document provided");
57
+ if (!actionOrActions) throw new Error("No actions provided");
58
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
59
+ if (actions.length === 0) throw new Error("No actions provided");
60
+ const reactorClient = window.ph?.reactorClient;
61
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
62
+ return await reactorClient.execute(document.header.id, "main", actions);
63
+ }
64
+ async function queueOperations(documentId, operationOrOperations) {
65
+ if (!documentId) throw new Error("No documentId provided");
66
+ if (!operationOrOperations) throw new Error("No operations provided");
67
+ const operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];
68
+ if (operations.length === 0) throw new Error("No operations provided");
69
+ const reactorClient = window.ph?.reactorClient;
70
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
71
+ const actions = operations.map((op) => op.action);
72
+ return await reactorClient.execute(documentId, "main", actions);
73
+ }
74
+ async function uploadOperations(documentId, allOperations, pushOperations, options) {
75
+ const operationsLimit = options?.operationsLimit || 50;
76
+ const onProgress = options?.onProgress;
77
+ logger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(",")}, limit:${operationsLimit})`);
78
+ const allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);
79
+ const totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);
80
+ let uploadedOperations = 0;
81
+ for (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {
82
+ logger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);
83
+ const chunk = operations.slice(i, i + operationsLimit);
84
+ const operation = chunk.at(-1);
85
+ if (!operation) break;
86
+ const scope = operation.action.scope;
87
+ await pushOperations(documentId, chunk);
88
+ uploadedOperations += chunk.length;
89
+ if (onProgress) onProgress({
90
+ stage: "uploading",
91
+ progress: Math.round(uploadedOperations / totalOperations * 100),
92
+ totalOperations,
93
+ uploadedOperations
94
+ });
95
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);
96
+ }
97
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
98
+ }
99
+ async function signAction(action, document) {
100
+ const reactor = window.ph?.reactorClient;
101
+ if (!reactor) return action;
102
+ const reducer = (await reactor.getDocumentModelModule(document.header.documentType)).reducer;
103
+ const renown = window.ph?.renown;
104
+ if (!renown?.user) return action;
105
+ if (!action.context?.signer) return action;
106
+ const actionSigner = action.context.signer;
107
+ return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
108
+ }
109
+ function addActionContext(action) {
110
+ const renown = window.ph?.renown;
111
+ if (!renown?.user) return action;
112
+ return {
113
+ context: { signer: {
114
+ app: {
115
+ name: "Connect",
116
+ key: renown.did
117
+ },
118
+ user: {
119
+ address: renown.user.address,
120
+ networkId: renown.user.networkId,
121
+ chainId: renown.user.chainId
122
+ },
123
+ signatures: []
124
+ } },
125
+ ...action
126
+ };
127
+ }
128
+ async function makeSignedActionWithContext(action, document) {
129
+ if (!action) {
130
+ logger.error("No action found");
131
+ return;
132
+ }
133
+ if (!document) {
134
+ logger.error("No document found");
135
+ return;
136
+ }
137
+ return addActionContext(await signAction(action, document));
138
+ }
139
+ async function makeSignedActionsWithContext(actionOrActions, document) {
140
+ if (!actionOrActions) {
141
+ logger.error("No actions found");
142
+ return;
143
+ }
144
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
145
+ return (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);
146
+ }
147
+ async function getDocument(documentId) {
148
+ try {
149
+ return await window.ph?.reactorClient?.get(documentId);
150
+ } catch (error) {
151
+ logger.debug(`Failed to get document with id ${documentId}:`, error);
152
+ return;
153
+ }
154
+ }
155
+ function getActionErrors(result, actions) {
156
+ return actions.reduce((errors, a) => {
157
+ const scopeOperations = result.operations[a.scope];
158
+ if (!scopeOperations) return errors;
159
+ const op = scopeOperations.findLast((op) => op.action.id === a.id);
160
+ if (op?.error) errors.push(new Error(op.error));
161
+ return errors;
162
+ }, new Array());
163
+ }
164
+ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
165
+ const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
166
+ if (!document) {
167
+ logger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);
168
+ return;
169
+ }
170
+ const signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);
171
+ if (!signedActionsWithContext) {
172
+ logger.error("No signed actions with context found");
173
+ return;
174
+ }
175
+ const result = await queueActions(document, signedActionsWithContext);
176
+ if (onErrors && result) {
177
+ const errors = getActionErrors(result, signedActionsWithContext);
178
+ if (errors.length) onErrors(errors);
179
+ }
180
+ if (onSuccess && result) onSuccess(result);
181
+ return result;
182
+ }
183
+ const documentEventFunctions = makePHEventFunctions("documentCache");
184
+ /** Returns all documents in the reactor. */
185
+ const useDocumentCache = documentEventFunctions.useValue;
186
+ documentEventFunctions.setValue;
187
+ documentEventFunctions.addEventHandler;
188
+ /**
189
+ * Retrieves a document from the reactor and subscribes to changes using React Suspense.
190
+ * This hook will suspend rendering while the document is loading.
191
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
192
+ * @returns The document if found, or undefined if id is null/undefined
193
+ */
194
+ function useDocument(id) {
195
+ const documentCache = useDocumentCache();
196
+ const document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);
197
+ return document ? use(document) : void 0;
198
+ }
199
+ function useDispatch(document) {
200
+ /**
201
+ * Dispatches actions to the document.
202
+ * @param actionOrActions - The action or actions to dispatch.
203
+ * @param onErrors - Callback invoked with any errors that occurred during action execution.
204
+ */
205
+ function dispatch(actionOrActions, onErrors, onSuccess) {
206
+ dispatchActions(actionOrActions, document, onErrors, onSuccess).catch(logger.error);
207
+ }
208
+ return [document, dispatch];
209
+ }
210
+ /** Returns a document by id. */
211
+ function useDocumentById(id) {
212
+ const document = useDocument(id);
213
+ const [, dispatch] = useDispatch(document);
214
+ return [document, dispatch];
215
+ }
216
+ //#endregion
217
+ //#region ../reactor-browser/dist/client-D7hUM13i.js
218
+ const PhDocumentFieldsFragmentDoc = gql`
219
+ fragment PHDocumentFields on PHDocument {
220
+ id
221
+ slug
222
+ name
223
+ documentType
224
+ state
225
+ revisionsList {
226
+ scope
227
+ revision
228
+ }
229
+ createdAtUtcIso
230
+ lastModifiedAtUtcIso
231
+ }
232
+ `;
233
+ gql`
234
+ query GetDocumentModels($namespace: String, $paging: PagingInput) {
235
+ documentModels(namespace: $namespace, paging: $paging) {
236
+ items {
237
+ id
238
+ name
239
+ namespace
240
+ version
241
+ specification
242
+ }
243
+ totalCount
244
+ hasNextPage
245
+ hasPreviousPage
246
+ cursor
247
+ }
248
+ }
249
+ `;
250
+ const GetDocumentDocument = gql`
251
+ query GetDocument($identifier: String!, $view: ViewFilterInput) {
252
+ document(identifier: $identifier, view: $view) {
253
+ document {
254
+ ...PHDocumentFields
255
+ }
256
+ childIds
257
+ }
258
+ }
259
+ ${PhDocumentFieldsFragmentDoc}
260
+ `;
261
+ const GetDocumentWithOperationsDocument = gql`
262
+ query GetDocumentWithOperations(
263
+ $identifier: String!
264
+ $view: ViewFilterInput
265
+ $operationsFilter: DocumentOperationsFilterInput
266
+ $operationsPaging: PagingInput
267
+ ) {
268
+ document(identifier: $identifier, view: $view) {
269
+ document {
270
+ ...PHDocumentFields
271
+ operations(filter: $operationsFilter, paging: $operationsPaging) {
272
+ items {
273
+ index
274
+ timestampUtcMs
275
+ hash
276
+ skip
277
+ error
278
+ id
279
+ action {
280
+ id
281
+ type
282
+ timestampUtcMs
283
+ input
284
+ scope
285
+ attachments {
286
+ data
287
+ mimeType
288
+ hash
289
+ extension
290
+ fileName
291
+ }
292
+ context {
293
+ signer {
294
+ user {
295
+ address
296
+ networkId
297
+ chainId
298
+ }
299
+ app {
300
+ name
301
+ key
302
+ }
303
+ signatures
304
+ }
305
+ }
306
+ }
307
+ }
308
+ totalCount
309
+ hasNextPage
310
+ hasPreviousPage
311
+ cursor
312
+ }
313
+ }
314
+ childIds
315
+ }
316
+ }
317
+ ${PhDocumentFieldsFragmentDoc}
318
+ `;
319
+ gql`
320
+ query GetDocumentOutgoingRelationships(
321
+ $sourceIdentifier: String!
322
+ $relationshipType: String!
323
+ $view: ViewFilterInput
324
+ $paging: PagingInput
325
+ ) {
326
+ documentOutgoingRelationships(
327
+ sourceIdentifier: $sourceIdentifier
328
+ relationshipType: $relationshipType
329
+ view: $view
330
+ paging: $paging
331
+ ) {
332
+ items {
333
+ ...PHDocumentFields
334
+ }
335
+ totalCount
336
+ hasNextPage
337
+ hasPreviousPage
338
+ cursor
339
+ }
340
+ }
341
+ ${PhDocumentFieldsFragmentDoc}
342
+ `;
343
+ gql`
344
+ query GetDocumentIncomingRelationships(
345
+ $targetIdentifier: String!
346
+ $relationshipType: String!
347
+ $view: ViewFilterInput
348
+ $paging: PagingInput
349
+ ) {
350
+ documentIncomingRelationships(
351
+ targetIdentifier: $targetIdentifier
352
+ relationshipType: $relationshipType
353
+ view: $view
354
+ paging: $paging
355
+ ) {
356
+ items {
357
+ ...PHDocumentFields
358
+ }
359
+ totalCount
360
+ hasNextPage
361
+ hasPreviousPage
362
+ cursor
363
+ }
364
+ }
365
+ ${PhDocumentFieldsFragmentDoc}
366
+ `;
367
+ gql`
368
+ query FindDocuments(
369
+ $search: SearchFilterInput
370
+ $view: ViewFilterInput
371
+ $paging: PagingInput
372
+ ) {
373
+ findDocuments(search: $search, view: $view, paging: $paging) {
374
+ items {
375
+ ...PHDocumentFields
376
+ }
377
+ totalCount
378
+ hasNextPage
379
+ hasPreviousPage
380
+ cursor
381
+ }
382
+ }
383
+ ${PhDocumentFieldsFragmentDoc}
384
+ `;
385
+ const GetDocumentOperationsDocument = gql`
386
+ query GetDocumentOperations(
387
+ $filter: OperationsFilterInput!
388
+ $paging: PagingInput
389
+ ) {
390
+ documentOperations(filter: $filter, paging: $paging) {
391
+ items {
392
+ index
393
+ timestampUtcMs
394
+ hash
395
+ skip
396
+ error
397
+ id
398
+ action {
399
+ id
400
+ type
401
+ timestampUtcMs
402
+ input
403
+ scope
404
+ attachments {
405
+ data
406
+ mimeType
407
+ hash
408
+ extension
409
+ fileName
410
+ }
411
+ context {
412
+ signer {
413
+ user {
414
+ address
415
+ networkId
416
+ chainId
417
+ }
418
+ app {
419
+ name
420
+ key
421
+ }
422
+ signatures
423
+ }
424
+ }
425
+ }
426
+ }
427
+ totalCount
428
+ hasNextPage
429
+ hasPreviousPage
430
+ cursor
431
+ }
432
+ }
433
+ `;
434
+ gql`
435
+ query GetJobStatus($jobId: String!) {
436
+ jobStatus(jobId: $jobId) {
437
+ id
438
+ status
439
+ result
440
+ error
441
+ createdAt
442
+ completedAt
443
+ }
444
+ }
445
+ `;
446
+ gql`
447
+ mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
448
+ createDocument(document: $document, parentIdentifier: $parentIdentifier) {
449
+ ...PHDocumentFields
450
+ }
451
+ }
452
+ ${PhDocumentFieldsFragmentDoc}
453
+ `;
454
+ gql`
455
+ mutation CreateEmptyDocument(
456
+ $documentType: String!
457
+ $parentIdentifier: String
458
+ ) {
459
+ createEmptyDocument(
460
+ documentType: $documentType
461
+ parentIdentifier: $parentIdentifier
462
+ ) {
463
+ ...PHDocumentFields
464
+ }
465
+ }
466
+ ${PhDocumentFieldsFragmentDoc}
467
+ `;
468
+ gql`
469
+ mutation MutateDocument(
470
+ $documentIdentifier: String!
471
+ $actions: [JSONObject!]!
472
+ $view: ViewFilterInput
473
+ ) {
474
+ mutateDocument(
475
+ documentIdentifier: $documentIdentifier
476
+ actions: $actions
477
+ view: $view
478
+ ) {
479
+ ...PHDocumentFields
480
+ }
481
+ }
482
+ ${PhDocumentFieldsFragmentDoc}
483
+ `;
484
+ gql`
485
+ mutation MutateDocumentAsync(
486
+ $documentIdentifier: String!
487
+ $actions: [JSONObject!]!
488
+ $view: ViewFilterInput
489
+ ) {
490
+ mutateDocumentAsync(
491
+ documentIdentifier: $documentIdentifier
492
+ actions: $actions
493
+ view: $view
494
+ )
495
+ }
496
+ `;
497
+ gql`
498
+ mutation RenameDocument(
499
+ $documentIdentifier: String!
500
+ $name: String!
501
+ $branch: String
502
+ ) {
503
+ renameDocument(
504
+ documentIdentifier: $documentIdentifier
505
+ name: $name
506
+ branch: $branch
507
+ ) {
508
+ ...PHDocumentFields
509
+ }
510
+ }
511
+ ${PhDocumentFieldsFragmentDoc}
512
+ `;
513
+ gql`
514
+ mutation SetPreferredEditor(
515
+ $documentIdentifier: String!
516
+ $preferredEditor: String
517
+ $branch: String
518
+ ) {
519
+ setPreferredEditor(
520
+ documentIdentifier: $documentIdentifier
521
+ preferredEditor: $preferredEditor
522
+ branch: $branch
523
+ ) {
524
+ ...PHDocumentFields
525
+ }
526
+ }
527
+ ${PhDocumentFieldsFragmentDoc}
528
+ `;
529
+ gql`
530
+ mutation AddRelationship(
531
+ $sourceIdentifier: String!
532
+ $targetIdentifier: String!
533
+ $relationshipType: String!
534
+ $branch: String
535
+ ) {
536
+ addRelationship(
537
+ sourceIdentifier: $sourceIdentifier
538
+ targetIdentifier: $targetIdentifier
539
+ relationshipType: $relationshipType
540
+ branch: $branch
541
+ ) {
542
+ ...PHDocumentFields
543
+ }
544
+ }
545
+ ${PhDocumentFieldsFragmentDoc}
546
+ `;
547
+ gql`
548
+ mutation RemoveRelationship(
549
+ $sourceIdentifier: String!
550
+ $targetIdentifier: String!
551
+ $relationshipType: String!
552
+ $branch: String
553
+ ) {
554
+ removeRelationship(
555
+ sourceIdentifier: $sourceIdentifier
556
+ targetIdentifier: $targetIdentifier
557
+ relationshipType: $relationshipType
558
+ branch: $branch
559
+ ) {
560
+ ...PHDocumentFields
561
+ }
562
+ }
563
+ ${PhDocumentFieldsFragmentDoc}
564
+ `;
565
+ gql`
566
+ mutation MoveRelationship(
567
+ $sourceParentIdentifier: String!
568
+ $targetParentIdentifier: String!
569
+ $targetIdentifier: String!
570
+ $relationshipType: String!
571
+ $branch: String
572
+ ) {
573
+ moveRelationship(
574
+ sourceParentIdentifier: $sourceParentIdentifier
575
+ targetParentIdentifier: $targetParentIdentifier
576
+ targetIdentifier: $targetIdentifier
577
+ relationshipType: $relationshipType
578
+ branch: $branch
579
+ ) {
580
+ source {
581
+ ...PHDocumentFields
582
+ }
583
+ target {
584
+ ...PHDocumentFields
585
+ }
586
+ }
587
+ }
588
+ ${PhDocumentFieldsFragmentDoc}
589
+ `;
590
+ gql`
591
+ mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {
592
+ deleteDocument(identifier: $identifier, propagate: $propagate)
593
+ }
594
+ `;
595
+ gql`
596
+ mutation DeleteDocuments(
597
+ $identifiers: [String!]!
598
+ $propagate: PropagationMode
599
+ ) {
600
+ deleteDocuments(identifiers: $identifiers, propagate: $propagate)
601
+ }
602
+ `;
603
+ gql`
604
+ subscription DocumentChanges(
605
+ $search: SearchFilterInput
606
+ $view: ViewFilterInput
607
+ ) {
608
+ documentChanges(search: $search, view: $view) {
609
+ type
610
+ documents {
611
+ ...PHDocumentFields
612
+ }
613
+ context {
614
+ parentId
615
+ childId
616
+ }
617
+ }
618
+ }
619
+ ${PhDocumentFieldsFragmentDoc}
620
+ `;
621
+ gql`
622
+ subscription JobChanges($jobId: String!) {
623
+ jobChanges(jobId: $jobId) {
624
+ jobId
625
+ status
626
+ result
627
+ error
628
+ }
629
+ }
630
+ `;
631
+ gql`
632
+ query PollSyncEnvelopes(
633
+ $channelId: String!
634
+ $outboxAck: Int!
635
+ $outboxLatest: Int!
636
+ ) {
637
+ pollSyncEnvelopes(
638
+ channelId: $channelId
639
+ outboxAck: $outboxAck
640
+ outboxLatest: $outboxLatest
641
+ ) {
642
+ envelopes {
643
+ type
644
+ channelMeta {
645
+ id
646
+ }
647
+ operations {
648
+ operation {
649
+ index
650
+ timestampUtcMs
651
+ hash
652
+ skip
653
+ error
654
+ id
655
+ action {
656
+ id
657
+ type
658
+ timestampUtcMs
659
+ input
660
+ scope
661
+ attachments {
662
+ data
663
+ mimeType
664
+ hash
665
+ extension
666
+ fileName
667
+ }
668
+ context {
669
+ signer {
670
+ user {
671
+ address
672
+ networkId
673
+ chainId
674
+ }
675
+ app {
676
+ name
677
+ key
678
+ }
679
+ signatures
680
+ }
681
+ }
682
+ }
683
+ }
684
+ context {
685
+ documentId
686
+ documentType
687
+ scope
688
+ branch
689
+ }
690
+ }
691
+ cursor {
692
+ remoteName
693
+ cursorOrdinal
694
+ lastSyncedAtUtcMs
695
+ }
696
+ key
697
+ dependsOn
698
+ }
699
+ ackOrdinal
700
+ deadLetters {
701
+ documentId
702
+ error
703
+ }
704
+ hasMore
705
+ }
706
+ }
707
+ `;
708
+ gql`
709
+ mutation TouchChannel($input: TouchChannelInput!) {
710
+ touchChannel(input: $input) {
711
+ success
712
+ ackOrdinal
713
+ }
714
+ }
715
+ `;
716
+ gql`
717
+ mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
718
+ pushSyncEnvelopes(envelopes: $envelopes)
719
+ }
720
+ `;
721
+ /** Get the source string from a GraphQL document (string or DocumentNode). */
722
+ function getDocumentSource(doc) {
723
+ return typeof doc === "string" ? doc : doc.loc?.source.body ?? "";
724
+ }
725
+ /**
726
+ * Extract the inner selection set of a named field from a GraphQL document source.
727
+ * Returns the `{ ... }` block including braces.
728
+ */
729
+ function extractSelectionSet(doc, fieldName, fallback) {
730
+ const source = getDocumentSource(doc);
731
+ return new RegExp(`${fieldName}\\([^)]*\\)\\s*(\\{[\\s\\S]*\\})\\s*\\}`).exec(source)?.[1] ?? fallback;
732
+ }
733
+ /**
734
+ * Extract the query body and any fragment definitions from a GraphQL document.
735
+ * Returns { body, fragments } where body is the content inside the query `{ ... }`
736
+ * and fragments are any trailing fragment definitions.
737
+ */
738
+ function extractQueryParts(doc, fallbackBody) {
739
+ const source = getDocumentSource(doc);
740
+ const queryMatch = /^[^{]*\{([\s\S]*?)\}\s*(fragment[\s\S]*)?$/.exec(source);
741
+ return {
742
+ body: queryMatch?.[1]?.trim() ?? fallbackBody,
743
+ fragments: queryMatch?.[2]?.trim() ?? ""
744
+ };
745
+ }
746
+ extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
747
+ extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
748
+ //#endregion
749
+ //#region ../reactor-browser/dist/renown-Dzmo1gJD.js
750
+ const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
751
+ const renownEventFunctions = makePHEventFunctions("renown");
752
+ renownEventFunctions.addEventHandler;
753
+ /** Returns the renown instance */
754
+ const useRenown = renownEventFunctions.useValue;
755
+ renownEventFunctions.setValue;
756
+ /** Returns the current user from the renown instance, subscribing to user events */
757
+ function useUser() {
758
+ const renown = useRenown();
759
+ const [user, setUser] = useState(renown?.user);
760
+ useEffect(() => {
761
+ setUser(renown?.user);
762
+ if (!renown) return;
763
+ return renown.on("user", setUser);
764
+ }, [renown]);
765
+ return user;
766
+ }
767
+ function mergeProps(parentProps, childProps) {
768
+ const merged = { ...parentProps };
769
+ for (const key of Object.keys(childProps)) {
770
+ const parentValue = parentProps[key];
771
+ const childValue = childProps[key];
772
+ if (key === "style") merged[key] = {
773
+ ...parentValue,
774
+ ...childValue
775
+ };
776
+ else if (key === "className") merged[key] = [parentValue, childValue].filter(Boolean).join(" ");
777
+ else if (typeof parentValue === "function" && typeof childValue === "function") merged[key] = (...args) => {
778
+ childValue(...args);
779
+ parentValue(...args);
780
+ };
781
+ else if (childValue !== void 0) merged[key] = childValue;
782
+ }
783
+ return merged;
784
+ }
785
+ const Slot = forwardRef(({ children, ...props }, ref) => {
786
+ const child = Children.only(children);
787
+ if (!isValidElement(child)) return null;
788
+ const childElement = child;
789
+ const mergedProps = mergeProps(props, childElement.props);
790
+ if (ref) mergedProps.ref = ref;
791
+ return cloneElement(childElement, mergedProps);
792
+ });
793
+ Slot.displayName = "Slot";
794
+ //#endregion
795
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
796
+ function e$8(e, t, n) {
797
+ let r = (n) => e(n, ...t);
798
+ return n === void 0 ? r : Object.assign(r, {
799
+ lazy: n,
800
+ lazyArgs: t
801
+ });
802
+ }
803
+ //#endregion
804
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js
805
+ function t$5(t, n, r) {
806
+ let i = t.length - n.length;
807
+ if (i === 0) return t(...n);
808
+ if (i === 1) return e$8(t, n, r);
809
+ throw Error(`Wrong number of arguments`);
810
+ }
811
+ //#endregion
812
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/allPass.js
813
+ function t$4(...t) {
814
+ return t$5(n$4, t);
815
+ }
816
+ const n$4 = (e, t) => t.every((t) => t(e));
817
+ //#endregion
818
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/conditional-CTEJD5TX.js
819
+ function e$7(e, t, n) {
820
+ return e(n[0]) ? (e) => t(e, ...n) : t(...n);
821
+ }
822
+ function t$3(...t) {
823
+ return e$7(r, n$3, t);
824
+ }
825
+ function n$3(e, ...t) {
826
+ for (let n of t) {
827
+ if (typeof n == `function`) return n(e);
828
+ let [t, r] = n;
829
+ if (t(e)) return r(e);
830
+ }
831
+ throw Error(`conditional: data failed for all cases`);
832
+ }
833
+ function r(e) {
834
+ if (!Array.isArray(e)) return !1;
835
+ let [t, n, ...r] = e;
836
+ return typeof t == `function` && t.length <= 1 && typeof n == `function` && n.length <= 1 && r.length === 0;
837
+ }
838
+ //#endregion
839
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/constant.js
840
+ function e$6(e) {
841
+ return () => e;
842
+ }
843
+ //#endregion
844
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js
845
+ function t$2(...t) {
846
+ return t$5(n$2, t);
847
+ }
848
+ const n$2 = (e, t) => e.length >= t;
849
+ //#endregion
850
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js
851
+ const e$5 = Symbol(`funnel/voidReducer`), t$1 = () => e$5;
852
+ function n$1(n, { triggerAt: r = `end`, minQuietPeriodMs: i, maxBurstDurationMs: a, minGapMs: o, reducer: s = t$1 }) {
853
+ let c, l, u, d, f = () => {
854
+ let t = u;
855
+ t !== void 0 && (u = void 0, t === e$5 ? n() : n(t), o !== void 0 && (l = setTimeout(p, o)));
856
+ }, p = () => {
857
+ clearTimeout(l), l = void 0, c === void 0 && f();
858
+ }, m = () => {
859
+ clearTimeout(c), c = void 0, d = void 0, l === void 0 && f();
860
+ };
861
+ return {
862
+ call: (...e) => {
863
+ let t = c === void 0 && l === void 0;
864
+ if ((r !== `start` || t) && (u = s(u, ...e)), !(c === void 0 && !t)) {
865
+ if (i !== void 0 || a !== void 0 || o === void 0) {
866
+ clearTimeout(c);
867
+ let e = Date.now();
868
+ d ??= e;
869
+ let t = a === void 0 ? i ?? 0 : Math.min(i ?? a, Math.max(0, a - (e - d)));
870
+ c = setTimeout(m, t);
871
+ }
872
+ r !== `end` && t && f();
873
+ }
874
+ },
875
+ cancel: () => {
876
+ clearTimeout(c), c = void 0, d = void 0, clearTimeout(l), l = void 0, u = void 0;
877
+ },
878
+ flush: () => {
879
+ m(), p();
880
+ },
881
+ get isIdle() {
882
+ return c === void 0 && l === void 0;
883
+ }
884
+ };
885
+ }
886
+ //#endregion
887
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js
888
+ function e$4(e) {
889
+ return e !== void 0;
890
+ }
891
+ //#endregion
892
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isNot.js
893
+ function e$3(e) {
894
+ return (t) => !e(t);
895
+ }
896
+ //#endregion
897
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isStrictEqual.js
898
+ function t(...t) {
899
+ return t$5(n, t);
900
+ }
901
+ const n = (e, t) => e === t || Object.is(e, t);
902
+ //#endregion
903
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isString.js
904
+ function e$2(e) {
905
+ return typeof e == `string`;
906
+ }
907
+ //#endregion
908
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isTruthy.js
909
+ function e$1(e) {
910
+ return !!e;
911
+ }
912
+ //#endregion
913
+ //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/once.js
914
+ function e(e) {
915
+ let t = !1, n;
916
+ return () => (t ||= (n = e(), !0), n);
917
+ }
918
+ //#endregion
919
+ //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
920
+ let base64;
921
+ if (typeof window !== "undefined") if (window.btoa) base64 = function(input) {
922
+ return btoa(unescape(encodeURIComponent(input)));
923
+ };
924
+ else base64 = function(input) {
925
+ const str = unescape(encodeURIComponent(input + ""));
926
+ let output = "";
927
+ for (let block, charCode, idx = 0, map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; str.charAt(idx | 0) || (map = "=", idx % 1); output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {
928
+ charCode = str.charCodeAt(idx += 3 / 4);
929
+ /* c8 ignore next 3 */
930
+ if (charCode > 255) throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
931
+ block = block << 8 | charCode;
932
+ }
933
+ return output;
934
+ };
935
+ else base64 = function(input) {
936
+ return Buffer.from(input).toString("base64");
937
+ };
938
+ function slug(string, opts) {
939
+ let result = slugify(string, opts);
940
+ if ((opts && opts.fallback !== void 0 ? opts.fallback : slug.defaults.fallback) === true && result === "") result = slugify(base64(string), opts);
941
+ return result;
942
+ }
943
+ const locales = {
944
+ bg: {
945
+ Й: "Y",
946
+ й: "y",
947
+ X: "H",
948
+ x: "h",
949
+ Ц: "Ts",
950
+ ц: "ts",
951
+ Щ: "Sht",
952
+ щ: "sht",
953
+ Ъ: "A",
954
+ ъ: "a",
955
+ Ь: "Y",
956
+ ь: "y"
957
+ },
958
+ de: {
959
+ Ä: "AE",
960
+ ä: "ae",
961
+ Ö: "OE",
962
+ ö: "oe",
963
+ Ü: "UE",
964
+ ü: "ue"
965
+ },
966
+ sr: {
967
+ đ: "dj",
968
+ Đ: "DJ"
969
+ },
970
+ uk: {
971
+ И: "Y",
972
+ и: "y",
973
+ Й: "Y",
974
+ й: "y",
975
+ Ц: "Ts",
976
+ ц: "ts",
977
+ Х: "Kh",
978
+ х: "kh",
979
+ Щ: "Shch",
980
+ щ: "shch",
981
+ Г: "H",
982
+ г: "h"
983
+ }
984
+ };
985
+ let defaultLocale = {};
986
+ function slugify(string, opts) {
987
+ if (typeof string !== "string") throw new Error("slug() requires a string argument, received " + typeof string);
988
+ if (!string.isWellFormed()) throw new Error("slug() received a malformed string with lone surrogates");
989
+ if (typeof opts === "string") opts = { replacement: opts };
990
+ opts = opts ? Object.assign({}, opts) : {};
991
+ opts.mode = opts.mode || slug.defaults.mode;
992
+ const defaults = slug.defaults.modes[opts.mode];
993
+ const keys = [
994
+ "replacement",
995
+ "multicharmap",
996
+ "charmap",
997
+ "remove",
998
+ "lower",
999
+ "trim"
1000
+ ];
1001
+ for (let key, i = 0, l = keys.length; i < l; i++) {
1002
+ key = keys[i];
1003
+ opts[key] = key in opts ? opts[key] : defaults[key];
1004
+ }
1005
+ const localeMap = locales[opts.locale] || defaultLocale;
1006
+ let lengths = [];
1007
+ for (const key in opts.multicharmap) {
1008
+ if (!Object.prototype.hasOwnProperty.call(opts.multicharmap, key)) continue;
1009
+ const len = key.length;
1010
+ if (lengths.indexOf(len) === -1) lengths.push(len);
1011
+ }
1012
+ lengths = lengths.sort(function(a, b) {
1013
+ return b - a;
1014
+ });
1015
+ const disallowedChars = opts.mode === "rfc3986" ? /[^\w\s\-.~]/ : /[^A-Za-z0-9\s]/;
1016
+ let result = "";
1017
+ for (let char, i = 0, l = string.length; i < l; i++) {
1018
+ char = string[i];
1019
+ let matchedMultichar = false;
1020
+ for (let j = 0; j < lengths.length; j++) {
1021
+ const len = lengths[j];
1022
+ const str = string.substr(i, len);
1023
+ if (opts.multicharmap[str]) {
1024
+ i += len - 1;
1025
+ char = opts.multicharmap[str];
1026
+ matchedMultichar = true;
1027
+ break;
1028
+ }
1029
+ }
1030
+ if (!matchedMultichar) if (localeMap[char]) char = localeMap[char];
1031
+ else if (opts.charmap[char]) char = opts.charmap[char].replace(opts.replacement, " ");
1032
+ else if (char.includes(opts.replacement)) char = char.replace(opts.replacement, " ");
1033
+ else char = char.replace(disallowedChars, "");
1034
+ result += char;
1035
+ }
1036
+ if (opts.remove) result = result.replace(opts.remove, "");
1037
+ if (opts.trim) result = result.trim();
1038
+ result = result.replace(/\s+/g, opts.replacement);
1039
+ if (opts.lower) result = result.toLowerCase();
1040
+ return result;
1041
+ }
1042
+ const initialMulticharmap = {
1043
+ फ़: "Fi",
1044
+ ग़: "Ghi",
1045
+ ख़: "Khi",
1046
+ क़: "Qi",
1047
+ ड़: "ugDha",
1048
+ ढ़: "ugDhha",
1049
+ य़: "Yi",
1050
+ ज़: "Za",
1051
+ בִי: "i",
1052
+ בֵ: "e",
1053
+ בֵי: "e",
1054
+ בֶ: "e",
1055
+ בַ: "a",
1056
+ בָ: "a",
1057
+ בֹ: "o",
1058
+ וֹ: "o",
1059
+ בֻ: "u",
1060
+ וּ: "u",
1061
+ בּ: "b",
1062
+ כּ: "k",
1063
+ ךּ: "k",
1064
+ פּ: "p",
1065
+ שׁ: "sh",
1066
+ שׂ: "s",
1067
+ בְ: "e",
1068
+ חֱ: "e",
1069
+ חֲ: "a",
1070
+ חֳ: "o",
1071
+ בִ: "i"
1072
+ };
1073
+ const initialCharmap = {
1074
+ À: "A",
1075
+ Á: "A",
1076
+ Â: "A",
1077
+ Ã: "A",
1078
+ Ä: "A",
1079
+ Å: "A",
1080
+ Æ: "AE",
1081
+ Ç: "C",
1082
+ È: "E",
1083
+ É: "E",
1084
+ Ê: "E",
1085
+ Ë: "E",
1086
+ Ì: "I",
1087
+ Í: "I",
1088
+ Î: "I",
1089
+ Ï: "I",
1090
+ Ð: "D",
1091
+ Ñ: "N",
1092
+ Ò: "O",
1093
+ Ó: "O",
1094
+ Ô: "O",
1095
+ Õ: "O",
1096
+ Ö: "O",
1097
+ Ő: "O",
1098
+ Ø: "O",
1099
+ Ō: "O",
1100
+ Ù: "U",
1101
+ Ú: "U",
1102
+ Û: "U",
1103
+ Ü: "U",
1104
+ Ű: "U",
1105
+ Ý: "Y",
1106
+ Þ: "TH",
1107
+ ß: "ss",
1108
+ à: "a",
1109
+ á: "a",
1110
+ â: "a",
1111
+ ã: "a",
1112
+ ä: "a",
1113
+ å: "a",
1114
+ æ: "ae",
1115
+ ç: "c",
1116
+ è: "e",
1117
+ é: "e",
1118
+ ê: "e",
1119
+ ë: "e",
1120
+ ì: "i",
1121
+ í: "i",
1122
+ î: "i",
1123
+ ï: "i",
1124
+ ð: "d",
1125
+ ñ: "n",
1126
+ ò: "o",
1127
+ ó: "o",
1128
+ ô: "o",
1129
+ õ: "o",
1130
+ ö: "o",
1131
+ ő: "o",
1132
+ ø: "o",
1133
+ ō: "o",
1134
+ Œ: "OE",
1135
+ œ: "oe",
1136
+ ù: "u",
1137
+ ú: "u",
1138
+ û: "u",
1139
+ ü: "u",
1140
+ ű: "u",
1141
+ ý: "y",
1142
+ þ: "th",
1143
+ ÿ: "y",
1144
+ ẞ: "SS",
1145
+ α: "a",
1146
+ β: "b",
1147
+ γ: "g",
1148
+ δ: "d",
1149
+ ε: "e",
1150
+ ζ: "z",
1151
+ η: "h",
1152
+ θ: "th",
1153
+ ι: "i",
1154
+ κ: "k",
1155
+ λ: "l",
1156
+ μ: "m",
1157
+ ν: "n",
1158
+ ξ: "3",
1159
+ ο: "o",
1160
+ π: "p",
1161
+ ρ: "r",
1162
+ σ: "s",
1163
+ τ: "t",
1164
+ υ: "y",
1165
+ φ: "f",
1166
+ χ: "x",
1167
+ ψ: "ps",
1168
+ ω: "w",
1169
+ ά: "a",
1170
+ έ: "e",
1171
+ ί: "i",
1172
+ ό: "o",
1173
+ ύ: "y",
1174
+ ή: "h",
1175
+ ώ: "w",
1176
+ ς: "s",
1177
+ ϊ: "i",
1178
+ ΰ: "y",
1179
+ ϋ: "y",
1180
+ ΐ: "i",
1181
+ Α: "A",
1182
+ Β: "B",
1183
+ Γ: "G",
1184
+ Δ: "D",
1185
+ Ε: "E",
1186
+ Ζ: "Z",
1187
+ Η: "H",
1188
+ Θ: "Th",
1189
+ Ι: "I",
1190
+ Κ: "K",
1191
+ Λ: "L",
1192
+ Μ: "M",
1193
+ Ν: "N",
1194
+ Ξ: "3",
1195
+ Ο: "O",
1196
+ Π: "P",
1197
+ Ρ: "R",
1198
+ Σ: "S",
1199
+ Τ: "T",
1200
+ Υ: "Y",
1201
+ Φ: "F",
1202
+ Χ: "X",
1203
+ Ψ: "PS",
1204
+ Ω: "W",
1205
+ Ά: "A",
1206
+ Έ: "E",
1207
+ Ί: "I",
1208
+ Ό: "O",
1209
+ Ύ: "Y",
1210
+ Ή: "H",
1211
+ Ώ: "W",
1212
+ Ϊ: "I",
1213
+ Ϋ: "Y",
1214
+ ş: "s",
1215
+ Ş: "S",
1216
+ ı: "i",
1217
+ İ: "I",
1218
+ ğ: "g",
1219
+ Ğ: "G",
1220
+ а: "a",
1221
+ б: "b",
1222
+ в: "v",
1223
+ г: "g",
1224
+ д: "d",
1225
+ е: "e",
1226
+ ё: "yo",
1227
+ ж: "zh",
1228
+ з: "z",
1229
+ и: "i",
1230
+ й: "j",
1231
+ к: "k",
1232
+ л: "l",
1233
+ м: "m",
1234
+ н: "n",
1235
+ о: "o",
1236
+ п: "p",
1237
+ р: "r",
1238
+ с: "s",
1239
+ т: "t",
1240
+ у: "u",
1241
+ ф: "f",
1242
+ х: "h",
1243
+ ц: "c",
1244
+ ч: "ch",
1245
+ ш: "sh",
1246
+ щ: "sh",
1247
+ ъ: "u",
1248
+ ы: "y",
1249
+ ь: "",
1250
+ э: "e",
1251
+ ю: "yu",
1252
+ я: "ya",
1253
+ А: "A",
1254
+ Б: "B",
1255
+ В: "V",
1256
+ Г: "G",
1257
+ Д: "D",
1258
+ Е: "E",
1259
+ Ё: "Yo",
1260
+ Ж: "Zh",
1261
+ З: "Z",
1262
+ И: "I",
1263
+ Й: "J",
1264
+ К: "K",
1265
+ Л: "L",
1266
+ М: "M",
1267
+ Н: "N",
1268
+ О: "O",
1269
+ П: "P",
1270
+ Р: "R",
1271
+ С: "S",
1272
+ Т: "T",
1273
+ У: "U",
1274
+ Ф: "F",
1275
+ Х: "H",
1276
+ Ц: "C",
1277
+ Ч: "Ch",
1278
+ Ш: "Sh",
1279
+ Щ: "Sh",
1280
+ Ъ: "U",
1281
+ Ы: "Y",
1282
+ Ь: "",
1283
+ Э: "E",
1284
+ Ю: "Yu",
1285
+ Я: "Ya",
1286
+ Є: "Ye",
1287
+ І: "I",
1288
+ Ї: "Yi",
1289
+ Ґ: "G",
1290
+ є: "ye",
1291
+ і: "i",
1292
+ ї: "yi",
1293
+ ґ: "g",
1294
+ č: "c",
1295
+ ď: "d",
1296
+ ě: "e",
1297
+ ň: "n",
1298
+ ř: "r",
1299
+ š: "s",
1300
+ ť: "t",
1301
+ ů: "u",
1302
+ ž: "z",
1303
+ Č: "C",
1304
+ Ď: "D",
1305
+ Ě: "E",
1306
+ Ň: "N",
1307
+ Ř: "R",
1308
+ Š: "S",
1309
+ Ť: "T",
1310
+ Ů: "U",
1311
+ Ž: "Z",
1312
+ ľ: "l",
1313
+ ĺ: "l",
1314
+ ŕ: "r",
1315
+ Ľ: "L",
1316
+ Ĺ: "L",
1317
+ Ŕ: "R",
1318
+ ą: "a",
1319
+ ć: "c",
1320
+ ę: "e",
1321
+ ł: "l",
1322
+ ń: "n",
1323
+ ś: "s",
1324
+ ź: "z",
1325
+ ż: "z",
1326
+ Ą: "A",
1327
+ Ć: "C",
1328
+ Ę: "E",
1329
+ Ł: "L",
1330
+ Ń: "N",
1331
+ Ś: "S",
1332
+ Ź: "Z",
1333
+ Ż: "Z",
1334
+ ā: "a",
1335
+ ē: "e",
1336
+ ģ: "g",
1337
+ ī: "i",
1338
+ ķ: "k",
1339
+ ļ: "l",
1340
+ ņ: "n",
1341
+ ū: "u",
1342
+ Ā: "A",
1343
+ Ē: "E",
1344
+ Ģ: "G",
1345
+ Ī: "I",
1346
+ Ķ: "K",
1347
+ Ļ: "L",
1348
+ Ņ: "N",
1349
+ Ū: "U",
1350
+ أ: "a",
1351
+ إ: "i",
1352
+ ب: "b",
1353
+ ت: "t",
1354
+ ث: "th",
1355
+ ج: "g",
1356
+ ح: "h",
1357
+ خ: "kh",
1358
+ د: "d",
1359
+ ذ: "th",
1360
+ ر: "r",
1361
+ ز: "z",
1362
+ س: "s",
1363
+ ش: "sh",
1364
+ ص: "s",
1365
+ ض: "d",
1366
+ ط: "t",
1367
+ ظ: "th",
1368
+ ع: "aa",
1369
+ غ: "gh",
1370
+ ف: "f",
1371
+ ق: "k",
1372
+ ك: "k",
1373
+ ل: "l",
1374
+ م: "m",
1375
+ ن: "n",
1376
+ ه: "h",
1377
+ و: "o",
1378
+ ي: "y",
1379
+ ء: "aa",
1380
+ ة: "a",
1381
+ آ: "a",
1382
+ ا: "a",
1383
+ پ: "p",
1384
+ ژ: "zh",
1385
+ گ: "g",
1386
+ چ: "ch",
1387
+ ک: "k",
1388
+ ی: "i",
1389
+ ė: "e",
1390
+ į: "i",
1391
+ ų: "u",
1392
+ Ė: "E",
1393
+ Į: "I",
1394
+ Ų: "U",
1395
+ ț: "t",
1396
+ Ț: "T",
1397
+ ţ: "t",
1398
+ Ţ: "T",
1399
+ ș: "s",
1400
+ Ș: "S",
1401
+ ă: "a",
1402
+ Ă: "A",
1403
+ Ạ: "A",
1404
+ Ả: "A",
1405
+ Ầ: "A",
1406
+ Ấ: "A",
1407
+ Ậ: "A",
1408
+ Ẩ: "A",
1409
+ Ẫ: "A",
1410
+ Ằ: "A",
1411
+ Ắ: "A",
1412
+ Ặ: "A",
1413
+ Ẳ: "A",
1414
+ Ẵ: "A",
1415
+ Ẹ: "E",
1416
+ Ẻ: "E",
1417
+ Ẽ: "E",
1418
+ Ề: "E",
1419
+ Ế: "E",
1420
+ Ệ: "E",
1421
+ Ể: "E",
1422
+ Ễ: "E",
1423
+ Ị: "I",
1424
+ Ỉ: "I",
1425
+ Ĩ: "I",
1426
+ Ọ: "O",
1427
+ Ỏ: "O",
1428
+ Ồ: "O",
1429
+ Ố: "O",
1430
+ Ộ: "O",
1431
+ Ổ: "O",
1432
+ Ỗ: "O",
1433
+ Ơ: "O",
1434
+ Ờ: "O",
1435
+ Ớ: "O",
1436
+ Ợ: "O",
1437
+ Ở: "O",
1438
+ Ỡ: "O",
1439
+ Ụ: "U",
1440
+ Ủ: "U",
1441
+ Ũ: "U",
1442
+ Ư: "U",
1443
+ Ừ: "U",
1444
+ Ứ: "U",
1445
+ Ự: "U",
1446
+ Ử: "U",
1447
+ Ữ: "U",
1448
+ Ỳ: "Y",
1449
+ Ỵ: "Y",
1450
+ Ỷ: "Y",
1451
+ Ỹ: "Y",
1452
+ Đ: "D",
1453
+ ạ: "a",
1454
+ ả: "a",
1455
+ ầ: "a",
1456
+ ấ: "a",
1457
+ ậ: "a",
1458
+ ẩ: "a",
1459
+ ẫ: "a",
1460
+ ằ: "a",
1461
+ ắ: "a",
1462
+ ặ: "a",
1463
+ ẳ: "a",
1464
+ ẵ: "a",
1465
+ ẹ: "e",
1466
+ ẻ: "e",
1467
+ ẽ: "e",
1468
+ ề: "e",
1469
+ ế: "e",
1470
+ ệ: "e",
1471
+ ể: "e",
1472
+ ễ: "e",
1473
+ ị: "i",
1474
+ ỉ: "i",
1475
+ ĩ: "i",
1476
+ ọ: "o",
1477
+ ỏ: "o",
1478
+ ồ: "o",
1479
+ ố: "o",
1480
+ ộ: "o",
1481
+ ổ: "o",
1482
+ ỗ: "o",
1483
+ ơ: "o",
1484
+ ờ: "o",
1485
+ ớ: "o",
1486
+ ợ: "o",
1487
+ ở: "o",
1488
+ ỡ: "o",
1489
+ ụ: "u",
1490
+ ủ: "u",
1491
+ ũ: "u",
1492
+ ư: "u",
1493
+ ừ: "u",
1494
+ ứ: "u",
1495
+ ự: "u",
1496
+ ử: "u",
1497
+ ữ: "u",
1498
+ ỳ: "y",
1499
+ ỵ: "y",
1500
+ ỷ: "y",
1501
+ ỹ: "y",
1502
+ đ: "d",
1503
+ Ә: "AE",
1504
+ ә: "ae",
1505
+ Ғ: "GH",
1506
+ ғ: "gh",
1507
+ Қ: "KH",
1508
+ қ: "kh",
1509
+ Ң: "NG",
1510
+ ң: "ng",
1511
+ Ү: "UE",
1512
+ ү: "ue",
1513
+ Ұ: "U",
1514
+ ұ: "u",
1515
+ Һ: "H",
1516
+ һ: "h",
1517
+ Ө: "OE",
1518
+ ө: "oe",
1519
+ ђ: "dj",
1520
+ ј: "j",
1521
+ љ: "lj",
1522
+ њ: "nj",
1523
+ ћ: "c",
1524
+ џ: "dz",
1525
+ Ђ: "Dj",
1526
+ Ј: "j",
1527
+ Љ: "Lj",
1528
+ Њ: "Nj",
1529
+ Ћ: "C",
1530
+ Џ: "Dz",
1531
+ nj: "nj",
1532
+ lj: "lj",
1533
+ Nj: "NJ",
1534
+ Lj: "LJ",
1535
+ अ: "a",
1536
+ आ: "aa",
1537
+ ए: "e",
1538
+ ई: "ii",
1539
+ ऍ: "ei",
1540
+ ऎ: "ae",
1541
+ ऐ: "ai",
1542
+ इ: "i",
1543
+ ओ: "o",
1544
+ ऑ: "oi",
1545
+ ऒ: "oii",
1546
+ ऊ: "uu",
1547
+ औ: "ou",
1548
+ उ: "u",
1549
+ ब: "B",
1550
+ भ: "Bha",
1551
+ च: "Ca",
1552
+ छ: "Chha",
1553
+ ड: "Da",
1554
+ ढ: "Dha",
1555
+ फ: "Fa",
1556
+ ग: "Ga",
1557
+ घ: "Gha",
1558
+ ग़: "Ghi",
1559
+ ह: "Ha",
1560
+ ज: "Ja",
1561
+ झ: "Jha",
1562
+ क: "Ka",
1563
+ ख: "Kha",
1564
+ ख़: "Khi",
1565
+ ल: "L",
1566
+ ळ: "Li",
1567
+ ऌ: "Li",
1568
+ ऴ: "Lii",
1569
+ ॡ: "Lii",
1570
+ म: "Ma",
1571
+ न: "Na",
1572
+ ङ: "Na",
1573
+ ञ: "Nia",
1574
+ ण: "Nae",
1575
+ ऩ: "Ni",
1576
+ ॐ: "oms",
1577
+ प: "Pa",
1578
+ क़: "Qi",
1579
+ र: "Ra",
1580
+ ऋ: "Ri",
1581
+ ॠ: "Ri",
1582
+ ऱ: "Ri",
1583
+ स: "Sa",
1584
+ श: "Sha",
1585
+ ष: "Shha",
1586
+ ट: "Ta",
1587
+ त: "Ta",
1588
+ ठ: "Tha",
1589
+ द: "Tha",
1590
+ थ: "Tha",
1591
+ ध: "Thha",
1592
+ ड़: "ugDha",
1593
+ ढ़: "ugDhha",
1594
+ व: "Va",
1595
+ य: "Ya",
1596
+ य़: "Yi",
1597
+ ज़: "Za",
1598
+ ə: "e",
1599
+ Ə: "E",
1600
+ ა: "a",
1601
+ ბ: "b",
1602
+ გ: "g",
1603
+ დ: "d",
1604
+ ე: "e",
1605
+ ვ: "v",
1606
+ ზ: "z",
1607
+ თ: "t",
1608
+ ი: "i",
1609
+ კ: "k",
1610
+ ლ: "l",
1611
+ მ: "m",
1612
+ ნ: "n",
1613
+ ო: "o",
1614
+ პ: "p",
1615
+ ჟ: "zh",
1616
+ რ: "r",
1617
+ ს: "s",
1618
+ ტ: "t",
1619
+ უ: "u",
1620
+ ფ: "p",
1621
+ ქ: "k",
1622
+ ღ: "gh",
1623
+ ყ: "q",
1624
+ შ: "sh",
1625
+ ჩ: "ch",
1626
+ ც: "ts",
1627
+ ძ: "dz",
1628
+ წ: "ts",
1629
+ ჭ: "ch",
1630
+ ხ: "kh",
1631
+ ჯ: "j",
1632
+ ჰ: "h",
1633
+ ב: "v",
1634
+ גּ: "g",
1635
+ ג: "g",
1636
+ ד: "d",
1637
+ דּ: "d",
1638
+ ה: "h",
1639
+ ו: "v",
1640
+ ז: "z",
1641
+ ח: "h",
1642
+ ט: "t",
1643
+ י: "y",
1644
+ כ: "kh",
1645
+ ך: "kh",
1646
+ ל: "l",
1647
+ מ: "m",
1648
+ ם: "m",
1649
+ נ: "n",
1650
+ ן: "n",
1651
+ ס: "s",
1652
+ פ: "f",
1653
+ ף: "f",
1654
+ ץ: "ts",
1655
+ צ: "ts",
1656
+ ק: "k",
1657
+ ר: "r",
1658
+ תּ: "t",
1659
+ ת: "t"
1660
+ };
1661
+ slug.charmap = Object.assign({}, initialCharmap);
1662
+ slug.multicharmap = Object.assign({}, initialMulticharmap);
1663
+ slug.defaults = {
1664
+ charmap: slug.charmap,
1665
+ mode: "pretty",
1666
+ modes: {
1667
+ rfc3986: {
1668
+ replacement: "-",
1669
+ remove: null,
1670
+ lower: true,
1671
+ charmap: slug.charmap,
1672
+ multicharmap: slug.multicharmap,
1673
+ trim: true
1674
+ },
1675
+ pretty: {
1676
+ replacement: "-",
1677
+ remove: null,
1678
+ lower: true,
1679
+ charmap: slug.charmap,
1680
+ multicharmap: slug.multicharmap,
1681
+ trim: true
1682
+ }
1683
+ },
1684
+ multicharmap: slug.multicharmap,
1685
+ fallback: true
1686
+ };
1687
+ slug.reset = function() {
1688
+ slug.defaults.modes.rfc3986.charmap = slug.defaults.modes.pretty.charmap = slug.charmap = slug.defaults.charmap = Object.assign({}, initialCharmap);
1689
+ slug.defaults.modes.rfc3986.multicharmap = slug.defaults.modes.pretty.multicharmap = slug.multicharmap = slug.defaults.multicharmap = Object.assign({}, initialMulticharmap);
1690
+ defaultLocale = "";
1691
+ };
1692
+ slug.extend = function(customMap) {
1693
+ const keys = Object.keys(customMap);
1694
+ const multi = {};
1695
+ const single = {};
1696
+ for (let i = 0; i < keys.length; i++) if (keys[i].length > 1) multi[keys[i]] = customMap[keys[i]];
1697
+ else single[keys[i]] = customMap[keys[i]];
1698
+ Object.assign(slug.charmap, single);
1699
+ Object.assign(slug.multicharmap, multi);
1700
+ };
1701
+ slug.setLocale = function(locale) {
1702
+ defaultLocale = locales[locale] || {};
1703
+ };
1704
+ //#endregion
1705
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
1706
+ const normalizeDescriptors = (error) => {
1707
+ CORE_ERROR_PROPS.forEach((propName) => {
1708
+ normalizeDescriptor(error, propName);
1709
+ });
1710
+ };
1711
+ const CORE_ERROR_PROPS = [
1712
+ "name",
1713
+ "message",
1714
+ "stack",
1715
+ "cause",
1716
+ "errors"
1717
+ ];
1718
+ const normalizeDescriptor = (error, propName) => {
1719
+ const descriptor = getDescriptor(error, propName);
1720
+ if (descriptor === void 0) return;
1721
+ if (isReadonlyGetter(descriptor)) {
1722
+ setErrorProperty(error, propName, error[propName]);
1723
+ return;
1724
+ }
1725
+ if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
1726
+ };
1727
+ const getDescriptor = (value, propName) => {
1728
+ const descriptor = Object.getOwnPropertyDescriptor(value, propName);
1729
+ if (descriptor !== void 0) return descriptor;
1730
+ const prototype = Object.getPrototypeOf(value);
1731
+ return prototype === null ? void 0 : getDescriptor(prototype, propName);
1732
+ };
1733
+ const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
1734
+ const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
1735
+ const setErrorProperty = (error, propName, value) => {
1736
+ setErrorDescriptor(error, propName, { value });
1737
+ };
1738
+ const setErrorDescriptor = (error, propName, descriptor) => {
1739
+ Object.defineProperty(error, propName, {
1740
+ ...descriptor,
1741
+ ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
1742
+ enumerable: false,
1743
+ configurable: true
1744
+ });
1745
+ };
1746
+ //#endregion
1747
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
1748
+ const normalizeAggregate = (error, recurse) => {
1749
+ if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
1750
+ else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
1751
+ else if (error.errors !== void 0) deleteAggregateErrors(error);
1752
+ };
1753
+ const isDefined = (error) => error !== void 0;
1754
+ const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
1755
+ const deleteAggregateErrors = (error) => {
1756
+ delete error.errors;
1757
+ if (error.errors !== void 0) setErrorProperty(error, "errors", []);
1758
+ };
1759
+ //#endregion
1760
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
1761
+ const normalizeCause = (error, recurse) => {
1762
+ if (!("cause" in error)) return;
1763
+ const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
1764
+ if (cause === void 0) delete error.cause;
1765
+ else setErrorProperty(error, "cause", cause);
1766
+ };
1767
+ //#endregion
1768
+ //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
1769
+ const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
1770
+ const isInstanceOfError = (value) => {
1771
+ try {
1772
+ return value instanceof Error;
1773
+ } catch {
1774
+ return false;
1775
+ }
1776
+ };
1777
+ const hasErrorTag = (value) => {
1778
+ try {
1779
+ return ERROR_TAGS.has(Object.prototype.toString.call(value));
1780
+ } catch {
1781
+ return false;
1782
+ }
1783
+ };
1784
+ const ERROR_TAGS = new Set([
1785
+ "[object Error]",
1786
+ "[object DOMException]",
1787
+ "[object DOMError]",
1788
+ "[object Exception]"
1789
+ ]);
1790
+ //#endregion
1791
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
1792
+ function isPlainObject(value) {
1793
+ if (typeof value !== "object" || value === null) return false;
1794
+ const prototype = Object.getPrototypeOf(value);
1795
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
1796
+ }
1797
+ //#endregion
1798
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
1799
+ const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
1800
+ const isNonConfigurableProp = (error, propName) => {
1801
+ const descriptor = Object.getOwnPropertyDescriptor(error, propName);
1802
+ return descriptor !== void 0 && !descriptor.configurable;
1803
+ };
1804
+ const isThrowingProp = (error, propName) => {
1805
+ try {
1806
+ error[propName];
1807
+ return false;
1808
+ } catch {
1809
+ return true;
1810
+ }
1811
+ };
1812
+ //#endregion
1813
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
1814
+ const setStack = (error) => {
1815
+ setErrorProperty(error, "stack", getStack(error.message, error.name));
1816
+ };
1817
+ const getStack = (message = "", name = "Error") => {
1818
+ const { stack } = new (getErrorClass(name))(message);
1819
+ return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
1820
+ };
1821
+ const getErrorClass = (name) => {
1822
+ const descriptor = {
1823
+ value: name,
1824
+ enumerable: false,
1825
+ writable: true,
1826
+ configurable: true
1827
+ };
1828
+ const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
1829
+ Object.defineProperty(StackError.prototype, "name", descriptor);
1830
+ return StackError;
1831
+ };
1832
+ //#endregion
1833
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
1834
+ const copyObject = (object) => {
1835
+ const objectCopy = {};
1836
+ for (const propName of getPropsToCopy(object)) try {
1837
+ const value = object[propName];
1838
+ const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
1839
+ Object.defineProperty(objectCopy, propName, {
1840
+ value,
1841
+ enumerable,
1842
+ configurable,
1843
+ writable
1844
+ });
1845
+ } catch {}
1846
+ return objectCopy;
1847
+ };
1848
+ const getPropsToCopy = (object) => {
1849
+ const propNames = getOwnKeys(object);
1850
+ for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
1851
+ return propNames;
1852
+ };
1853
+ const getOwnKeys = (object) => {
1854
+ try {
1855
+ return Reflect.ownKeys(object);
1856
+ } catch {
1857
+ return [];
1858
+ }
1859
+ };
1860
+ const isInheritedProp = (object, propName) => {
1861
+ try {
1862
+ return propName in object && !Object.hasOwn(object, propName);
1863
+ } catch {
1864
+ return false;
1865
+ }
1866
+ };
1867
+ //#endregion
1868
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
1869
+ const objectifyError = (object) => {
1870
+ const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
1871
+ const messageA = getMessage(message, objectA);
1872
+ const error = newError(name, messageA);
1873
+ if (message === messageA) assignObjectProps(error, objectA);
1874
+ Object.entries({
1875
+ name,
1876
+ stack,
1877
+ cause,
1878
+ errors
1879
+ }).forEach(([propName, propValue]) => {
1880
+ setNewErrorProperty(error, propName, propValue);
1881
+ });
1882
+ if (stack === void 0) setStack(error);
1883
+ return error;
1884
+ };
1885
+ const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
1886
+ const safeJsonStringify = (object) => {
1887
+ try {
1888
+ return JSON.stringify(object);
1889
+ } catch {
1890
+ return safeStringify(object);
1891
+ }
1892
+ };
1893
+ const safeStringify = (object) => {
1894
+ try {
1895
+ return String(object);
1896
+ } catch {
1897
+ return "Invalid error";
1898
+ }
1899
+ };
1900
+ const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
1901
+ const MESSAGE_MAX_SIZE = 1e3;
1902
+ const newError = (name, message) => {
1903
+ if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
1904
+ if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
1905
+ return new Error(message);
1906
+ };
1907
+ const NATIVE_ERRORS = {
1908
+ Error,
1909
+ ReferenceError,
1910
+ TypeError,
1911
+ SyntaxError,
1912
+ RangeError,
1913
+ URIError,
1914
+ EvalError
1915
+ };
1916
+ const assignObjectProps = (error, object) => {
1917
+ for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
1918
+ };
1919
+ const setNewErrorProperty = (error, propName, propValue) => {
1920
+ if (propValue !== void 0) setErrorProperty(error, propName, propValue);
1921
+ };
1922
+ //#endregion
1923
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
1924
+ const stringifyError = (value) => {
1925
+ try {
1926
+ const error = new Error(String(value));
1927
+ setStack(error);
1928
+ return error;
1929
+ } catch (error_) {
1930
+ return error_;
1931
+ }
1932
+ };
1933
+ //#endregion
1934
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
1935
+ const { toString: objectToString } = Object.prototype;
1936
+ const createError = (value) => {
1937
+ if (isErrorPlainObj(value)) return objectifyError(value);
1938
+ if (!isErrorInstance(value)) return stringifyError(value);
1939
+ if (isInvalidError(value)) return objectifyError(value);
1940
+ return value;
1941
+ };
1942
+ const isErrorPlainObj = (value) => {
1943
+ try {
1944
+ return isPlainObject(value);
1945
+ } catch {
1946
+ return false;
1947
+ }
1948
+ };
1949
+ const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
1950
+ const isProxy = (value) => {
1951
+ try {
1952
+ return objectToString.call(value) === "[object Object]";
1953
+ } catch {
1954
+ return true;
1955
+ }
1956
+ };
1957
+ const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
1958
+ //#endregion
1959
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
1960
+ const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
1961
+ const recurseException = (error, parents, shallow) => {
1962
+ if (parents.includes(error)) return;
1963
+ const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
1964
+ const errorA = createError(error);
1965
+ normalizeProps(errorA, recurse);
1966
+ return errorA;
1967
+ };
1968
+ const identity = (error) => error;
1969
+ const normalizeProps = (error, recurse) => {
1970
+ normalizeName(error);
1971
+ normalizeMessage(error);
1972
+ normalizeStack(error);
1973
+ normalizeCause(error, recurse);
1974
+ normalizeAggregate(error, recurse);
1975
+ normalizeDescriptors(error);
1976
+ };
1977
+ const normalizeName = (error) => {
1978
+ if (isDefinedString(error.name)) return;
1979
+ const prototypeName = Object.getPrototypeOf(error).name;
1980
+ setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
1981
+ };
1982
+ const normalizeMessage = (error) => {
1983
+ if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
1984
+ };
1985
+ const normalizeStack = (error) => {
1986
+ if (!isDefinedString(error.stack)) setStack(error);
1987
+ };
1988
+ const isDefinedString = (value) => typeof value === "string" && value !== "";
1989
+ //#endregion
1990
+ //#region ../reactor-browser/dist/index.js
1991
+ var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1992
+ var LZString = (function() {
1993
+ var f = String.fromCharCode;
1994
+ var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
1995
+ var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
1996
+ var baseReverseDic = {};
1997
+ function getBaseValue(alphabet, character) {
1998
+ if (!baseReverseDic[alphabet]) {
1999
+ baseReverseDic[alphabet] = {};
2000
+ for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
2001
+ }
2002
+ return baseReverseDic[alphabet][character];
2003
+ }
2004
+ var LZString = {
2005
+ compressToBase64: function(input) {
2006
+ if (input == null) return "";
2007
+ var res = LZString._compress(input, 6, function(a) {
2008
+ return keyStrBase64.charAt(a);
2009
+ });
2010
+ switch (res.length % 4) {
2011
+ default:
2012
+ case 0: return res;
2013
+ case 1: return res + "===";
2014
+ case 2: return res + "==";
2015
+ case 3: return res + "=";
2016
+ }
2017
+ },
2018
+ decompressFromBase64: function(input) {
2019
+ if (input == null) return "";
2020
+ if (input == "") return null;
2021
+ return LZString._decompress(input.length, 32, function(index) {
2022
+ return getBaseValue(keyStrBase64, input.charAt(index));
2023
+ });
2024
+ },
2025
+ compressToUTF16: function(input) {
2026
+ if (input == null) return "";
2027
+ return LZString._compress(input, 15, function(a) {
2028
+ return f(a + 32);
2029
+ }) + " ";
2030
+ },
2031
+ decompressFromUTF16: function(compressed) {
2032
+ if (compressed == null) return "";
2033
+ if (compressed == "") return null;
2034
+ return LZString._decompress(compressed.length, 16384, function(index) {
2035
+ return compressed.charCodeAt(index) - 32;
2036
+ });
2037
+ },
2038
+ compressToUint8Array: function(uncompressed) {
2039
+ var compressed = LZString.compress(uncompressed);
2040
+ var buf = new Uint8Array(compressed.length * 2);
2041
+ for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
2042
+ var current_value = compressed.charCodeAt(i);
2043
+ buf[i * 2] = current_value >>> 8;
2044
+ buf[i * 2 + 1] = current_value % 256;
2045
+ }
2046
+ return buf;
2047
+ },
2048
+ decompressFromUint8Array: function(compressed) {
2049
+ if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
2050
+ else {
2051
+ var buf = new Array(compressed.length / 2);
2052
+ for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
2053
+ var result = [];
2054
+ buf.forEach(function(c) {
2055
+ result.push(f(c));
2056
+ });
2057
+ return LZString.decompress(result.join(""));
2058
+ }
2059
+ },
2060
+ compressToEncodedURIComponent: function(input) {
2061
+ if (input == null) return "";
2062
+ return LZString._compress(input, 6, function(a) {
2063
+ return keyStrUriSafe.charAt(a);
2064
+ });
2065
+ },
2066
+ decompressFromEncodedURIComponent: function(input) {
2067
+ if (input == null) return "";
2068
+ if (input == "") return null;
2069
+ input = input.replace(/ /g, "+");
2070
+ return LZString._decompress(input.length, 32, function(index) {
2071
+ return getBaseValue(keyStrUriSafe, input.charAt(index));
2072
+ });
2073
+ },
2074
+ compress: function(uncompressed) {
2075
+ return LZString._compress(uncompressed, 16, function(a) {
2076
+ return f(a);
2077
+ });
2078
+ },
2079
+ _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
2080
+ if (uncompressed == null) return "";
2081
+ 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;
2082
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
2083
+ context_c = uncompressed.charAt(ii);
2084
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
2085
+ context_dictionary[context_c] = context_dictSize++;
2086
+ context_dictionaryToCreate[context_c] = true;
2087
+ }
2088
+ context_wc = context_w + context_c;
2089
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
2090
+ else {
2091
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2092
+ if (context_w.charCodeAt(0) < 256) {
2093
+ for (i = 0; i < context_numBits; i++) {
2094
+ context_data_val = context_data_val << 1;
2095
+ if (context_data_position == bitsPerChar - 1) {
2096
+ context_data_position = 0;
2097
+ context_data.push(getCharFromInt(context_data_val));
2098
+ context_data_val = 0;
2099
+ } else context_data_position++;
2100
+ }
2101
+ value = context_w.charCodeAt(0);
2102
+ for (i = 0; i < 8; i++) {
2103
+ context_data_val = context_data_val << 1 | value & 1;
2104
+ if (context_data_position == bitsPerChar - 1) {
2105
+ context_data_position = 0;
2106
+ context_data.push(getCharFromInt(context_data_val));
2107
+ context_data_val = 0;
2108
+ } else context_data_position++;
2109
+ value = value >> 1;
2110
+ }
2111
+ } else {
2112
+ value = 1;
2113
+ for (i = 0; i < context_numBits; i++) {
2114
+ context_data_val = context_data_val << 1 | value;
2115
+ if (context_data_position == bitsPerChar - 1) {
2116
+ context_data_position = 0;
2117
+ context_data.push(getCharFromInt(context_data_val));
2118
+ context_data_val = 0;
2119
+ } else context_data_position++;
2120
+ value = 0;
2121
+ }
2122
+ value = context_w.charCodeAt(0);
2123
+ for (i = 0; i < 16; i++) {
2124
+ context_data_val = context_data_val << 1 | value & 1;
2125
+ if (context_data_position == bitsPerChar - 1) {
2126
+ context_data_position = 0;
2127
+ context_data.push(getCharFromInt(context_data_val));
2128
+ context_data_val = 0;
2129
+ } else context_data_position++;
2130
+ value = value >> 1;
2131
+ }
2132
+ }
2133
+ context_enlargeIn--;
2134
+ if (context_enlargeIn == 0) {
2135
+ context_enlargeIn = Math.pow(2, context_numBits);
2136
+ context_numBits++;
2137
+ }
2138
+ delete context_dictionaryToCreate[context_w];
2139
+ } else {
2140
+ value = context_dictionary[context_w];
2141
+ for (i = 0; i < context_numBits; i++) {
2142
+ context_data_val = context_data_val << 1 | value & 1;
2143
+ if (context_data_position == bitsPerChar - 1) {
2144
+ context_data_position = 0;
2145
+ context_data.push(getCharFromInt(context_data_val));
2146
+ context_data_val = 0;
2147
+ } else context_data_position++;
2148
+ value = value >> 1;
2149
+ }
2150
+ }
2151
+ context_enlargeIn--;
2152
+ if (context_enlargeIn == 0) {
2153
+ context_enlargeIn = Math.pow(2, context_numBits);
2154
+ context_numBits++;
2155
+ }
2156
+ context_dictionary[context_wc] = context_dictSize++;
2157
+ context_w = String(context_c);
2158
+ }
2159
+ }
2160
+ if (context_w !== "") {
2161
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2162
+ if (context_w.charCodeAt(0) < 256) {
2163
+ for (i = 0; i < context_numBits; i++) {
2164
+ context_data_val = context_data_val << 1;
2165
+ if (context_data_position == bitsPerChar - 1) {
2166
+ context_data_position = 0;
2167
+ context_data.push(getCharFromInt(context_data_val));
2168
+ context_data_val = 0;
2169
+ } else context_data_position++;
2170
+ }
2171
+ value = context_w.charCodeAt(0);
2172
+ for (i = 0; i < 8; i++) {
2173
+ context_data_val = context_data_val << 1 | value & 1;
2174
+ if (context_data_position == bitsPerChar - 1) {
2175
+ context_data_position = 0;
2176
+ context_data.push(getCharFromInt(context_data_val));
2177
+ context_data_val = 0;
2178
+ } else context_data_position++;
2179
+ value = value >> 1;
2180
+ }
2181
+ } else {
2182
+ value = 1;
2183
+ for (i = 0; i < context_numBits; i++) {
2184
+ context_data_val = context_data_val << 1 | value;
2185
+ if (context_data_position == bitsPerChar - 1) {
2186
+ context_data_position = 0;
2187
+ context_data.push(getCharFromInt(context_data_val));
2188
+ context_data_val = 0;
2189
+ } else context_data_position++;
2190
+ value = 0;
2191
+ }
2192
+ value = context_w.charCodeAt(0);
2193
+ for (i = 0; i < 16; i++) {
2194
+ context_data_val = context_data_val << 1 | value & 1;
2195
+ if (context_data_position == bitsPerChar - 1) {
2196
+ context_data_position = 0;
2197
+ context_data.push(getCharFromInt(context_data_val));
2198
+ context_data_val = 0;
2199
+ } else context_data_position++;
2200
+ value = value >> 1;
2201
+ }
2202
+ }
2203
+ context_enlargeIn--;
2204
+ if (context_enlargeIn == 0) {
2205
+ context_enlargeIn = Math.pow(2, context_numBits);
2206
+ context_numBits++;
2207
+ }
2208
+ delete context_dictionaryToCreate[context_w];
2209
+ } else {
2210
+ value = context_dictionary[context_w];
2211
+ for (i = 0; i < context_numBits; i++) {
2212
+ context_data_val = context_data_val << 1 | value & 1;
2213
+ if (context_data_position == bitsPerChar - 1) {
2214
+ context_data_position = 0;
2215
+ context_data.push(getCharFromInt(context_data_val));
2216
+ context_data_val = 0;
2217
+ } else context_data_position++;
2218
+ value = value >> 1;
2219
+ }
2220
+ }
2221
+ context_enlargeIn--;
2222
+ if (context_enlargeIn == 0) {
2223
+ context_enlargeIn = Math.pow(2, context_numBits);
2224
+ context_numBits++;
2225
+ }
2226
+ }
2227
+ value = 2;
2228
+ for (i = 0; i < context_numBits; i++) {
2229
+ context_data_val = context_data_val << 1 | value & 1;
2230
+ if (context_data_position == bitsPerChar - 1) {
2231
+ context_data_position = 0;
2232
+ context_data.push(getCharFromInt(context_data_val));
2233
+ context_data_val = 0;
2234
+ } else context_data_position++;
2235
+ value = value >> 1;
2236
+ }
2237
+ while (true) {
2238
+ context_data_val = context_data_val << 1;
2239
+ if (context_data_position == bitsPerChar - 1) {
2240
+ context_data.push(getCharFromInt(context_data_val));
2241
+ break;
2242
+ } else context_data_position++;
2243
+ }
2244
+ return context_data.join("");
2245
+ },
2246
+ decompress: function(compressed) {
2247
+ if (compressed == null) return "";
2248
+ if (compressed == "") return null;
2249
+ return LZString._decompress(compressed.length, 32768, function(index) {
2250
+ return compressed.charCodeAt(index);
2251
+ });
2252
+ },
2253
+ _decompress: function(length, resetValue, getNextValue) {
2254
+ var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
2255
+ val: getNextValue(0),
2256
+ position: resetValue,
2257
+ index: 1
2258
+ };
2259
+ for (i = 0; i < 3; i += 1) dictionary[i] = i;
2260
+ bits = 0;
2261
+ maxpower = Math.pow(2, 2);
2262
+ power = 1;
2263
+ while (power != maxpower) {
2264
+ resb = data.val & data.position;
2265
+ data.position >>= 1;
2266
+ if (data.position == 0) {
2267
+ data.position = resetValue;
2268
+ data.val = getNextValue(data.index++);
2269
+ }
2270
+ bits |= (resb > 0 ? 1 : 0) * power;
2271
+ power <<= 1;
2272
+ }
2273
+ switch (bits) {
2274
+ case 0:
2275
+ bits = 0;
2276
+ maxpower = Math.pow(2, 8);
2277
+ power = 1;
2278
+ while (power != maxpower) {
2279
+ resb = data.val & data.position;
2280
+ data.position >>= 1;
2281
+ if (data.position == 0) {
2282
+ data.position = resetValue;
2283
+ data.val = getNextValue(data.index++);
2284
+ }
2285
+ bits |= (resb > 0 ? 1 : 0) * power;
2286
+ power <<= 1;
2287
+ }
2288
+ c = f(bits);
2289
+ break;
2290
+ case 1:
2291
+ bits = 0;
2292
+ maxpower = Math.pow(2, 16);
2293
+ power = 1;
2294
+ while (power != maxpower) {
2295
+ resb = data.val & data.position;
2296
+ data.position >>= 1;
2297
+ if (data.position == 0) {
2298
+ data.position = resetValue;
2299
+ data.val = getNextValue(data.index++);
2300
+ }
2301
+ bits |= (resb > 0 ? 1 : 0) * power;
2302
+ power <<= 1;
2303
+ }
2304
+ c = f(bits);
2305
+ break;
2306
+ case 2: return "";
2307
+ }
2308
+ dictionary[3] = c;
2309
+ w = c;
2310
+ result.push(c);
2311
+ while (true) {
2312
+ if (data.index > length) return "";
2313
+ bits = 0;
2314
+ maxpower = Math.pow(2, numBits);
2315
+ power = 1;
2316
+ while (power != maxpower) {
2317
+ resb = data.val & data.position;
2318
+ data.position >>= 1;
2319
+ if (data.position == 0) {
2320
+ data.position = resetValue;
2321
+ data.val = getNextValue(data.index++);
2322
+ }
2323
+ bits |= (resb > 0 ? 1 : 0) * power;
2324
+ power <<= 1;
2325
+ }
2326
+ switch (c = bits) {
2327
+ case 0:
2328
+ bits = 0;
2329
+ maxpower = Math.pow(2, 8);
2330
+ power = 1;
2331
+ while (power != maxpower) {
2332
+ resb = data.val & data.position;
2333
+ data.position >>= 1;
2334
+ if (data.position == 0) {
2335
+ data.position = resetValue;
2336
+ data.val = getNextValue(data.index++);
2337
+ }
2338
+ bits |= (resb > 0 ? 1 : 0) * power;
2339
+ power <<= 1;
2340
+ }
2341
+ dictionary[dictSize++] = f(bits);
2342
+ c = dictSize - 1;
2343
+ enlargeIn--;
2344
+ break;
2345
+ case 1:
2346
+ bits = 0;
2347
+ maxpower = Math.pow(2, 16);
2348
+ power = 1;
2349
+ while (power != maxpower) {
2350
+ resb = data.val & data.position;
2351
+ data.position >>= 1;
2352
+ if (data.position == 0) {
2353
+ data.position = resetValue;
2354
+ data.val = getNextValue(data.index++);
2355
+ }
2356
+ bits |= (resb > 0 ? 1 : 0) * power;
2357
+ power <<= 1;
2358
+ }
2359
+ dictionary[dictSize++] = f(bits);
2360
+ c = dictSize - 1;
2361
+ enlargeIn--;
2362
+ break;
2363
+ case 2: return result.join("");
2364
+ }
2365
+ if (enlargeIn == 0) {
2366
+ enlargeIn = Math.pow(2, numBits);
2367
+ numBits++;
2368
+ }
2369
+ if (dictionary[c]) entry = dictionary[c];
2370
+ else if (c === dictSize) entry = w + w.charAt(0);
2371
+ else return null;
2372
+ result.push(entry);
2373
+ dictionary[dictSize++] = w + entry.charAt(0);
2374
+ enlargeIn--;
2375
+ w = entry;
2376
+ if (enlargeIn == 0) {
2377
+ enlargeIn = Math.pow(2, numBits);
2378
+ numBits++;
2379
+ }
2380
+ }
2381
+ }
2382
+ };
2383
+ return LZString;
2384
+ })();
2385
+ if (typeof define === "function" && define.amd) define(function() {
2386
+ return LZString;
2387
+ });
2388
+ else if (typeof module !== "undefined" && module != null) module.exports = LZString;
2389
+ else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
2390
+ return LZString;
2391
+ });
2392
+ })))(), 1);
2393
+ var DocumentModelNotFoundError = class extends Error {
2394
+ documentType;
2395
+ name = "DocumentModelNotFoundError";
2396
+ constructor(documentType) {
2397
+ super(`Document model module for type ${documentType} not found`);
2398
+ this.documentType = documentType;
2399
+ }
2400
+ static isError(error) {
2401
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
2402
+ }
2403
+ };
2404
+ var DocumentTypeMismatchError = class extends Error {
2405
+ constructor(documentId, expectedType, actualType) {
2406
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
2407
+ }
2408
+ };
2409
+ var NoSelectedDocumentError = class extends Error {
2410
+ constructor() {
2411
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
2412
+ }
2413
+ };
2414
+ function getUserPermissions() {
2415
+ const user = window.ph?.renown?.user;
2416
+ const allowList = window.ph?.allowList;
2417
+ if (!allowList) return {
2418
+ isAllowedToCreateDocuments: true,
2419
+ isAllowedToEditDocuments: true
2420
+ };
2421
+ return {
2422
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
2423
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2424
+ };
2425
+ }
2426
+ const BASE_STATE_KEYS = new Set(["auth"]);
2427
+ const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2428
+ async function downloadFile(document, fileName) {
2429
+ try {
2430
+ const data = await createZip(document);
2431
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
2432
+ const link = window.document.createElement("a");
2433
+ link.style.display = "none";
2434
+ link.href = URL.createObjectURL(blob);
2435
+ link.download = fileName;
2436
+ window.document.body.appendChild(link);
2437
+ link.click();
2438
+ window.document.body.removeChild(link);
2439
+ } catch (e) {
2440
+ logger.error(e instanceof Error ? e.message : String(e));
2441
+ }
2442
+ }
2443
+ async function getDocumentExtension(document) {
2444
+ const documentType = document.header.documentType;
2445
+ let rawExtension;
2446
+ if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2447
+ else {
2448
+ const reactorClient = window.ph?.reactorClient;
2449
+ if (reactorClient) {
2450
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2451
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
2452
+ }
2453
+ }
2454
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
2455
+ }
2456
+ /**
2457
+ * Fetches all operations for a document using cursor-based pagination.
2458
+ * The reactor client handles multi-scope cursors transparently via
2459
+ * composite cursors, so all scopes are fetched in a single paginated stream.
2460
+ */
2461
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2462
+ const scopes = Object.keys(document.state).filter((k) => !BASE_STATE_KEYS.has(k));
2463
+ const operations = {};
2464
+ for (const scope of scopes) operations[scope] = [];
2465
+ let cursor = "";
2466
+ do {
2467
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
2468
+ cursor,
2469
+ limit: pageSize
2470
+ });
2471
+ for (const op of page.results) {
2472
+ const scope = op.action.scope ?? "global";
2473
+ if (operations[scope]) operations[scope].push(op);
2474
+ }
2475
+ cursor = page.nextCursor ?? "";
2476
+ } while (cursor);
2477
+ return operations;
2478
+ }
2479
+ function extractInitialState(documentScopeOps) {
2480
+ const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
2481
+ if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
2482
+ const input = upgradeOp.action.input;
2483
+ const initialState = input.initialState ?? input.state;
2484
+ if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
2485
+ return initialState;
2486
+ }
2487
+ function filterDomainOperations(operations) {
2488
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2489
+ }
2490
+ async function exportFile(document, suggestedName) {
2491
+ const reactorClient = window.ph?.reactorClient;
2492
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2493
+ const operations = await fetchDocumentOperations(reactorClient, document);
2494
+ const initialState = extractInitialState(operations["document"] ?? []);
2495
+ const documentWithOps = {
2496
+ ...document,
2497
+ operations,
2498
+ initialState
2499
+ };
2500
+ const extension = await getDocumentExtension(documentWithOps);
2501
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
2502
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
2503
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
2504
+ try {
2505
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
2506
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
2507
+ return fileHandle;
2508
+ } catch (e) {
2509
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
2510
+ }
2511
+ }
2512
+ async function loadFile(path) {
2513
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2514
+ const reactorClient = window.ph?.reactorClient;
2515
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2516
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2517
+ const documentModelModule = documentModelModules.find((module) => module.documentModel.global.id === baseDocument.header.documentType);
2518
+ if (!documentModelModule) throw new DocumentModelNotFoundError(baseDocument.header.documentType);
2519
+ return documentModelModule.utils.loadFromInput(path);
2520
+ }
2521
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
2522
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2523
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2524
+ const reactorClient = window.ph?.reactorClient;
2525
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2526
+ const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2527
+ const newDocument = document ?? documentModelModule.utils.createDocument();
2528
+ newDocument.header.name = name;
2529
+ if (preferredEditor) newDocument.header.meta = {
2530
+ ...newDocument.header.meta,
2531
+ preferredEditor
2532
+ };
2533
+ let newDoc;
2534
+ try {
2535
+ newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2536
+ } catch (e) {
2537
+ logger.error("Error adding document: @error", e);
2538
+ throw new Error("There was an error adding document", { cause: e });
2539
+ }
2540
+ return {
2541
+ id: newDoc.header.id,
2542
+ name: newDoc.header.name,
2543
+ documentType,
2544
+ parentFolder: parentFolder ?? null,
2545
+ kind: "file"
2546
+ };
2547
+ }
2548
+ async function addFile(file, driveId, name, parentFolder) {
2549
+ logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2550
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2551
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2552
+ const document = await loadFile(file);
2553
+ let duplicateId = false;
2554
+ const reactorClient = window.ph?.reactorClient;
2555
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2556
+ try {
2557
+ await reactorClient.get(document.header.id);
2558
+ duplicateId = true;
2559
+ } catch {}
2560
+ const documentId = duplicateId ? generateId() : document.header.id;
2561
+ const header = createPresignedHeader(documentId, document.header.documentType);
2562
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2563
+ header.meta = document.header.meta;
2564
+ header.name = name || document.header.name;
2565
+ const initialDocument = {
2566
+ ...document,
2567
+ header,
2568
+ state: document.initialState,
2569
+ operations: Object.keys(document.operations).reduce((acc, key) => {
2570
+ acc[key] = [];
2571
+ return acc;
2572
+ }, {})
2573
+ };
2574
+ await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2575
+ await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
2576
+ }
2577
+ async function addFolder(driveId, name, parentFolder) {
2578
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2579
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2580
+ const reactorClient = window.ph?.reactorClient;
2581
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2582
+ await reactorClient.get(driveId);
2583
+ const folderId = generateId();
2584
+ const node = (await reactorClient.execute(driveId, "main", [addFolder$1({
2585
+ id: folderId,
2586
+ name,
2587
+ parentFolder
2588
+ })])).state.global.nodes.find((node) => node.id === folderId);
2589
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2590
+ return node;
2591
+ }
2592
+ async function renameNode(driveId, nodeId, name) {
2593
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2594
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2595
+ const reactorClient = window.ph?.reactorClient;
2596
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2597
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2598
+ const node = (await reactorClient.execute(driveId, "main", [updateNode({
2599
+ id: nodeId,
2600
+ name
2601
+ })])).state.global.nodes.find((n) => n.id === nodeId);
2602
+ if (!node) throw new Error("There was an error renaming node in the drive");
2603
+ return node;
2604
+ }
2605
+ async function renameDriveNode(driveId, nodeId, name) {
2606
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2607
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2608
+ const reactorClient = window.ph?.reactorClient;
2609
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2610
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2611
+ await reactorClient.execute(driveId, "main", [updateNode({
2612
+ id: nodeId,
2613
+ name
2614
+ })]);
2615
+ return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2616
+ }
2617
+ async function moveNodeById(args) {
2618
+ const { driveId, srcId, targetId } = args;
2619
+ if (!driveId || !srcId) return;
2620
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2621
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2622
+ const reactorClient = window.ph?.reactorClient;
2623
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2624
+ const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2625
+ if (t(targetParentFolder, srcId)) return;
2626
+ return await reactorClient.execute(driveId, "main", [moveNode({
2627
+ srcFolder: srcId,
2628
+ targetParentFolder
2629
+ })]);
2630
+ }
2631
+ async function moveNode$1(driveId, src, target) {
2632
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2633
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2634
+ const reactorClient = window.ph?.reactorClient;
2635
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2636
+ return await reactorClient.execute(driveId, "main", [moveNode({
2637
+ srcFolder: src.id,
2638
+ targetParentFolder: target?.id
2639
+ })]);
2640
+ }
2641
+ async function _duplicateDocument(reactor, document, newId = generateId()) {
2642
+ const documentModule = await reactor.getDocumentModelModule(document.header.documentType);
2643
+ return replayDocument(document.initialState, document.operations, documentModule.reducer, createPresignedHeader(newId, document.header.documentType));
2644
+ }
2645
+ async function copyNode$1(driveId, src, target) {
2646
+ const reactor = window.ph?.reactorClient;
2647
+ if (!reactor) return;
2648
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2649
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2650
+ const drive = await reactor.get(driveId);
2651
+ const copyNodesInput = generateNodesCopy({
2652
+ srcId: src.id,
2653
+ targetParentFolder: target?.id,
2654
+ targetName: src.name
2655
+ }, () => generateId(), drive.state.global.nodes);
2656
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
2657
+ for (const copyNodeInput of copyNodesInput) {
2658
+ const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2659
+ if (node) {
2660
+ const resolvedName = handleTargetNameCollisions({
2661
+ nodes: drive.state.global.nodes,
2662
+ srcName: copyNodeInput.targetName || node.name,
2663
+ srcKind: isFileNode(node) ? "file" : "folder",
2664
+ targetParentFolder: copyNodeInput.targetParentFolder || null
2665
+ });
2666
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2667
+ }
2668
+ }
2669
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2670
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2671
+ return node !== void 0 && isFileNode(node);
2672
+ });
2673
+ for (const fileNodeToCopy of fileNodesToCopy) try {
2674
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2675
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2676
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
2677
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2678
+ } catch (e) {
2679
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2680
+ }
2681
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2682
+ }
2683
+ const baseDocumentModelsMap = {
2684
+ DocumentModel: documentModelDocumentModelModule,
2685
+ DocumentDrive: driveDocumentModelModule,
2686
+ ReactorDrive: reactorDriveDocumentModelModule
2687
+ };
2688
+ Object.values(baseDocumentModelsMap);
2689
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2690
+ /** Sets whether external controls are enabled for a given editor. */
2691
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2692
+ /** Gets whether external controls are enabled for a given editor. */
2693
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2694
+ isExternalControlsEnabledEventFunctions.addEventHandler;
2695
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2696
+ /** Sets whether drag and drop is enabled for a given app. */
2697
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2698
+ /** Gets whether drag and drop is enabled for a given app. */
2699
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2700
+ isDragAndDropEnabledEventFunctions.addEventHandler;
2701
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2702
+ /** Sets the allowed document types for a given app. */
2703
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2704
+ /** Defines the document types a drive supports.
2705
+ *
2706
+ * Defaults to all of the document types registered in the reactor.
2707
+ */
2708
+ function useAllowedDocumentTypes() {
2709
+ return allowedDocumentTypesEventFunctions.useValue();
2710
+ }
2711
+ allowedDocumentTypesEventFunctions.addEventHandler;
2712
+ const phAppConfigSetters = {
2713
+ allowedDocumentTypes: setAllowedDocumentTypes,
2714
+ isDragAndDropEnabled: setIsDragAndDropEnabled
2715
+ };
2716
+ const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
2717
+ const phAppConfigHooks = {
2718
+ allowedDocumentTypes: useAllowedDocumentTypes,
2719
+ isDragAndDropEnabled: useIsDragAndDropEnabled
2720
+ };
2721
+ const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
2722
+ const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
2723
+ const { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions("version");
2724
+ const { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions("requiresHardRefresh");
2725
+ const { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions("warnOutdatedApp");
2726
+ const { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions("studioMode");
2727
+ const { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions("basePath");
2728
+ const { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions("versionCheckInterval");
2729
+ const { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions("cliVersion");
2730
+ const { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions("fileUploadOperationsChunkSize");
2731
+ const { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions("isDocumentModelSelectionSettingsEnabled");
2732
+ const { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions("gaTrackingId");
2733
+ const { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions("defaultDrivesUrl");
2734
+ const { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions("drivesPreserveStrategy");
2735
+ const { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
2736
+ const { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions("isAddDriveEnabled");
2737
+ const { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions("isPublicDrivesEnabled");
2738
+ const { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions("isAddPublicDrivesEnabled");
2739
+ const { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions("isDeletePublicDrivesEnabled");
2740
+ const { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions("isCloudDrivesEnabled");
2741
+ const { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions("isAddCloudDrivesEnabled");
2742
+ const { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteCloudDrivesEnabled");
2743
+ const { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
2744
+ const { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions("isAddLocalDrivesEnabled");
2745
+ const { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteLocalDrivesEnabled");
2746
+ const { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions("isEditorDebugModeEnabled");
2747
+ const { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions("isEditorReadModeEnabled");
2748
+ const { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled");
2749
+ const { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions("isDiffAnalyticsEnabled");
2750
+ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions("isDriveAnalyticsEnabled");
2751
+ const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
2752
+ const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
2753
+ const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
2754
+ const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
2755
+ const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
2756
+ const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
2757
+ const { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions("isSentryTracingEnabled");
2758
+ const { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions("isExternalProcessorsEnabled");
2759
+ const { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions("isExternalPackagesEnabled");
2760
+ const enabledEditorsEventFunctions = makePHEventFunctions("enabledEditors");
2761
+ /** Sets the enabled editors for Connect. */
2762
+ const setEnabledEditors = enabledEditorsEventFunctions.setValue;
2763
+ /** Gets the enabled editors for Connect. */
2764
+ const useEnabledEditors = enabledEditorsEventFunctions.useValue;
2765
+ enabledEditorsEventFunctions.addEventHandler;
2766
+ const disabledEditorsEventFunctions = makePHEventFunctions("disabledEditors");
2767
+ /** Sets the disabled editors for Connect. */
2768
+ const setDisabledEditors = disabledEditorsEventFunctions.setValue;
2769
+ /** Gets the disabled editors for Connect. */
2770
+ const useDisabledEditors = disabledEditorsEventFunctions.useValue;
2771
+ disabledEditorsEventFunctions.addEventHandler;
2772
+ const isRelationalProcessorsEnabled = makePHEventFunctions("isRelationalProcessorsEnabled");
2773
+ /** Sets the isRelationalProcessorsEnabled for Connect. */
2774
+ const setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;
2775
+ /** Gets the isRelationalProcessorsEnabled for Connect. */
2776
+ const useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;
2777
+ isRelationalProcessorsEnabled.addEventHandler;
2778
+ const isExternalRelationalProcessorsEnabled = makePHEventFunctions("isExternalRelationalProcessorsEnabled");
2779
+ /** Sets the isExternalRelationalProcessorsEnabled for Connect. */
2780
+ const setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;
2781
+ /** Gets the isExternalRelationalProcessorsEnabled for Connect. */
2782
+ const useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;
2783
+ isExternalRelationalProcessorsEnabled.addEventHandler;
2784
+ const isAnalyticsEnabledEventFunctions = makePHEventFunctions("isAnalyticsEnabled");
2785
+ /** Sets the isAnalyticsEnabled for Connect. */
2786
+ const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;
2787
+ /** Gets the isAnalyticsEnabled for Connect. */
2788
+ const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;
2789
+ isAnalyticsEnabledEventFunctions.addEventHandler;
2790
+ const isAnalyticsExternalProcessorsEnabled = makePHEventFunctions("isAnalyticsExternalProcessorsEnabled");
2791
+ /** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */
2792
+ const setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;
2793
+ /** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */
2794
+ const useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;
2795
+ isAnalyticsExternalProcessorsEnabled.addEventHandler;
2796
+ const analyticsDatabaseNameEventFunctions = makePHEventFunctions("analyticsDatabaseName");
2797
+ /** Sets the analytics database name for Connect. */
2798
+ const setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;
2799
+ /** Gets the analytics database name for Connect. */
2800
+ const useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;
2801
+ analyticsDatabaseNameEventFunctions.addEventHandler;
2802
+ const logLevelEventFunctions = makePHEventFunctions("logLevel");
2803
+ /** Sets the log level for Connect. */
2804
+ const setLogLevel = logLevelEventFunctions.setValue;
2805
+ /** Gets the log level for Connect. */
2806
+ const useLogLevel = logLevelEventFunctions.useValue;
2807
+ logLevelEventFunctions.addEventHandler;
2808
+ const allowListEventFunctions = makePHEventFunctions("allowList");
2809
+ /** Sets the allow list for Connect. */
2810
+ const setAllowList = allowListEventFunctions.setValue;
2811
+ /** Gets the allow list for Connect. */
2812
+ const useAllowList = allowListEventFunctions.useValue;
2813
+ allowListEventFunctions.addEventHandler;
2814
+ const nonUserConfigSetters = {
2815
+ routerBasename: setRouterBasename,
2816
+ version: setVersion,
2817
+ requiresHardRefresh: setRequiresHardRefresh,
2818
+ warnOutdatedApp: setWarnOutdatedApp,
2819
+ studioMode: setStudioMode,
2820
+ basePath: setBasePath,
2821
+ versionCheckInterval: setVersionCheckInterval,
2822
+ cliVersion: setCliVersion,
2823
+ fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,
2824
+ isDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,
2825
+ gaTrackingId: setGaTrackingId,
2826
+ defaultDrivesUrl: setDefaultDrivesUrl,
2827
+ drivesPreserveStrategy: setDrivesPreserveStrategy,
2828
+ isLocalDrivesEnabled: setIsLocalDrivesEnabled,
2829
+ isAddDriveEnabled: setIsAddDriveEnabled,
2830
+ isPublicDrivesEnabled: setIsPublicDrivesEnabled,
2831
+ isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,
2832
+ isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,
2833
+ isCloudDrivesEnabled: setIsCloudDrivesEnabled,
2834
+ isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,
2835
+ isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,
2836
+ isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,
2837
+ isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,
2838
+ isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,
2839
+ isEditorReadModeEnabled: setIsEditorReadModeEnabled,
2840
+ isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,
2841
+ isExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,
2842
+ isAnalyticsEnabled: setIsAnalyticsEnabled,
2843
+ analyticsDatabaseName: setAnalyticsDatabaseName,
2844
+ isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,
2845
+ isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,
2846
+ isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,
2847
+ isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,
2848
+ renownUrl: setRenownUrl,
2849
+ renownNetworkId: setRenownNetworkId,
2850
+ renownChainId: setRenownChainId,
2851
+ sentryRelease: setSentryRelease,
2852
+ sentryDsn: setSentryDsn,
2853
+ sentryEnv: setSentryEnv,
2854
+ isSentryTracingEnabled: setIsSentryTracingEnabled,
2855
+ isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,
2856
+ isExternalPackagesEnabled: setIsExternalPackagesEnabled,
2857
+ allowList: setAllowList,
2858
+ logLevel: setLogLevel,
2859
+ disabledEditors: setDisabledEditors,
2860
+ enabledEditors: setEnabledEditors
2861
+ };
2862
+ const phGlobalConfigSetters = {
2863
+ ...phAppConfigSetters,
2864
+ ...phDocumentEditorConfigSetters,
2865
+ ...nonUserConfigSetters
2866
+ };
2867
+ const nonUserConfigHooks = {
2868
+ routerBasename: useRouterBasename,
2869
+ version: useVersion,
2870
+ requiresHardRefresh: useRequiresHardRefresh,
2871
+ warnOutdatedApp: useWarnOutdatedApp,
2872
+ studioMode: useStudioMode,
2873
+ basePath: useBasePath,
2874
+ versionCheckInterval: useVersionCheckInterval,
2875
+ cliVersion: useCliVersion,
2876
+ fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,
2877
+ isDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,
2878
+ gaTrackingId: useGaTrackingId,
2879
+ defaultDrivesUrl: useDefaultDrivesUrl,
2880
+ drivesPreserveStrategy: useDrivesPreserveStrategy,
2881
+ isAddDriveEnabled: useIsAddDriveEnabled,
2882
+ isPublicDrivesEnabled: useIsPublicDrivesEnabled,
2883
+ isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,
2884
+ isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,
2885
+ isCloudDrivesEnabled: useIsCloudDrivesEnabled,
2886
+ isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,
2887
+ isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,
2888
+ isLocalDrivesEnabled: useIsLocalDrivesEnabled,
2889
+ isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,
2890
+ isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,
2891
+ isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,
2892
+ isEditorReadModeEnabled: useIsEditorReadModeEnabled,
2893
+ isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,
2894
+ isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,
2895
+ isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,
2896
+ renownUrl: useRenownUrl,
2897
+ renownNetworkId: useRenownNetworkId,
2898
+ renownChainId: useRenownChainId,
2899
+ sentryRelease: useSentryRelease,
2900
+ sentryDsn: useSentryDsn,
2901
+ sentryEnv: useSentryEnv,
2902
+ isSentryTracingEnabled: useIsSentryTracingEnabled,
2903
+ isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,
2904
+ isExternalPackagesEnabled: useIsExternalPackagesEnabled,
2905
+ allowList: useAllowList,
2906
+ isAnalyticsEnabled: useIsAnalyticsEnabled,
2907
+ isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,
2908
+ isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,
2909
+ isExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,
2910
+ analyticsDatabaseName: useAnalyticsDatabaseName,
2911
+ logLevel: useLogLevel,
2912
+ disabledEditors: useDisabledEditors,
2913
+ enabledEditors: useEnabledEditors
2914
+ };
2915
+ ({
2916
+ ...phAppConfigHooks,
2917
+ ...phDocumentEditorConfigHooks,
2918
+ ...nonUserConfigHooks
2919
+ });
2920
+ const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
2921
+ attachmentServiceEventFunctions.useValue;
2922
+ attachmentServiceEventFunctions.setValue;
2923
+ attachmentServiceEventFunctions.addEventHandler;
2924
+ const featuresEventFunctions = makePHEventFunctions("features");
2925
+ featuresEventFunctions.useValue;
2926
+ featuresEventFunctions.setValue;
2927
+ featuresEventFunctions.addEventHandler;
2928
+ function resolveUrlPathname(path) {
2929
+ return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2930
+ }
2931
+ /** Returns the current path without the base path */
2932
+ function getPathWithoutBase(path) {
2933
+ const basePath = window.ph?.basePath ?? "/";
2934
+ return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
2935
+ }
2936
+ /** Makes a URL component for a node. */
2937
+ function makeNodeSlug(node) {
2938
+ if (!node) return "";
2939
+ const nodeName = node.name;
2940
+ if (!nodeName) return slug(node.id);
2941
+ return slug(`${nodeName}-${node.id}`);
2942
+ }
2943
+ /** Extracts the node slug from a path.
2944
+ *
2945
+ * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
2946
+ */
2947
+ function extractNodeSlugFromPath(path) {
2948
+ const currentPath = getPathWithoutBase(path);
2949
+ return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
2950
+ }
2951
+ /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
2952
+ function findUuid(input) {
2953
+ if (!input) return void 0;
2954
+ 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];
2955
+ }
2956
+ function extractNodeIdFromSlug(nodeSlug) {
2957
+ return findUuid(nodeSlug);
2958
+ }
2959
+ /** Extracts the drive slug from a path.
2960
+ * Used for extracting drive ids from drive slugs in the URL.
2961
+ * Expects the path to be in the format `/d/<drive-slug>`.
2962
+ */
2963
+ function extractDriveSlugFromPath(path) {
2964
+ const currentPath = getPathWithoutBase(path);
2965
+ return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
2966
+ }
2967
+ /**
2968
+ * Creates a URL string with the given pathname while preserving existing query parameters.
2969
+ */
2970
+ function createUrlWithPreservedParams(pathname) {
2971
+ const search = window.location.search;
2972
+ return search ? `${pathname}${search}` : pathname;
2973
+ }
2974
+ const drivesEventFunctions = makePHEventFunctions("drives");
2975
+ /** Returns all of the drives in the reactor */
2976
+ const useDrives = drivesEventFunctions.useValue;
2977
+ /** Sets the drives in the reactor */
2978
+ const setDrives = drivesEventFunctions.setValue;
2979
+ drivesEventFunctions.addEventHandler;
2980
+ const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
2981
+ const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
2982
+ const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
2983
+ selectedNodeIdEventFunctions.addEventHandler;
2984
+ /** Sets the selected node (file or folder). */
2985
+ function setSelectedNode(nodeOrNodeSlug) {
2986
+ const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
2987
+ setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
2988
+ const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
2989
+ if (!driveSlugFromPath) return;
2990
+ if (!nodeSlug) {
2991
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
2992
+ if (pathname === window.location.pathname) return;
2993
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2994
+ return;
2995
+ }
2996
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
2997
+ if (pathname === window.location.pathname) return;
2998
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2999
+ }
3000
+ const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
3001
+ /** Returns the selected drive id */
3002
+ const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
3003
+ /** Sets the selected drive id */
3004
+ const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
3005
+ selectedDriveIdEventFunctions.addEventHandler;
3006
+ /** Returns the selected drive, or undefined if no drive is selected */
3007
+ function useSelectedDriveSafe() {
3008
+ const selectedDriveId = useSelectedDriveId();
3009
+ const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
3010
+ const [drive, dispatch] = useDispatch(selectedDrive);
3011
+ if (!selectedDrive) return [void 0, void 0];
3012
+ return [drive, dispatch];
3013
+ }
3014
+ function setSelectedDrive(driveOrDriveSlug) {
3015
+ const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
3016
+ const drives = window.ph?.drives;
3017
+ const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
3018
+ if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
3019
+ if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
3020
+ deferDriveSelection(driveSlug);
3021
+ return;
3022
+ }
3023
+ cancelPendingDriveSelection();
3024
+ setSelectedDriveId(driveId);
3025
+ if (!driveId) {
3026
+ const pathname = resolveUrlPathname("/");
3027
+ if (pathname === window.location.pathname) return;
3028
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3029
+ return;
3030
+ }
3031
+ const pathname = resolveUrlPathname(`/d/${driveSlug}`);
3032
+ if (pathname === window.location.pathname) return;
3033
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3034
+ }
3035
+ const DEFERRED_DRIVE_TICK_MS = 2e3;
3036
+ const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
3037
+ function isInitialSyncInFlight() {
3038
+ const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
3039
+ if (!remotes?.length) return false;
3040
+ return remotes.some((remote) => {
3041
+ try {
3042
+ const snapshot = remote.channel.getConnectionState();
3043
+ return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
3044
+ } catch {
3045
+ return false;
3046
+ }
3047
+ });
3048
+ }
3049
+ let pendingHandler;
3050
+ let pendingTimeout;
3051
+ function cancelPendingDriveSelection() {
3052
+ if (pendingHandler) {
3053
+ window.removeEventListener("ph:drivesUpdated", pendingHandler);
3054
+ pendingHandler = void 0;
3055
+ }
3056
+ if (pendingTimeout) {
3057
+ clearTimeout(pendingTimeout);
3058
+ pendingTimeout = void 0;
3059
+ }
3060
+ }
3061
+ function deferDriveSelection(driveSlug) {
3062
+ cancelPendingDriveSelection();
3063
+ const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
3064
+ const handler = () => {
3065
+ if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
3066
+ cancelPendingDriveSelection();
3067
+ setSelectedDrive(driveSlug);
3068
+ setSelectedNode(nodeSlug);
3069
+ };
3070
+ pendingHandler = handler;
3071
+ window.addEventListener("ph:drivesUpdated", handler);
3072
+ const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
3073
+ const scheduleTick = () => {
3074
+ pendingTimeout = setTimeout(() => {
3075
+ if (Date.now() < deadline && isInitialSyncInFlight()) {
3076
+ scheduleTick();
3077
+ return;
3078
+ }
3079
+ cancelPendingDriveSelection();
3080
+ const pathname = resolveUrlPathname("/");
3081
+ if (pathname === window.location.pathname) return;
3082
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3083
+ }, DEFERRED_DRIVE_TICK_MS);
3084
+ };
3085
+ scheduleTick();
3086
+ }
3087
+ function useDropTarget() {
3088
+ const [isDropTarget, setIsDropTarget] = useState(false);
3089
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
3090
+ const targetSetter = n$1(() => setIsDropTarget(true), {
3091
+ triggerAt: "start",
3092
+ minQuietPeriodMs: 100
3093
+ });
3094
+ const targetUnsetter = n$1(() => setIsDropTarget(false), {
3095
+ triggerAt: "start",
3096
+ minQuietPeriodMs: 100
3097
+ });
3098
+ function setTarget() {
3099
+ if (!isDragAndDropEnabled) return;
3100
+ targetUnsetter.cancel();
3101
+ targetSetter.call();
3102
+ }
3103
+ function unsetTarget() {
3104
+ if (!isDragAndDropEnabled) return;
3105
+ targetSetter.cancel();
3106
+ targetUnsetter.call();
3107
+ }
3108
+ return {
3109
+ isDropTarget,
3110
+ setTarget,
3111
+ unsetTarget
3112
+ };
3113
+ }
3114
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3115
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
3116
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
3117
+ draggingNodeEventFunctions.addEventHandler;
3118
+ const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3119
+ reducer: (_, newNode) => newNode,
3120
+ triggerAt: "start",
3121
+ minQuietPeriodMs: 100
3122
+ });
3123
+ const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3124
+ triggerAt: "start",
3125
+ minQuietPeriodMs: 100
3126
+ });
3127
+ function setDragging(node) {
3128
+ draggingNodeUnsetter.cancel();
3129
+ draggingNodeSetter.call(node);
3130
+ }
3131
+ function unsetDragging() {
3132
+ draggingNodeSetter.cancel();
3133
+ draggingNodeUnsetter.call();
3134
+ }
3135
+ 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));
3136
+ function useDragNode(args) {
3137
+ const { srcId, parentId } = args;
3138
+ const driveId = useSelectedDriveId();
3139
+ const draggingNodeId = useDraggingNode()?.srcId;
3140
+ const params = {
3141
+ driveId,
3142
+ srcId,
3143
+ parentId
3144
+ };
3145
+ const draggable = isNodeDrag(params);
3146
+ const isDragging = t$4({
3147
+ srcId,
3148
+ draggingNodeId
3149
+ }, [
3150
+ () => draggable,
3151
+ ({ srcId }) => e$2(srcId),
3152
+ ({ draggingNodeId }) => e$2(draggingNodeId),
3153
+ ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3154
+ ]);
3155
+ const onDragStart = () => {
3156
+ if (!draggable) return;
3157
+ setDragging(params);
3158
+ };
3159
+ const onDragEnd = () => {
3160
+ if (!draggable) return;
3161
+ unsetDragging();
3162
+ };
3163
+ return {
3164
+ isDragging,
3165
+ draggable,
3166
+ onDragStart,
3167
+ onDragEnd
3168
+ };
3169
+ }
3170
+ 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));
3171
+ function useDropNode(targetId) {
3172
+ const driveId = useSelectedDriveId();
3173
+ const { srcId, parentId } = useDraggingNode() ?? {};
3174
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3175
+ const params = {
3176
+ driveId,
3177
+ parentId,
3178
+ targetId,
3179
+ srcId
3180
+ };
3181
+ function handleNodeDrop(event, cb) {
3182
+ if (!isNodeDrop(params)) return;
3183
+ event.preventDefault();
3184
+ event.stopPropagation();
3185
+ cb?.();
3186
+ }
3187
+ const onDragEnter = (event) => handleNodeDrop(event);
3188
+ const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3189
+ const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3190
+ const onDrop = (event) => handleNodeDrop(event, e(() => {
3191
+ unsetDragging();
3192
+ unsetTarget();
3193
+ moveNodeById(params).catch(console.error);
3194
+ }));
3195
+ return {
3196
+ isDropTarget,
3197
+ onDragEnter,
3198
+ onDragOver,
3199
+ onDragLeave,
3200
+ onDrop
3201
+ };
3202
+ }
3203
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3204
+ graphQLReactorClientEventFunctions.useValue;
3205
+ graphQLReactorClientEventFunctions.setValue;
3206
+ graphQLReactorClientEventFunctions.addEventHandler;
3207
+ const modalEventFunctions = makePHEventFunctions("modal");
3208
+ modalEventFunctions.useValue;
3209
+ /** Sets the current modal */
3210
+ const setPHModal = modalEventFunctions.setValue;
3211
+ modalEventFunctions.addEventHandler;
3212
+ /** Shows a modal */
3213
+ function showPHModal(modal) {
3214
+ setPHModal(modal);
3215
+ }
3216
+ /** Shows the create document modal */
3217
+ function showCreateDocumentModal(documentType) {
3218
+ setPHModal({
3219
+ type: "createDocument",
3220
+ documentType
3221
+ });
3222
+ }
3223
+ /** Shows the delete node modal */
3224
+ function showDeleteNodeModal(nodeOrId) {
3225
+ setPHModal({
3226
+ type: "deleteItem",
3227
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
3228
+ });
3229
+ }
3230
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3231
+ packageDiscoveryFunctions.useValue;
3232
+ packageDiscoveryFunctions.setValue;
3233
+ packageDiscoveryFunctions.addEventHandler;
3234
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3235
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3236
+ /** Returns the reactor client module */
3237
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3238
+ reactorClientModuleEventFunctions.setValue;
3239
+ reactorClientModuleEventFunctions.addEventHandler;
3240
+ reactorClientEventFunctions.useValue;
3241
+ reactorClientEventFunctions.setValue;
3242
+ reactorClientEventFunctions.addEventHandler;
3243
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3244
+ const useSyncList = () => {
3245
+ return useSync()?.list() ?? [];
3246
+ };
3247
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3248
+ revisionHistoryEventFunctions.useValue;
3249
+ /** Sets revision history visibility */
3250
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3251
+ revisionHistoryEventFunctions.addEventHandler;
3252
+ /** Shows the revision history */
3253
+ function showRevisionHistory() {
3254
+ setRevisionHistoryVisible(true);
3255
+ }
3256
+ /** Sorts nodes by name. */
3257
+ function sortNodesByName(nodes) {
3258
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
3259
+ }
3260
+ /** Returns whether a node is a file. */
3261
+ function isFileNodeKind(node) {
3262
+ if (!node) return false;
3263
+ return node.kind.toUpperCase() === "FILE";
3264
+ }
3265
+ /** Returns whether a node is a folder. */
3266
+ function isFolderNodeKind(node) {
3267
+ if (!node) return false;
3268
+ return node.kind.toUpperCase() === "FOLDER";
3269
+ }
3270
+ /** Returns the nodes in the selected drive. */
3271
+ function useNodesInSelectedDrive() {
3272
+ const [selectedDrive] = useSelectedDriveSafe();
3273
+ return selectedDrive?.state.global.nodes;
3274
+ }
3275
+ /** Returns the folder nodes in the selected drive. */
3276
+ function useFolderNodesInSelectedDrive() {
3277
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
3278
+ }
3279
+ /** Returns the selected node. */
3280
+ function useSelectedNode() {
3281
+ const selectedNodeId = useSelectedNodeId();
3282
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3283
+ }
3284
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3285
+ selectedTimelineItemEventFunctions.useValue;
3286
+ selectedTimelineItemEventFunctions.setValue;
3287
+ selectedTimelineItemEventFunctions.addEventHandler;
3288
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3289
+ selectedTimelineRevisionEventFunctions.useValue;
3290
+ selectedTimelineRevisionEventFunctions.setValue;
3291
+ selectedTimelineRevisionEventFunctions.addEventHandler;
3292
+ const toastEventFunctions = makePHEventFunctions("toast");
3293
+ /** Returns the toast function */
3294
+ const usePHToast = toastEventFunctions.useValue;
3295
+ toastEventFunctions.setValue;
3296
+ toastEventFunctions.addEventHandler;
3297
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
3298
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
3299
+ /** Returns all of the Vetra packages loaded by the Connect instance */
3300
+ const useVetraPackages = () => {
3301
+ const packageManager = useVetraPackageManager();
3302
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
3303
+ };
3304
+ vetraPackageManagerFunctions.addEventHandler;
3305
+ function useDocumentModelModules() {
3306
+ 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);
3307
+ }
3308
+ function useDocumentModelModuleById(id) {
3309
+ return useDocumentModelModules()?.find((module) => module.documentModel.global.id === id);
3310
+ }
3311
+ /** Returns the selected folder. */
3312
+ function useSelectedFolder() {
3313
+ const selectedNode = useSelectedNode();
3314
+ if (isFolderNodeKind(selectedNode)) return selectedNode;
3315
+ }
3316
+ /** Returns the child nodes for the selected drive or folder. */
3317
+ function useNodesInSelectedDriveOrFolder() {
3318
+ const nodes = useNodesInSelectedDrive();
3319
+ const selectedFolderId = useSelectedFolder()?.id;
3320
+ if (!nodes) return [];
3321
+ if (!selectedFolderId) return sortNodesByName(nodes.filter((n) => !n.parentFolder));
3322
+ return sortNodesByName(nodes.filter((n) => n.parentFolder === selectedFolderId));
3323
+ }
3324
+ function callGlobalSetterForKey(key, value) {
3325
+ const setter = phGlobalConfigSetters[key];
3326
+ setter(value);
3327
+ }
3328
+ /** Sets the global drive config.
3329
+ *
3330
+ * Pass in a partial object of the global drive config to set.
3331
+ */
3332
+ function setPHAppConfig(config) {
3333
+ for (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);
3334
+ }
3335
+ /** Sets the global document config.
3336
+ *
3337
+ * Pass in a partial object of the global document config to set.
3338
+ */
3339
+ function setPHDocumentEditorConfig(config) {
3340
+ for (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);
3341
+ }
3342
+ /** Wrapper hook for setting the global app config.
3343
+ *
3344
+ * Automatically sets the global app config when the component mounts.
3345
+ *
3346
+ * Pass in a partial object of the global app config to set.
3347
+ */
3348
+ function useSetPHAppConfig(config) {
3349
+ const [isInitialized, setIsInitialized] = useState(false);
3350
+ useEffect(() => {
3351
+ if (isInitialized) return;
3352
+ setPHAppConfig(config);
3353
+ setIsInitialized(true);
3354
+ }, [config, isInitialized]);
3355
+ }
3356
+ /** Wrapper hook for setting the global document editor config.
3357
+ *
3358
+ * Automatically sets the global document editor config when the component mounts.
3359
+ *
3360
+ * Pass in a partial object of the global document editor config to set.
3361
+ */
3362
+ function useSetPHDocumentEditorConfig(config) {
3363
+ const [isInitialized, setIsInitialized] = useState(false);
3364
+ useEffect(() => {
3365
+ if (isInitialized) return;
3366
+ setPHDocumentEditorConfig(config);
3367
+ setIsInitialized(true);
3368
+ }, [config, isInitialized]);
3369
+ }
3370
+ /** Returns a document of a specific type, throws an error if the found document has a different type */
3371
+ function useDocumentOfType(documentId, documentType) {
3372
+ const [document, dispatch] = useDocumentById(documentId);
3373
+ const documentModelModule = useDocumentModelModuleById(documentType);
3374
+ if (!documentId || !documentType) return [];
3375
+ if (!document) throw new Error(`Document not found: ${documentId}`);
3376
+ if (!documentModelModule) throw new ModuleNotFoundError(documentType);
3377
+ if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3378
+ return [document, dispatch];
3379
+ }
3380
+ const validateDocument = (document) => {
3381
+ const errors = [];
3382
+ if (document.header.documentType !== "powerhouse/document-model") return errors;
3383
+ const doc = document;
3384
+ const specs = doc.state.global.specifications[0];
3385
+ const initialStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {
3386
+ const scope = scopeKey;
3387
+ return [...acc, ...validateInitialState(specs.state[scope].initialValue, scope !== "global").map((err) => ({
3388
+ ...err,
3389
+ message: `${err.message}. Scope: ${scope}`,
3390
+ details: {
3391
+ ...err.details,
3392
+ scope
3393
+ }
3394
+ }))];
3395
+ }, []);
3396
+ const schemaStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {
3397
+ const scope = scopeKey;
3398
+ const isGlobalScope = scope === "global";
3399
+ return [...acc, ...validateStateSchemaName(specs.state[scope].schema, doc.state.global?.name || doc.header.name || "", !isGlobalScope ? scope : "", !isGlobalScope).map((err) => ({
3400
+ ...err,
3401
+ message: `${err.message}. Scope: ${scope}`,
3402
+ details: {
3403
+ ...err.details,
3404
+ scope
3405
+ }
3406
+ }))];
3407
+ }, []);
3408
+ const modulesErrors = validateModules(specs.modules);
3409
+ return [
3410
+ ...initialStateErrors,
3411
+ ...schemaStateErrors,
3412
+ ...modulesErrors
3413
+ ];
3414
+ };
3415
+ function defaultHandleError(error) {
3416
+ console.error(`Failed to export document: ${error.message}`);
3417
+ }
3418
+ function handleDocumentValidation(document) {
3419
+ if (t$2(validateDocument(document), 1)) return false;
3420
+ return true;
3421
+ }
3422
+ function downloadDocument(document, handleError = defaultHandleError) {
3423
+ if (!document) return;
3424
+ if (!handleDocumentValidation(document)) {
3425
+ showPHModal({
3426
+ type: "downloadDocumentWithErrors",
3427
+ documentId: document.header.id
3428
+ });
3429
+ return;
3430
+ }
3431
+ exportFile(document).catch((error) => handleError(normalizeException(error)));
3432
+ }
3433
+ function useDownloadDocument(id) {
3434
+ const [document] = useDocumentById(id);
3435
+ const toast = usePHToast();
3436
+ return () => downloadDocument(document, (error) => toast?.(`Failed to export document: ${error.message}`));
3437
+ }
3438
+ function useFolderById(id) {
3439
+ return useFolderNodesInSelectedDrive()?.find((n) => n.id === id);
3440
+ }
3441
+ function resolveNode(driveId, node) {
3442
+ return node?.id !== driveId ? node : void 0;
3443
+ }
3444
+ function useNodeActions() {
3445
+ const [selectedDrive] = useSelectedDriveSafe();
3446
+ const selectedFolder = useSelectedFolder();
3447
+ const selectedParentFolder = useFolderById(useSelectedNode()?.parentFolder);
3448
+ const selectedDriveId = selectedDrive?.header.id;
3449
+ const drives = useDrives();
3450
+ async function onAddFile(file, parent) {
3451
+ if (!selectedDriveId) return;
3452
+ return addFile(file, selectedDriveId, file.name.replace(/\..+/gim, ""), resolveNode(selectedDriveId, parent)?.id);
3453
+ }
3454
+ async function onAddFolder(name, parent) {
3455
+ if (!selectedDriveId) return;
3456
+ return addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3457
+ }
3458
+ async function onRenameNode(newName, node) {
3459
+ if (!selectedDriveId) return;
3460
+ if (!resolveNode(selectedDriveId, node)) {
3461
+ console.error(`Node ${node.id} not found`);
3462
+ return;
3463
+ }
3464
+ return await renameNode(selectedDriveId, node.id, newName);
3465
+ }
3466
+ async function onCopyNode(src, target) {
3467
+ if (!selectedDriveId) return;
3468
+ const resolvedSrc = resolveNode(selectedDriveId, src);
3469
+ if (!resolvedSrc) {
3470
+ console.error(`Node ${src.id} not found`);
3471
+ return;
3472
+ }
3473
+ await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, target));
3474
+ }
3475
+ async function onMoveNode(src, target) {
3476
+ if (!selectedDriveId) return;
3477
+ const resolvedSrc = resolveNode(selectedDriveId, src);
3478
+ if (!resolvedSrc) {
3479
+ console.error(`Node ${src.id} not found`);
3480
+ return;
3481
+ }
3482
+ const resolvedTarget = resolveNode(selectedDriveId, target);
3483
+ if (!resolvedTarget?.id && !src.parentFolder || resolvedTarget?.id === src.parentFolder) return;
3484
+ await moveNode$1(selectedDriveId, resolvedSrc, resolvedTarget);
3485
+ }
3486
+ async function onDuplicateNode(src) {
3487
+ if (!selectedDriveId) return;
3488
+ const resolvedSrc = resolveNode(selectedDriveId, src);
3489
+ if (!resolvedSrc) {
3490
+ console.error(`Node ${src.id} not found`);
3491
+ return;
3492
+ }
3493
+ await copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder));
3494
+ }
3495
+ async function onAddAndSelectNewFolder(name) {
3496
+ if (!name) return;
3497
+ if (!selectedDriveId) return;
3498
+ const resolvedTarget = resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder);
3499
+ if (!resolvedTarget) return;
3500
+ const newFolder = await onAddFolder(name, resolvedTarget);
3501
+ if (newFolder) setSelectedNode(newFolder);
3502
+ }
3503
+ async function onRenameDriveNodes(newName, nodeId) {
3504
+ if (!drives) return;
3505
+ const drivesWithNode = drives.filter((drive) => drive.state.global.nodes.some((n) => n.id === nodeId));
3506
+ await Promise.all(drivesWithNode.map((drive) => renameDriveNode(drive.header.id, nodeId, newName)));
3507
+ }
3508
+ return {
3509
+ onAddFile,
3510
+ onAddFolder,
3511
+ onRenameNode,
3512
+ onCopyNode,
3513
+ onMoveNode,
3514
+ onDuplicateNode,
3515
+ onAddAndSelectNewFolder,
3516
+ onRenameDriveNodes
3517
+ };
3518
+ }
3519
+ /** Returns a node in the selected drive by id. */
3520
+ function useNodeById(id) {
3521
+ return useNodesInSelectedDrive()?.find((n) => n.id === id);
3522
+ }
3523
+ /** Returns the path to a node in the selected drive */
3524
+ function useNodePathById(id) {
3525
+ const nodes = useNodesInSelectedDrive();
3526
+ if (!nodes) return [];
3527
+ const path = [];
3528
+ let current = nodes.find((n) => n.id === id);
3529
+ while (current) {
3530
+ path.push(current);
3531
+ if (!current.parentFolder) break;
3532
+ current = nodes.find((n) => n.id === current?.parentFolder);
3533
+ }
3534
+ return path.reverse();
3535
+ }
3536
+ /** Returns the path to the currently selected node in the selected drive. */
3537
+ function useSelectedNodePath() {
3538
+ return useNodePathById(useSelectedNode()?.id);
3539
+ }
3540
+ function useNodeParentFolderById(id) {
3541
+ return useFolderById(useNodeById(id)?.parentFolder);
3542
+ }
3543
+ /** Returns the selected document id */
3544
+ function useSelectedDocumentId() {
3545
+ const selectedNode = useSelectedNode();
3546
+ return selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;
3547
+ }
3548
+ /** Returns the selected document. */
3549
+ function useSelectedDocumentSafe() {
3550
+ return useDocumentById(useSelectedDocumentId());
3551
+ }
3552
+ function useSelectedDocumentOfType(documentType) {
3553
+ const documentId = useSelectedDocumentId();
3554
+ if (!documentType) return [];
3555
+ if (!documentId) throw new NoSelectedDocumentError();
3556
+ return useDocumentOfType(documentId, documentType);
3557
+ }
3558
+ const STORED_THEME_KEY = "ph:theme";
3559
+ const UPDATE_STORED_THEME = "ph:updateStoredTheme";
3560
+ const STORED_THEME_UPDATED = "ph:storedThemeUpdated";
3561
+ const SYSTEM_THEME_UPDATED = "ph:systemThemeUpdated";
3562
+ const isServer = typeof window === "undefined";
3563
+ function setTheme(storedTheme) {
3564
+ if (isServer) return;
3565
+ const updateStoredThemeEvent = new CustomEvent(UPDATE_STORED_THEME, { detail: { storedTheme } });
3566
+ window.dispatchEvent(updateStoredThemeEvent);
3567
+ }
3568
+ function getStoredTheme() {
3569
+ if (isServer) return void 0;
3570
+ return localStorage.getItem(STORED_THEME_KEY) ?? void 0;
3571
+ }
3572
+ function getPrefersDarkMediaQuery() {
3573
+ if (isServer) return;
3574
+ return window.matchMedia("(prefers-color-scheme: dark)");
3575
+ }
3576
+ function getPrefersDark() {
3577
+ if (isServer) return false;
3578
+ if (getPrefersDarkMediaQuery()?.matches) return true;
3579
+ return false;
3580
+ }
3581
+ function getSystemTheme() {
3582
+ if (isServer) return "light";
3583
+ if (getPrefersDark()) return "dark";
3584
+ return "light";
3585
+ }
3586
+ function toggleDark(isDark) {
3587
+ if (isServer) return;
3588
+ document.documentElement.classList.toggle("dark", isDark);
3589
+ }
3590
+ function subscribeToStoredTheme(onStoreChange) {
3591
+ if (isServer) return () => {};
3592
+ window.addEventListener(STORED_THEME_UPDATED, onStoreChange);
3593
+ return () => {
3594
+ window.removeEventListener(STORED_THEME_UPDATED, onStoreChange);
3595
+ };
3596
+ }
3597
+ function subscribeToSystemTheme(onStoreChange) {
3598
+ if (isServer) return () => {};
3599
+ window.addEventListener(SYSTEM_THEME_UPDATED, onStoreChange);
3600
+ return () => {
3601
+ window.removeEventListener(SYSTEM_THEME_UPDATED, onStoreChange);
3602
+ };
3603
+ }
3604
+ function useTheme() {
3605
+ const storedTheme = useSyncExternalStore(subscribeToStoredTheme, () => getStoredTheme(), () => "system");
3606
+ const systemTheme = useSyncExternalStore(subscribeToSystemTheme, () => getSystemTheme(), () => "light");
3607
+ const isSystem = storedTheme === void 0 || storedTheme === "system";
3608
+ const theme = isSystem ? systemTheme : storedTheme;
3609
+ const isDark = theme === "dark";
3610
+ useEffect(() => {
3611
+ toggleDark(isDark);
3612
+ }, [isDark]);
3613
+ return {
3614
+ theme,
3615
+ isSystem,
3616
+ setTheme
3617
+ };
3618
+ }
3619
+ const syncStatusToUI = {
3620
+ [SyncStatus.Synced]: "SUCCESS",
3621
+ [SyncStatus.Outgoing]: "SYNCING",
3622
+ [SyncStatus.Incoming]: "SYNCING",
3623
+ [SyncStatus.OutgoingAndIncoming]: "SYNCING",
3624
+ [SyncStatus.Error]: "ERROR"
3625
+ };
3626
+ async function getDrives(reactor) {
3627
+ return (await reactor.find({ type: "powerhouse/document-drive" })).results;
3628
+ }
3629
+ function getSyncStatusSync(documentId, sharingType) {
3630
+ if (sharingType === "LOCAL") return;
3631
+ const syncManager = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;
3632
+ if (!syncManager) return;
3633
+ const status = syncManager.getSyncStatus(documentId);
3634
+ if (status === void 0) return;
3635
+ return syncStatusToUI[status];
3636
+ }
3637
+ function getDocumentGraphqlQuery() {
3638
+ const loc = GetDocumentWithOperationsDocument.loc;
3639
+ if (!loc) throw new Error("GetDocumentWithOperationsDocument is misconfigured, loc is missing.");
3640
+ return loc.source.body;
3641
+ }
3642
+ function buildDocumentSubgraphQuery(identifier, authToken) {
3643
+ const query = getDocumentGraphqlQuery();
3644
+ const variables = { identifier };
3645
+ const headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;
3646
+ const payload = {
3647
+ document: query.trim(),
3648
+ variables: JSON.stringify(variables, null, 2)
3649
+ };
3650
+ if (headers) payload.headers = JSON.stringify(headers);
3651
+ return import_lz_string.compressToEncodedURIComponent(JSON.stringify(payload));
3652
+ }
3653
+ function buildDocumentSubgraphUrl(driveUrl, identifier, authToken) {
3654
+ return `${driveUrl}?explorerURLState=${buildDocumentSubgraphQuery(identifier, authToken)}`;
3655
+ }
3656
+ /**
3657
+ * Hook that returns a function to generate a document's switchboard URL.
3658
+ * Only returns a function for documents in remote drives.
3659
+ * Returns null for local drives or when the document/drive cannot be determined.
3660
+ *
3661
+ * The returned function generates a fresh bearer token and builds the switchboard URL
3662
+ * with authentication when called.
3663
+ *
3664
+ * @param document - The document to create a switchboard URL generator for
3665
+ * @returns An async function that returns the switchboard URL, or null if not applicable
3666
+ */
3667
+ function useGetSwitchboardLink(document) {
3668
+ const [drive] = useSelectedDriveSafe();
3669
+ const remotes = useSyncList();
3670
+ const isRemoteDrive = useMemo(() => {
3671
+ if (!e$4(drive)) return false;
3672
+ return remotes.some((remote) => remote.collectionId === driveCollectionId("main", drive.header.id));
3673
+ }, [remotes, drive]);
3674
+ const remoteUrl = useMemo(() => {
3675
+ if (!e$4(drive)) return null;
3676
+ try {
3677
+ const channelUrl = (remotes.find((remote) => remote.collectionId === driveCollectionId("main", drive.header.id))?.channel)?.config.url;
3678
+ if (typeof channelUrl === "string") return channelUrl;
3679
+ return null;
3680
+ } catch (error) {
3681
+ console.error("Error determining remote URL:", error);
3682
+ return null;
3683
+ }
3684
+ }, [remotes, drive]);
3685
+ const renown = useRenown();
3686
+ const user = useUser();
3687
+ return useMemo(() => {
3688
+ if (!isRemoteDrive || !document?.header.id || !remoteUrl) return null;
3689
+ return async () => {
3690
+ const token = user?.address ? await renown?.getBearerToken({
3691
+ expiresIn: 600,
3692
+ aud: remoteUrl
3693
+ }) : void 0;
3694
+ return buildDocumentSubgraphUrl(remoteUrl, document.header.id, token);
3695
+ };
3696
+ }, [
3697
+ isRemoteDrive,
3698
+ remoteUrl,
3699
+ document,
3700
+ user,
3701
+ renown
3702
+ ]);
3703
+ }
3704
+ function useUserPermissions() {
3705
+ const user = useUser();
3706
+ const allowList = useAllowList();
3707
+ if (!allowList) return {
3708
+ isAllowedToCreateDocuments: true,
3709
+ isAllowedToEditDocuments: true
3710
+ };
3711
+ return {
3712
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
3713
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
3714
+ };
3715
+ }
3716
+ const DEFAULT_DEBOUNCE_DELAY_MS = 200;
3717
+ const DEFAULT_IMMEDIATE_THRESHOLD_MS = 1e3;
3718
+ async function _refreshReactorData(reactor) {
3719
+ setDrives(await getDrives(reactor));
3720
+ }
3721
+ async function _refreshReactorDataClient(reactor) {
3722
+ if (!reactor) return;
3723
+ setDrives((await reactor.find({ type: "powerhouse/document-drive" })).results);
3724
+ }
3725
+ function createDebouncedRefreshReactorData(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {
3726
+ let timeout = null;
3727
+ let lastRefreshTime = 0;
3728
+ return (reactor, immediate = false) => {
3729
+ const now = Date.now();
3730
+ const timeSinceLastRefresh = now - lastRefreshTime;
3731
+ if (timeout !== null) clearTimeout(timeout);
3732
+ if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {
3733
+ lastRefreshTime = now;
3734
+ return _refreshReactorData(reactor);
3735
+ }
3736
+ return new Promise((resolve) => {
3737
+ timeout = setTimeout(() => {
3738
+ lastRefreshTime = Date.now();
3739
+ _refreshReactorData(reactor).then(resolve);
3740
+ }, debounceDelayMs);
3741
+ });
3742
+ };
3743
+ }
3744
+ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {
3745
+ let timeout = null;
3746
+ let lastRefreshTime = 0;
3747
+ return (reactor, immediate = false) => {
3748
+ const now = Date.now();
3749
+ const timeSinceLastRefresh = now - lastRefreshTime;
3750
+ if (timeout !== null) clearTimeout(timeout);
3751
+ if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {
3752
+ lastRefreshTime = now;
3753
+ return _refreshReactorDataClient(reactor);
3754
+ }
3755
+ return new Promise((resolve) => {
3756
+ timeout = setTimeout(() => {
3757
+ lastRefreshTime = Date.now();
3758
+ _refreshReactorDataClient(reactor).then(resolve);
3759
+ }, debounceDelayMs);
3760
+ });
3761
+ };
3762
+ }
3763
+ createDebouncedRefreshReactorData();
3764
+ createDebouncedRefreshReactorDataClient();
3765
+ //#endregion
3766
+ export { e$4 as A, useSelectedDriveSafe as C, useTheme as D, useSetPHDocumentEditorConfig as E, t$5 as M, useDocumentById as N, useUserPermissions as O, useSelectedDriveId as S, useSetPHAppConfig as T, useNodeParentFolderById as _, setSelectedDrive as a, useSelectedDocumentOfType as b, showDeleteNodeModal as c, useDownloadDocument as d, useDragNode as f, useNodeById as g, useNodeActions as h, isFolderNodeKind as i, t$2 as j, e$1 as k, showRevisionHistory as l, useGetSwitchboardLink as m, getSyncStatusSync as n, setSelectedNode as o, useDropNode as p, isFileNodeKind as r, showCreateDocumentModal as s, addFolder as t, useDocumentModelModules as u, useNodesInSelectedDriveOrFolder as v, useSelectedNodePath as w, useSelectedDocumentSafe as x, usePHToast as y };
3767
+
3768
+ //# sourceMappingURL=dist-C1nRM9t2.js.map