@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.7 → 6.2.2-dev.70

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 (103) hide show
  1. package/dist/browser/assets/{entry-Cvoo4_c9.js → entry-BBghrmE1.js} +3 -2
  2. package/dist/browser/assets/{projection-entry-DVec8YRh.js → projection-entry-BtmaPdIp.js} +4 -4
  3. package/dist/browser/{linting-Dn6pXRkK.js → button-CuO8Gh3v.js} +20 -6
  4. package/dist/browser/button-CuO8Gh3v.js.map +1 -0
  5. package/dist/browser/{connect-KEU-HR3o.js → connect-DmCpI0kg.js} +916 -200
  6. package/dist/browser/connect-DmCpI0kg.js.map +1 -0
  7. package/dist/browser/{dist-CXoKspdx.js → dist-B4FWbuEM.js} +10 -2
  8. package/dist/browser/{dist-CXoKspdx.js.map → dist-B4FWbuEM.js.map} +1 -1
  9. package/dist/{node/dist-BeZaEP6S.mjs → browser/dist-BAJ5nRDl.js} +21 -2
  10. package/dist/browser/{dist-D8H48e8N.js.map → dist-BAJ5nRDl.js.map} +1 -1
  11. package/dist/browser/{dist-D5ra2aRj.js → dist-DfoAQf6g.js} +1617 -1293
  12. package/dist/browser/dist-DfoAQf6g.js.map +1 -0
  13. package/dist/browser/{document-drive-IdFV1QXL.js → document-drive-D6XhjHzr.js} +1184 -122
  14. package/dist/browser/document-drive-D6XhjHzr.js.map +1 -0
  15. package/dist/browser/document-models/index.js +1 -1
  16. package/dist/browser/{documents-D4ek7Ubv.js → documents-J_l59mSV.js} +5 -604
  17. package/dist/browser/documents-J_l59mSV.js.map +1 -0
  18. package/dist/browser/editor-C069kNOj.js +25 -0
  19. package/dist/browser/editor-C069kNOj.js.map +1 -0
  20. package/dist/browser/{editor-DiZF3ao3.js → editor-XlOiVjqp.js} +671 -236
  21. package/dist/browser/editor-XlOiVjqp.js.map +1 -0
  22. package/dist/browser/editors/document-model-editor/module.js +1 -1
  23. package/dist/browser/editors/generic-drive-explorer/index.js +5 -5
  24. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  25. package/dist/{node/folder-view-Cy-QxsDg.mjs → browser/folder-view-B4b9Ik-G.js} +73 -46
  26. package/dist/browser/folder-view-B4b9Ik-G.js.map +1 -0
  27. package/dist/browser/{graphql-editor-ZLRO_8Ce.js → graphql-editor-BDze7_wI.js} +8 -7
  28. package/dist/browser/{graphql-editor-ZLRO_8Ce.js.map → graphql-editor-BDze7_wI.js.map} +1 -1
  29. package/dist/browser/{hooks-CORHBNHb.js → hooks-KKcNp2X0.js} +2 -2
  30. package/dist/browser/{hooks-CORHBNHb.js.map → hooks-KKcNp2X0.js.map} +1 -1
  31. package/dist/browser/index.js +378 -9
  32. package/dist/browser/index.js.map +1 -1
  33. package/dist/browser/{json-editor-DBuZ6gN7.js → json-editor-nI61gbA-.js} +4 -4
  34. package/dist/browser/{json-editor-DBuZ6gN7.js.map → json-editor-nI61gbA-.js.map} +1 -1
  35. package/dist/browser/{lib-C-f3izXz.js → lib-CE5V8jW5.js} +13 -4
  36. package/dist/browser/lib-CE5V8jW5.js.map +1 -0
  37. package/dist/browser/printer-CEYr4JOg.js +604 -0
  38. package/dist/browser/printer-CEYr4JOg.js.map +1 -0
  39. package/dist/browser/{schema-context-DY-GEGnY.js → schema-context-ZyeclQwy.js} +2 -2
  40. package/dist/browser/{schema-context-DY-GEGnY.js.map → schema-context-ZyeclQwy.js.map} +1 -1
  41. package/dist/browser/{state-schemas-BjQKM498.js → state-schemas-DvpLHgMU.js} +8 -18
  42. package/dist/browser/state-schemas-DvpLHgMU.js.map +1 -0
  43. package/dist/node/{linting-Dx50GuLN.mjs → button-Da7CxMn7.mjs} +20 -7
  44. package/dist/node/button-Da7CxMn7.mjs.map +1 -0
  45. package/dist/node/{connect-KcYZcy_Z.mjs → connect-BOwTtHRq.mjs} +916 -200
  46. package/dist/node/connect-BOwTtHRq.mjs.map +1 -0
  47. package/dist/node/{dist-DJEK2WVi.mjs → dist-CRrgpr8A.mjs} +1621 -1292
  48. package/dist/node/dist-CRrgpr8A.mjs.map +1 -0
  49. package/dist/{browser/dist-D8H48e8N.js → node/dist-CzYOpeXN.mjs} +21 -2
  50. package/dist/node/{dist-BeZaEP6S.mjs.map → dist-CzYOpeXN.mjs.map} +1 -1
  51. package/dist/node/{dist-fA4EItr0.mjs → dist-DT7jI9ol.mjs} +10 -2
  52. package/dist/node/{dist-fA4EItr0.mjs.map → dist-DT7jI9ol.mjs.map} +1 -1
  53. package/dist/node/{document-drive-C8hbqQ3C.mjs → document-drive-B65n0lIk.mjs} +1184 -122
  54. package/dist/node/document-drive-B65n0lIk.mjs.map +1 -0
  55. package/dist/node/document-models/index.mjs +1 -1
  56. package/dist/node/{documents-BFBPmyw1.mjs → documents-DCf53bzO.mjs} +3 -3
  57. package/dist/node/{documents-BFBPmyw1.mjs.map → documents-DCf53bzO.mjs.map} +1 -1
  58. package/dist/node/{editor-B1KhoF1f.mjs → editor-BGcLm6LA.mjs} +672 -237
  59. package/dist/node/editor-BGcLm6LA.mjs.map +1 -0
  60. package/dist/node/editor-DIiXhhl2.mjs +25 -0
  61. package/dist/node/editor-DIiXhhl2.mjs.map +1 -0
  62. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  63. package/dist/node/editors/generic-drive-explorer/index.mjs +5 -5
  64. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  65. package/dist/{browser/folder-view-DMFqcJhc.js → node/folder-view-DyijTEeD.mjs} +73 -46
  66. package/dist/node/folder-view-DyijTEeD.mjs.map +1 -0
  67. package/dist/node/{graphql-DskHmkMe.mjs → graphql-BfAoPeWM.mjs} +2 -2
  68. package/dist/node/{graphql-DskHmkMe.mjs.map → graphql-BfAoPeWM.mjs.map} +1 -1
  69. package/dist/node/{graphql-editor-C5VLRqEf.mjs → graphql-editor-5YU1uHpd.mjs} +7 -7
  70. package/dist/node/{graphql-editor-C5VLRqEf.mjs.map → graphql-editor-5YU1uHpd.mjs.map} +1 -1
  71. package/dist/node/{hooks-DJrjfVaS.mjs → hooks-D0DcS3MV.mjs} +2 -2
  72. package/dist/node/{hooks-DJrjfVaS.mjs.map → hooks-D0DcS3MV.mjs.map} +1 -1
  73. package/dist/node/index.mjs +378 -9
  74. package/dist/node/index.mjs.map +1 -1
  75. package/dist/node/{json-editor-iI2s9a_4.mjs → json-editor-iuJkZEgS.mjs} +4 -4
  76. package/dist/node/{json-editor-iI2s9a_4.mjs.map → json-editor-iuJkZEgS.mjs.map} +1 -1
  77. package/dist/node/{main-D82dkD7g.mjs → main-B5JSm6Hi.mjs} +15 -6
  78. package/dist/node/main-B5JSm6Hi.mjs.map +1 -0
  79. package/dist/node/{schema-context-CX5ml_9t.mjs → schema-context-DL8jhi_d.mjs} +3 -3
  80. package/dist/node/{schema-context-CX5ml_9t.mjs.map → schema-context-DL8jhi_d.mjs.map} +1 -1
  81. package/dist/node/{state-schemas-Bl7nA8bB.mjs → state-schemas-DHQAxfto.mjs} +10 -20
  82. package/dist/{browser/state-schemas-BjQKM498.js.map → node/state-schemas-DHQAxfto.mjs.map} +1 -1
  83. package/package.json +8 -7
  84. package/dist/browser/connect-KEU-HR3o.js.map +0 -1
  85. package/dist/browser/dist-D5ra2aRj.js.map +0 -1
  86. package/dist/browser/document-drive-IdFV1QXL.js.map +0 -1
  87. package/dist/browser/documents-D4ek7Ubv.js.map +0 -1
  88. package/dist/browser/editor-DiZF3ao3.js.map +0 -1
  89. package/dist/browser/editor-SqNULDP-.js +0 -29
  90. package/dist/browser/editor-SqNULDP-.js.map +0 -1
  91. package/dist/browser/folder-view-DMFqcJhc.js.map +0 -1
  92. package/dist/browser/lib-C-f3izXz.js.map +0 -1
  93. package/dist/browser/linting-Dn6pXRkK.js.map +0 -1
  94. package/dist/node/connect-KcYZcy_Z.mjs.map +0 -1
  95. package/dist/node/dist-DJEK2WVi.mjs.map +0 -1
  96. package/dist/node/document-drive-C8hbqQ3C.mjs.map +0 -1
  97. package/dist/node/editor-B1KhoF1f.mjs.map +0 -1
  98. package/dist/node/editor-yBGEvMGD.mjs +0 -29
  99. package/dist/node/editor-yBGEvMGD.mjs.map +0 -1
  100. package/dist/node/folder-view-Cy-QxsDg.mjs.map +0 -1
  101. package/dist/node/linting-Dx50GuLN.mjs.map +0 -1
  102. package/dist/node/main-D82dkD7g.mjs.map +0 -1
  103. package/dist/node/state-schemas-Bl7nA8bB.mjs.map +0 -1
@@ -1,9 +1,10 @@
1
- import { E as __commonJSMin, j as __toESM, t as capitalCase } from "./dist-fA4EItr0.mjs";
2
- import { B as setName, C as createZip, J as validateModules, X as generateId, Y as validateStateSchemaName, _ as baseLoadFromInputVersioned, a as handleTargetNameCollisions, b as createPresignedHeader, c as moveNode, d as logger, g as baseLoadFromInput, i as generateNodesCopy, j as replayDocumentVersioned, l as updateNode, n as copyNode, o as isFileNode, q as validateInitialState, s as isFolderNode, t as addFolder$1, v as baseSaveToFileHandle, y as buildSignedAction } from "./document-drive-C8hbqQ3C.mjs";
3
- import { a as DriveCollectionId, i as SyncStatus, o as ModuleNotFoundError, t as require_main } from "./main-D82dkD7g.mjs";
4
- import { Children, cloneElement, forwardRef, isValidElement, use, useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
1
+ import { D as __commonJSMin, M as __toESM, t as capitalCase } from "./dist-DT7jI9ol.mjs";
2
+ import { A as createZip, C as baseSaveToFileHandle, D as createPresignedHeader, H as replayDocumentVersioned, S as baseLoadFromInputVersioned, Z as setName, a as handleTargetNameCollisions, at as validateInitialState, ct as generateId, f as logger, i as generateNodesCopy, l as moveNode, n as copyNode, o as isFileNode, ot as validateModules, s as isFolderNode, st as validateStateSchemaName, t as addFolder, u as updateNode, v as assertAuthPreservedOnDuplicate, w as buildSignedAction, x as baseLoadFromInput } from "./document-drive-B65n0lIk.mjs";
3
+ import { a as DriveCollectionId, i as SyncStatus, o as ModuleNotFoundError, t as require_main } from "./main-B5JSm6Hi.mjs";
4
+ import { t as require_graphql } from "./graphql-BfAoPeWM.mjs";
5
+ import { createContext, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
5
6
  import "react/jsx-runtime";
6
- //#region ../reactor-browser/dist/make-ph-event-functions-BHoLPif5.js
7
+ //#region ../reactor-browser/dist/make-ph-event-functions-DBq3iWYn.js
7
8
  const isServer$1 = typeof window === "undefined";
8
9
  function makePHEventFunctions(key) {
9
10
  const setEventName = `ph:set${capitalCase(key)}`;
@@ -51,7 +52,7 @@ function makePHEventFunctions(key) {
51
52
  };
52
53
  }
53
54
  //#endregion
54
- //#region ../reactor-browser/dist/document-by-id-dLYFX-xz.js
55
+ //#region ../reactor-browser/dist/document-by-id-BSZqTN66.js
55
56
  async function queueActions(document, actionOrActions) {
56
57
  if (!document) throw new Error("No document provided");
57
58
  if (!actionOrActions) throw new Error("No actions provided");
@@ -97,12 +98,12 @@ async function uploadOperations(documentId, allOperations, pushOperations, optio
97
98
  logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
98
99
  }
99
100
  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
101
  const renown = window.ph?.renown;
104
102
  if (!renown?.user) return action;
105
103
  if (!action.context?.signer) return action;
104
+ const reactorClient = window.ph?.reactorClientModule?.client;
105
+ if (!reactorClient) return action;
106
+ const reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;
106
107
  const actionSigner = action.context.signer;
107
108
  return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
108
109
  }
@@ -180,6 +181,21 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
180
181
  if (onSuccess && result) onSuccess(result);
181
182
  return result;
182
183
  }
184
+ /**
185
+ * The reactor's `DocumentChangeType` members, typed as the enum so they can be
186
+ * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
187
+ * TypeScript string enum is nominal, so no string literal is assignable to it
188
+ * without one - and the two checks above are what make it safe.
189
+ */
190
+ const DOCUMENT_CHANGE_TYPE = {
191
+ Created: "created",
192
+ Deleted: "deleted",
193
+ Updated: "updated",
194
+ ParentAdded: "parent_added",
195
+ ParentRemoved: "parent_removed",
196
+ ChildAdded: "child_added",
197
+ ChildRemoved: "child_removed"
198
+ };
183
199
  const documentEventFunctions = makePHEventFunctions("documentCache");
184
200
  /** Returns all documents in the reactor. */
185
201
  const useDocumentCache = documentEventFunctions.useValue;
@@ -225,9 +241,27 @@ function useDocumentById(id) {
225
241
  const [, dispatch] = useDispatch(document);
226
242
  return [document, dispatch];
227
243
  }
244
+ Error;
245
+ require_graphql();
246
+ JSON;
228
247
  //#endregion
229
- //#region ../reactor-browser/dist/client-_Gh2Uf0E.js
248
+ //#region ../reactor-browser/dist/client-DB8gP4hz.js
230
249
  var import_main = require_main();
250
+ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
251
+ DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
252
+ DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
253
+ DocumentChangeType["Created"] = "CREATED";
254
+ DocumentChangeType["Deleted"] = "DELETED";
255
+ DocumentChangeType["ParentAdded"] = "PARENT_ADDED";
256
+ DocumentChangeType["ParentRemoved"] = "PARENT_REMOVED";
257
+ DocumentChangeType["Updated"] = "UPDATED";
258
+ return DocumentChangeType;
259
+ }({});
260
+ let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
261
+ PropagationMode["Cascade"] = "CASCADE";
262
+ PropagationMode["Orphan"] = "ORPHAN";
263
+ return PropagationMode;
264
+ }({});
231
265
  const PhDocumentFieldsFragmentDoc = import_main.gql`
232
266
  fragment PHDocumentFields on PHDocument {
233
267
  id
@@ -288,6 +322,7 @@ const GetDocumentWithOperationsDocument = import_main.gql`
288
322
  hash
289
323
  skip
290
324
  error
325
+ deniedReason
291
326
  id
292
327
  action {
293
328
  id
@@ -400,6 +435,7 @@ const GetDocumentOperationsDocument = import_main.gql`
400
435
  hash
401
436
  skip
402
437
  error
438
+ deniedReason
403
439
  id
404
440
  action {
405
441
  id
@@ -442,6 +478,28 @@ import_main.gql`
442
478
  }
443
479
  }
444
480
  `;
481
+ import_main.gql`
482
+ query EvaluateActions(
483
+ $documentIdentifier: String!
484
+ $branch: String
485
+ $candidates: [ActionCandidateInput!]!
486
+ ) {
487
+ evaluateActions(
488
+ documentIdentifier: $documentIdentifier
489
+ branch: $branch
490
+ candidates: $candidates
491
+ ) {
492
+ evaluations {
493
+ decision
494
+ reason
495
+ }
496
+ allAllowed
497
+ anyAllowed
498
+ allDenied
499
+ anyDenied
500
+ }
501
+ }
502
+ `;
445
503
  import_main.gql`
446
504
  mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
447
505
  createDocument(document: $document, parentIdentifier: $parentIdentifier) {
@@ -467,13 +525,13 @@ import_main.gql`
467
525
  import_main.gql`
468
526
  mutation MutateDocument(
469
527
  $documentIdentifier: String!
470
- $actions: [JSONObject!]!
471
- $view: ViewFilterInput
528
+ $actions: [ActionInput!]!
529
+ $branch: String
472
530
  ) {
473
- mutateDocument(
531
+ mutateDocument: execute(
474
532
  documentIdentifier: $documentIdentifier
475
533
  actions: $actions
476
- view: $view
534
+ branch: $branch
477
535
  ) {
478
536
  ...PHDocumentFields
479
537
  }
@@ -483,14 +541,21 @@ import_main.gql`
483
541
  import_main.gql`
484
542
  mutation MutateDocumentAsync(
485
543
  $documentIdentifier: String!
486
- $actions: [JSONObject!]!
487
- $view: ViewFilterInput
544
+ $actions: [ActionInput!]!
545
+ $branch: String
488
546
  ) {
489
- mutateDocumentAsync(
547
+ mutateDocumentAsync: executeAsync(
490
548
  documentIdentifier: $documentIdentifier
491
549
  actions: $actions
492
- view: $view
493
- )
550
+ branch: $branch
551
+ ) {
552
+ id
553
+ status
554
+ result
555
+ error
556
+ createdAt
557
+ completedAt
558
+ }
494
559
  }
495
560
  `;
496
561
  import_main.gql`
@@ -650,6 +715,7 @@ import_main.gql`
650
715
  hash
651
716
  skip
652
717
  error
718
+ deniedReason
653
719
  id
654
720
  action {
655
721
  id
@@ -692,6 +758,7 @@ import_main.gql`
692
758
  deadLetters {
693
759
  documentId
694
760
  error
761
+ errorType
695
762
  }
696
763
  hasMore
697
764
  }
@@ -738,51 +805,65 @@ function extractQueryParts(doc, fallbackBody) {
738
805
  extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
739
806
  extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
740
807
  //#endregion
741
- //#region ../reactor-browser/dist/renown-D-1c_Bvx.js
808
+ //#region ../reactor-browser/dist/renown-6w_ImTvm.js
742
809
  const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
810
+ const RenownInitialUserContext = createContext({ state: "unknown" });
811
+ /** First-render auth as a three-state value; use this to skip a spinner when anonymous. */
812
+ function useRenownInitialAuth() {
813
+ return useContext(RenownInitialUserContext);
814
+ }
815
+ function useRenownInitialUser() {
816
+ const initial = useRenownInitialAuth();
817
+ return initial.state === "authenticated" ? initial.user : void 0;
818
+ }
743
819
  const renownEventFunctions = makePHEventFunctions("renown");
744
820
  renownEventFunctions.addEventHandler;
745
821
  /** Returns the renown instance */
746
822
  const useRenown = renownEventFunctions.useValue;
747
823
  renownEventFunctions.setValue;
824
+ function jsonEqual(a, b) {
825
+ if (a === b) return true;
826
+ if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false;
827
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
828
+ const ra = a;
829
+ const rb = b;
830
+ const keys = Object.keys(ra).filter((k) => ra[k] !== void 0);
831
+ if (keys.length !== Object.keys(rb).filter((k) => rb[k] !== void 0).length) return false;
832
+ return keys.every((k) => jsonEqual(ra[k], rb[k]));
833
+ }
834
+ function sameUser(a, b) {
835
+ return jsonEqual(a, b);
836
+ }
837
+ function resolveInstanceUser(instance, seed) {
838
+ const restored = instance.user;
839
+ if (restored) return sameUser(seed, restored) ? seed : restored;
840
+ return instance.status === "initial" ? void 0 : seed;
841
+ }
748
842
  /** Returns the current user from the renown instance, subscribing to user events */
749
843
  function useUser() {
750
844
  const renown = useRenown();
751
- const [user, setUser] = useState(renown?.user);
845
+ const initialUser = useRenownInitialUser();
846
+ const instance = renown ? renown : void 0;
847
+ const [tracked, setTracked] = useState(() => ({
848
+ instance,
849
+ user: instance ? resolveInstanceUser(instance, initialUser) : initialUser
850
+ }));
851
+ const current = tracked.instance === instance ? tracked : {
852
+ instance,
853
+ user: instance ? resolveInstanceUser(instance, tracked.user ?? initialUser) : tracked.user
854
+ };
752
855
  useEffect(() => {
753
- setUser(renown?.user);
754
- if (!renown) return;
755
- return renown.on("user", setUser);
756
- }, [renown]);
757
- return user;
758
- }
759
- function mergeProps(parentProps, childProps) {
760
- const merged = { ...parentProps };
761
- for (const key of Object.keys(childProps)) {
762
- const parentValue = parentProps[key];
763
- const childValue = childProps[key];
764
- if (key === "style") merged[key] = {
765
- ...parentValue,
766
- ...childValue
767
- };
768
- else if (key === "className") merged[key] = [parentValue, childValue].filter(Boolean).join(" ");
769
- else if (typeof parentValue === "function" && typeof childValue === "function") merged[key] = (...args) => {
770
- childValue(...args);
771
- parentValue(...args);
772
- };
773
- else if (childValue !== void 0) merged[key] = childValue;
774
- }
775
- return merged;
856
+ if (current !== tracked) setTracked(current);
857
+ }, [current, tracked]);
858
+ useEffect(() => {
859
+ if (!instance) return;
860
+ return instance.on("user", (user) => setTracked((prev) => ({
861
+ instance,
862
+ user: sameUser(prev.user, user) ? prev.user : user
863
+ })));
864
+ }, [instance]);
865
+ return instance ? current.user : initialUser ?? current.user;
776
866
  }
777
- const Slot = forwardRef(({ children, ...props }, ref) => {
778
- const child = Children.only(children);
779
- if (!isValidElement(child)) return null;
780
- const childElement = child;
781
- const mergedProps = mergeProps(props, childElement.props);
782
- if (ref) mergedProps.ref = ref;
783
- return cloneElement(childElement, mergedProps);
784
- });
785
- Slot.displayName = "Slot";
786
867
  //#endregion
787
868
  //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
788
869
  function e$8(e, t, n) {
@@ -907,6 +988,32 @@ function e(e) {
907
988
  let t = !1, n;
908
989
  return () => (t ||= (n = e(), !0), n);
909
990
  }
991
+ var CloseCode = /* @__PURE__ */ ((CloseCode2) => {
992
+ CloseCode2[CloseCode2["InternalServerError"] = 4500] = "InternalServerError";
993
+ CloseCode2[CloseCode2["InternalClientError"] = 4005] = "InternalClientError";
994
+ CloseCode2[CloseCode2["BadRequest"] = 4400] = "BadRequest";
995
+ CloseCode2[CloseCode2["BadResponse"] = 4004] = "BadResponse";
996
+ CloseCode2[CloseCode2["Unauthorized"] = 4401] = "Unauthorized";
997
+ CloseCode2[CloseCode2["Forbidden"] = 4403] = "Forbidden";
998
+ CloseCode2[CloseCode2["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
999
+ CloseCode2[CloseCode2["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
1000
+ CloseCode2[CloseCode2["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
1001
+ CloseCode2[CloseCode2["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
1002
+ CloseCode2[CloseCode2["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
1003
+ return CloseCode2;
1004
+ })(CloseCode || {});
1005
+ var MessageType = /* @__PURE__ */ ((MessageType2) => {
1006
+ MessageType2["ConnectionInit"] = "connection_init";
1007
+ MessageType2["ConnectionAck"] = "connection_ack";
1008
+ MessageType2["Ping"] = "ping";
1009
+ MessageType2["Pong"] = "pong";
1010
+ MessageType2["Subscribe"] = "subscribe";
1011
+ MessageType2["Next"] = "next";
1012
+ MessageType2["Error"] = "error";
1013
+ MessageType2["Complete"] = "complete";
1014
+ return MessageType2;
1015
+ })(MessageType || {});
1016
+ Error;
910
1017
  //#endregion
911
1018
  //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
912
1019
  let base64;
@@ -1694,1065 +1801,518 @@ slug.setLocale = function(locale) {
1694
1801
  defaultLocale = locales[locale] || {};
1695
1802
  };
1696
1803
  //#endregion
1697
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
1698
- const normalizeDescriptors = (error) => {
1699
- CORE_ERROR_PROPS.forEach((propName) => {
1700
- normalizeDescriptor(error, propName);
1701
- });
1702
- };
1703
- const CORE_ERROR_PROPS = [
1704
- "name",
1705
- "message",
1706
- "stack",
1707
- "cause",
1708
- "errors"
1709
- ];
1710
- const normalizeDescriptor = (error, propName) => {
1711
- const descriptor = getDescriptor(error, propName);
1712
- if (descriptor === void 0) return;
1713
- if (isReadonlyGetter(descriptor)) {
1714
- setErrorProperty(error, propName, error[propName]);
1715
- return;
1804
+ //#region ../reactor-browser/dist/document-operations-DQfMZpj8.js
1805
+ var DocumentModelNotFoundError = class extends Error {
1806
+ documentType;
1807
+ name = "DocumentModelNotFoundError";
1808
+ constructor(documentType) {
1809
+ super(`Document model module for type ${documentType} not found`);
1810
+ this.documentType = documentType;
1716
1811
  }
1717
- if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
1718
- };
1719
- const getDescriptor = (value, propName) => {
1720
- const descriptor = Object.getOwnPropertyDescriptor(value, propName);
1721
- if (descriptor !== void 0) return descriptor;
1722
- const prototype = Object.getPrototypeOf(value);
1723
- return prototype === null ? void 0 : getDescriptor(prototype, propName);
1724
- };
1725
- const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
1726
- const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
1727
- const setErrorProperty = (error, propName, value) => {
1728
- setErrorDescriptor(error, propName, { value });
1729
- };
1730
- const setErrorDescriptor = (error, propName, descriptor) => {
1731
- Object.defineProperty(error, propName, {
1732
- ...descriptor,
1733
- ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
1734
- enumerable: false,
1735
- configurable: true
1736
- });
1737
- };
1738
- //#endregion
1739
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
1740
- const normalizeAggregate = (error, recurse) => {
1741
- if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
1742
- else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
1743
- else if (error.errors !== void 0) deleteAggregateErrors(error);
1744
- };
1745
- const isDefined = (error) => error !== void 0;
1746
- const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
1747
- const deleteAggregateErrors = (error) => {
1748
- delete error.errors;
1749
- if (error.errors !== void 0) setErrorProperty(error, "errors", []);
1750
- };
1751
- //#endregion
1752
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
1753
- const normalizeCause = (error, recurse) => {
1754
- if (!("cause" in error)) return;
1755
- const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
1756
- if (cause === void 0) delete error.cause;
1757
- else setErrorProperty(error, "cause", cause);
1758
- };
1759
- //#endregion
1760
- //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
1761
- const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
1762
- const isInstanceOfError = (value) => {
1763
- try {
1764
- return value instanceof Error;
1765
- } catch {
1766
- return false;
1812
+ static isError(error) {
1813
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
1767
1814
  }
1768
1815
  };
1769
- const hasErrorTag = (value) => {
1770
- try {
1771
- return ERROR_TAGS.has(Object.prototype.toString.call(value));
1772
- } catch {
1773
- return false;
1816
+ var DocumentTypeMismatchError = class extends Error {
1817
+ constructor(documentId, expectedType, actualType) {
1818
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
1774
1819
  }
1775
1820
  };
1776
- const ERROR_TAGS = new Set([
1777
- "[object Error]",
1778
- "[object DOMException]",
1779
- "[object DOMError]",
1780
- "[object Exception]"
1781
- ]);
1782
- //#endregion
1783
- //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
1784
- function isPlainObject(value) {
1785
- if (typeof value !== "object" || value === null) return false;
1786
- const prototype = Object.getPrototypeOf(value);
1787
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
1788
- }
1789
- //#endregion
1790
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
1791
- const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
1792
- const isNonConfigurableProp = (error, propName) => {
1793
- const descriptor = Object.getOwnPropertyDescriptor(error, propName);
1794
- return descriptor !== void 0 && !descriptor.configurable;
1795
- };
1796
- const isThrowingProp = (error, propName) => {
1797
- try {
1798
- error[propName];
1799
- return false;
1800
- } catch {
1801
- return true;
1821
+ var NoSelectedDocumentError = class extends Error {
1822
+ constructor() {
1823
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
1802
1824
  }
1803
1825
  };
1804
- //#endregion
1805
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
1806
- const setStack = (error) => {
1807
- setErrorProperty(error, "stack", getStack(error.message, error.name));
1808
- };
1809
- const getStack = (message = "", name = "Error") => {
1810
- const { stack } = new (getErrorClass(name))(message);
1811
- return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
1812
- };
1813
- const getErrorClass = (name) => {
1814
- const descriptor = {
1815
- value: name,
1816
- enumerable: false,
1817
- writable: true,
1818
- configurable: true
1826
+ const modalEventFunctions = makePHEventFunctions("modal");
1827
+ modalEventFunctions.useValue;
1828
+ /** Sets the current modal */
1829
+ const setPHModal = modalEventFunctions.setValue;
1830
+ modalEventFunctions.addEventHandler;
1831
+ /** Shows a modal */
1832
+ function showPHModal(modal) {
1833
+ setPHModal(modal);
1834
+ }
1835
+ /** Shows the delete node modal */
1836
+ function showDeleteNodeModal(nodeOrId) {
1837
+ setPHModal({
1838
+ type: "deleteItem",
1839
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
1840
+ });
1841
+ }
1842
+ function getUserPermissions() {
1843
+ const user = window.ph?.renown?.user;
1844
+ const allowList = window.ph?.allowList;
1845
+ if (!allowList) return {
1846
+ isAllowedToCreateDocuments: true,
1847
+ isAllowedToEditDocuments: true
1819
1848
  };
1820
- const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
1821
- Object.defineProperty(StackError.prototype, "name", descriptor);
1822
- return StackError;
1823
- };
1824
- //#endregion
1825
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
1826
- const copyObject = (object) => {
1827
- const objectCopy = {};
1828
- for (const propName of getPropsToCopy(object)) try {
1829
- const value = object[propName];
1830
- const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
1831
- Object.defineProperty(objectCopy, propName, {
1832
- value,
1833
- enumerable,
1834
- configurable,
1835
- writable
1836
- });
1837
- } catch {}
1838
- return objectCopy;
1839
- };
1840
- const getPropsToCopy = (object) => {
1841
- const propNames = getOwnKeys(object);
1842
- for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
1843
- return propNames;
1844
- };
1845
- const getOwnKeys = (object) => {
1849
+ return {
1850
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
1851
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
1852
+ };
1853
+ }
1854
+ const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
1855
+ async function downloadFile(document, fileName) {
1846
1856
  try {
1847
- return Reflect.ownKeys(object);
1848
- } catch {
1849
- return [];
1857
+ const data = await createZip(document);
1858
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
1859
+ const link = window.document.createElement("a");
1860
+ link.style.display = "none";
1861
+ link.href = URL.createObjectURL(blob);
1862
+ link.download = fileName;
1863
+ window.document.body.appendChild(link);
1864
+ link.click();
1865
+ window.document.body.removeChild(link);
1866
+ } catch (e) {
1867
+ logger.error(e instanceof Error ? e.message : String(e));
1850
1868
  }
1851
- };
1852
- const isInheritedProp = (object, propName) => {
1853
- try {
1854
- return propName in object && !Object.hasOwn(object, propName);
1855
- } catch {
1856
- return false;
1869
+ }
1870
+ async function getDocumentExtension(document) {
1871
+ const documentType = document.header.documentType;
1872
+ let rawExtension;
1873
+ if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
1874
+ else {
1875
+ const reactorClient = window.ph?.reactorClientModule?.client;
1876
+ if (reactorClient) {
1877
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
1878
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
1879
+ }
1857
1880
  }
1858
- };
1859
- //#endregion
1860
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
1861
- const objectifyError = (object) => {
1862
- const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
1863
- const messageA = getMessage(message, objectA);
1864
- const error = newError(name, messageA);
1865
- if (message === messageA) assignObjectProps(error, objectA);
1866
- Object.entries({
1867
- name,
1868
- stack,
1869
- cause,
1870
- errors
1871
- }).forEach(([propName, propValue]) => {
1872
- setNewErrorProperty(error, propName, propValue);
1873
- });
1874
- if (stack === void 0) setStack(error);
1875
- return error;
1876
- };
1877
- const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
1878
- const safeJsonStringify = (object) => {
1879
- try {
1880
- return JSON.stringify(object);
1881
- } catch {
1882
- return safeStringify(object);
1881
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
1882
+ }
1883
+ /**
1884
+ * Fetches all operations for a document using cursor-based pagination.
1885
+ * The reactor client handles multi-scope cursors transparently via
1886
+ * composite cursors, so all scopes are fetched in a single paginated stream.
1887
+ */
1888
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
1889
+ const scopes = Object.keys(document.state);
1890
+ const operations = {};
1891
+ for (const scope of scopes) operations[scope] = [];
1892
+ let cursor = "";
1893
+ do {
1894
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
1895
+ cursor,
1896
+ limit: pageSize
1897
+ });
1898
+ for (const op of page.results) {
1899
+ const scope = op.action.scope ?? "global";
1900
+ if (operations[scope]) operations[scope].push(op);
1901
+ }
1902
+ cursor = page.nextCursor ?? "";
1903
+ } while (cursor);
1904
+ return operations;
1905
+ }
1906
+ function extractInitialState(documentScopeOps) {
1907
+ const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
1908
+ if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
1909
+ const input = upgradeOp.action.input;
1910
+ const initialState = input.initialState ?? input.state;
1911
+ if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
1912
+ return initialState;
1913
+ }
1914
+ function filterDomainOperations(operations) {
1915
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
1916
+ }
1917
+ function countOperations(operations) {
1918
+ let total = 0;
1919
+ for (const ops of Object.values(operations)) total += ops?.length ?? 0;
1920
+ return total;
1921
+ }
1922
+ /**
1923
+ * Split an imported document's domain operations at its mid-history upgrade
1924
+ * boundaries, so the caller can re-dispatch each upgrade between segments.
1925
+ *
1926
+ * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
1927
+ * path and must not be repeated. A later upgrade must be: it is where the
1928
+ * reducer version changes, and dropping it replays everything after it through
1929
+ * the module the document was created with.
1930
+ */
1931
+ function splitAtUpgradeBoundaries(operations) {
1932
+ const upgrades = (operations.document ?? []).filter((op) => op.action.type === "UPGRADE_DOCUMENT").filter((op) => op.action.input.fromVersion > 0).sort((a, b) => a.index - b.index);
1933
+ const domain = filterDomainOperations(operations);
1934
+ if (upgrades.length === 0) return [{ operations: domain }];
1935
+ const segments = [];
1936
+ const consumed = /* @__PURE__ */ new Map();
1937
+ const take = (until) => {
1938
+ const slice = {};
1939
+ for (const [scope, ops] of Object.entries(domain)) {
1940
+ if (!ops) continue;
1941
+ const from = consumed.get(scope) ?? 0;
1942
+ const stop = Math.max(from, until(scope, ops));
1943
+ const chunk = ops.slice(from, stop);
1944
+ if (chunk.length > 0) slice[scope] = chunk;
1945
+ consumed.set(scope, stop);
1946
+ }
1947
+ return slice;
1948
+ };
1949
+ for (const upgrade of upgrades) {
1950
+ const input = upgrade.action.input;
1951
+ const slice = take((scope, ops) => boundary(upgrade, scope, ops));
1952
+ segments.push({
1953
+ operations: slice,
1954
+ upgradeTo: input.toVersion
1955
+ });
1883
1956
  }
1884
- };
1885
- const safeStringify = (object) => {
1886
- try {
1887
- return String(object);
1888
- } catch {
1889
- return "Invalid error";
1957
+ const tail = take((_scope, ops) => ops.length);
1958
+ if (countOperations(tail) > 0) segments.push({ operations: tail });
1959
+ return segments;
1960
+ }
1961
+ /**
1962
+ * How many of a scope's operations precede an upgrade. Must stay identical to
1963
+ * the boundary computation in `replayDocumentVersioned` — snapshots compare
1964
+ * against operation indices, not array positions, and the timestamp fallback
1965
+ * excludes the upgrade's own instant.
1966
+ */
1967
+ function boundary(upgrade, scope, ops) {
1968
+ const snapshot = upgrade.action.input.revision;
1969
+ if (snapshot !== void 0) {
1970
+ const revision = snapshot[scope] ?? 0;
1971
+ let count = 0;
1972
+ for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
1973
+ return count;
1890
1974
  }
1891
- };
1892
- const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
1893
- const MESSAGE_MAX_SIZE = 1e3;
1894
- const newError = (name, message) => {
1895
- if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
1896
- if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
1897
- return new Error(message);
1898
- };
1899
- const NATIVE_ERRORS = {
1900
- Error,
1901
- ReferenceError,
1902
- TypeError,
1903
- SyntaxError,
1904
- RangeError,
1905
- URIError,
1906
- EvalError
1907
- };
1908
- const assignObjectProps = (error, object) => {
1909
- for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
1910
- };
1911
- const setNewErrorProperty = (error, propName, propValue) => {
1912
- if (propValue !== void 0) setErrorProperty(error, propName, propValue);
1913
- };
1914
- //#endregion
1915
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
1916
- const stringifyError = (value) => {
1975
+ for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
1976
+ return ops.length;
1977
+ }
1978
+ async function exportFile(document, suggestedName) {
1979
+ const reactorClient = window.ph?.reactorClient;
1980
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1981
+ const operations = await fetchDocumentOperations(reactorClient, document);
1982
+ const initialState = extractInitialState(operations["document"] ?? []);
1983
+ const documentWithOps = {
1984
+ ...document,
1985
+ operations,
1986
+ initialState
1987
+ };
1988
+ const extension = await getDocumentExtension(documentWithOps);
1989
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
1990
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
1991
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
1917
1992
  try {
1918
- const error = new Error(String(value));
1919
- setStack(error);
1920
- return error;
1921
- } catch (error_) {
1922
- return error_;
1993
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
1994
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
1995
+ return fileHandle;
1996
+ } catch (e) {
1997
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
1923
1998
  }
1924
- };
1925
- //#endregion
1926
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
1927
- const { toString: objectToString } = Object.prototype;
1928
- const createError = (value) => {
1929
- if (isErrorPlainObj(value)) return objectifyError(value);
1930
- if (!isErrorInstance(value)) return stringifyError(value);
1931
- if (isInvalidError(value)) return objectifyError(value);
1932
- return value;
1933
- };
1934
- const isErrorPlainObj = (value) => {
1999
+ }
2000
+ /**
2001
+ * Loads a document file and replays it with version-aware reducers from the registry.
2002
+ * Falls back to single-version legacy replay when no upgrade manifest is registered for
2003
+ * the document type.
2004
+ */
2005
+ async function loadFile(path) {
2006
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2007
+ const reactorClient = window.ph?.reactorClientModule?.client;
2008
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2009
+ const documentType = baseDocument.header.documentType;
2010
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2011
+ const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
2012
+ if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
2013
+ const reducers = {};
2014
+ for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
2015
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2016
+ let upgradeManifest;
2017
+ if (registry) try {
2018
+ upgradeManifest = registry.getUpgradeManifest(documentType);
2019
+ } catch {}
2020
+ return baseLoadFromInputVersioned(path, {
2021
+ reducers,
2022
+ upgradeManifest
2023
+ });
2024
+ }
2025
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
2026
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2027
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2028
+ const reactorClient = window.ph?.reactorClientModule?.client;
2029
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2030
+ let documentModelModule;
2031
+ if (documentModelVersion !== void 0) {
2032
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2033
+ const module = documentModelModules.find((m) => m.documentModel.global.id === documentType && (m.version ?? 1) === documentModelVersion);
2034
+ if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
2035
+ documentModelModule = module;
2036
+ } else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2037
+ const newDocument = document ?? documentModelModule.utils.createDocument();
2038
+ if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
2039
+ newDocument.header.name = name;
2040
+ if (preferredEditor) newDocument.header.meta = {
2041
+ ...newDocument.header.meta,
2042
+ preferredEditor
2043
+ };
2044
+ let newDoc;
1935
2045
  try {
1936
- return isPlainObject(value);
1937
- } catch {
1938
- return false;
2046
+ newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2047
+ } catch (e) {
2048
+ logger.error("Error adding document: @error", e);
2049
+ throw new Error("There was an error adding document", { cause: e });
1939
2050
  }
1940
- };
1941
- const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
1942
- const isProxy = (value) => {
2051
+ return {
2052
+ id: newDoc.header.id,
2053
+ name: newDoc.header.name,
2054
+ documentType,
2055
+ parentFolder: parentFolder ?? null,
2056
+ kind: "file"
2057
+ };
2058
+ }
2059
+ async function addFile(file, driveId, name, parentFolder) {
2060
+ logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2061
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2062
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2063
+ const document = await loadFile(file);
2064
+ let duplicateId = false;
2065
+ const reactorClient = window.ph?.reactorClient;
2066
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1943
2067
  try {
1944
- return objectToString.call(value) === "[object Object]";
1945
- } catch {
1946
- return true;
2068
+ await reactorClient.get(document.header.id);
2069
+ duplicateId = true;
2070
+ } catch {}
2071
+ const documentId = duplicateId ? generateId() : document.header.id;
2072
+ const header = createPresignedHeader(documentId, document.header.documentType);
2073
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2074
+ header.meta = document.header.meta;
2075
+ header.name = name || document.header.name;
2076
+ const initialDocument = {
2077
+ ...document,
2078
+ header,
2079
+ state: document.initialState,
2080
+ operations: Object.keys(document.operations).reduce((acc, key) => {
2081
+ acc[key] = [];
2082
+ return acc;
2083
+ }, {})
2084
+ };
2085
+ await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2086
+ for (const segment of splitAtUpgradeBoundaries(document.operations)) {
2087
+ await uploadOperations(documentId, segment.operations, queueOperations);
2088
+ if (segment.upgradeTo !== void 0) await upgradeDocument(documentId, segment.upgradeTo);
1947
2089
  }
1948
- };
1949
- const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
1950
- //#endregion
1951
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
1952
- const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
1953
- const recurseException = (error, parents, shallow) => {
1954
- if (parents.includes(error)) return;
1955
- const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
1956
- const errorA = createError(error);
1957
- normalizeProps(errorA, recurse);
1958
- return errorA;
1959
- };
1960
- const identity = (error) => error;
1961
- const normalizeProps = (error, recurse) => {
1962
- normalizeName(error);
1963
- normalizeMessage(error);
1964
- normalizeStack(error);
1965
- normalizeCause(error, recurse);
1966
- normalizeAggregate(error, recurse);
1967
- normalizeDescriptors(error);
1968
- };
1969
- const normalizeName = (error) => {
1970
- if (isDefinedString(error.name)) return;
1971
- const prototypeName = Object.getPrototypeOf(error).name;
1972
- setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
1973
- };
1974
- const normalizeMessage = (error) => {
1975
- if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
1976
- };
1977
- const normalizeStack = (error) => {
1978
- if (!isDefinedString(error.stack)) setStack(error);
1979
- };
1980
- const isDefinedString = (value) => typeof value === "string" && value !== "";
1981
- //#endregion
1982
- //#region ../reactor-browser/dist/index.js
1983
- var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1984
- var LZString = (function() {
1985
- var f = String.fromCharCode;
1986
- var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
1987
- var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
1988
- var baseReverseDic = {};
1989
- function getBaseValue(alphabet, character) {
1990
- if (!baseReverseDic[alphabet]) {
1991
- baseReverseDic[alphabet] = {};
1992
- for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
1993
- }
1994
- return baseReverseDic[alphabet][character];
2090
+ }
2091
+ async function addFolder$1(driveId, name, parentFolder) {
2092
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2093
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2094
+ const reactorClient = window.ph?.reactorClient;
2095
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2096
+ await reactorClient.get(driveId);
2097
+ const folderId = generateId();
2098
+ const node = (await reactorClient.execute(driveId, "main", [addFolder({
2099
+ id: folderId,
2100
+ name,
2101
+ parentFolder
2102
+ })])).state.global.nodes.find((node) => node.id === folderId);
2103
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2104
+ return node;
2105
+ }
2106
+ async function renameNode(driveId, nodeId, name) {
2107
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2108
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2109
+ const reactorClient = window.ph?.reactorClient;
2110
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2111
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2112
+ const node = (await reactorClient.execute(driveId, "main", [updateNode({
2113
+ id: nodeId,
2114
+ name
2115
+ })])).state.global.nodes.find((n) => n.id === nodeId);
2116
+ if (!node) throw new Error("There was an error renaming node in the drive");
2117
+ return node;
2118
+ }
2119
+ async function renameDriveNode(driveId, nodeId, name) {
2120
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2121
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2122
+ const reactorClient = window.ph?.reactorClient;
2123
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2124
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2125
+ await reactorClient.execute(driveId, "main", [updateNode({
2126
+ id: nodeId,
2127
+ name
2128
+ })]);
2129
+ return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2130
+ }
2131
+ async function moveNodeById(args) {
2132
+ const { driveId, srcId, targetId } = args;
2133
+ if (!driveId || !srcId) return;
2134
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2135
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2136
+ const reactorClient = window.ph?.reactorClient;
2137
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2138
+ const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2139
+ if (t(targetParentFolder, srcId)) return;
2140
+ return await reactorClient.execute(driveId, "main", [moveNode({
2141
+ srcFolder: srcId,
2142
+ targetParentFolder
2143
+ })]);
2144
+ }
2145
+ async function moveNode$1(driveId, src, target) {
2146
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2147
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2148
+ const reactorClient = window.ph?.reactorClient;
2149
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2150
+ return await reactorClient.execute(driveId, "main", [moveNode({
2151
+ srcFolder: src.id,
2152
+ targetParentFolder: target?.id
2153
+ })]);
2154
+ }
2155
+ /**
2156
+ * Duplicates a document under a new id using version-aware replay.
2157
+ * Falls back gracefully when no upgrade manifest is registered for the document type.
2158
+ */
2159
+ async function _duplicateDocument(reactor, document, newId = generateId()) {
2160
+ const documentType = document.header.documentType;
2161
+ const { results: allModules } = await reactor.getDocumentModelModules();
2162
+ const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2163
+ const reducers = {};
2164
+ for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2165
+ if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2166
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2167
+ let upgradeManifest;
2168
+ if (registry) try {
2169
+ upgradeManifest = registry.getUpgradeManifest(documentType);
2170
+ } catch {}
2171
+ const config = {
2172
+ reducers,
2173
+ upgradeManifest
2174
+ };
2175
+ const header = createPresignedHeader(newId, documentType);
2176
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2177
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2178
+ return duplicated;
2179
+ }
2180
+ async function copyNode$1(driveId, src, target) {
2181
+ const reactor = window.ph?.reactorClientModule?.client;
2182
+ if (!reactor) return;
2183
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2184
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2185
+ const drive = await reactor.get(driveId);
2186
+ const copyNodesInput = generateNodesCopy({
2187
+ srcId: src.id,
2188
+ targetParentFolder: target?.id,
2189
+ targetName: src.name
2190
+ }, () => generateId(), drive.state.global.nodes);
2191
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
2192
+ for (const copyNodeInput of copyNodesInput) {
2193
+ const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2194
+ if (node) {
2195
+ const resolvedName = handleTargetNameCollisions({
2196
+ nodes: drive.state.global.nodes,
2197
+ srcName: copyNodeInput.targetName || node.name,
2198
+ srcKind: isFileNode(node) ? "file" : "folder",
2199
+ targetParentFolder: copyNodeInput.targetParentFolder || null
2200
+ });
2201
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
1995
2202
  }
1996
- var LZString = {
1997
- compressToBase64: function(input) {
1998
- if (input == null) return "";
1999
- var res = LZString._compress(input, 6, function(a) {
2000
- return keyStrBase64.charAt(a);
2001
- });
2002
- switch (res.length % 4) {
2003
- default:
2004
- case 0: return res;
2005
- case 1: return res + "===";
2006
- case 2: return res + "==";
2007
- case 3: return res + "=";
2008
- }
2009
- },
2010
- decompressFromBase64: function(input) {
2011
- if (input == null) return "";
2012
- if (input == "") return null;
2013
- return LZString._decompress(input.length, 32, function(index) {
2014
- return getBaseValue(keyStrBase64, input.charAt(index));
2015
- });
2016
- },
2017
- compressToUTF16: function(input) {
2018
- if (input == null) return "";
2019
- return LZString._compress(input, 15, function(a) {
2020
- return f(a + 32);
2021
- }) + " ";
2022
- },
2023
- decompressFromUTF16: function(compressed) {
2024
- if (compressed == null) return "";
2025
- if (compressed == "") return null;
2026
- return LZString._decompress(compressed.length, 16384, function(index) {
2027
- return compressed.charCodeAt(index) - 32;
2028
- });
2029
- },
2030
- compressToUint8Array: function(uncompressed) {
2031
- var compressed = LZString.compress(uncompressed);
2032
- var buf = new Uint8Array(compressed.length * 2);
2033
- for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
2034
- var current_value = compressed.charCodeAt(i);
2035
- buf[i * 2] = current_value >>> 8;
2036
- buf[i * 2 + 1] = current_value % 256;
2037
- }
2038
- return buf;
2039
- },
2040
- decompressFromUint8Array: function(compressed) {
2041
- if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
2042
- else {
2043
- var buf = new Array(compressed.length / 2);
2044
- for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
2045
- var result = [];
2046
- buf.forEach(function(c) {
2047
- result.push(f(c));
2048
- });
2049
- return LZString.decompress(result.join(""));
2050
- }
2051
- },
2052
- compressToEncodedURIComponent: function(input) {
2053
- if (input == null) return "";
2054
- return LZString._compress(input, 6, function(a) {
2055
- return keyStrUriSafe.charAt(a);
2056
- });
2057
- },
2058
- decompressFromEncodedURIComponent: function(input) {
2059
- if (input == null) return "";
2060
- if (input == "") return null;
2061
- input = input.replace(/ /g, "+");
2062
- return LZString._decompress(input.length, 32, function(index) {
2063
- return getBaseValue(keyStrUriSafe, input.charAt(index));
2064
- });
2065
- },
2066
- compress: function(uncompressed) {
2067
- return LZString._compress(uncompressed, 16, function(a) {
2068
- return f(a);
2069
- });
2070
- },
2071
- _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
2072
- if (uncompressed == null) return "";
2073
- 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;
2074
- for (ii = 0; ii < uncompressed.length; ii += 1) {
2075
- context_c = uncompressed.charAt(ii);
2076
- if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
2077
- context_dictionary[context_c] = context_dictSize++;
2078
- context_dictionaryToCreate[context_c] = true;
2079
- }
2080
- context_wc = context_w + context_c;
2081
- if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
2082
- else {
2083
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2084
- if (context_w.charCodeAt(0) < 256) {
2085
- for (i = 0; i < context_numBits; i++) {
2086
- context_data_val = context_data_val << 1;
2087
- if (context_data_position == bitsPerChar - 1) {
2088
- context_data_position = 0;
2089
- context_data.push(getCharFromInt(context_data_val));
2090
- context_data_val = 0;
2091
- } else context_data_position++;
2092
- }
2093
- value = context_w.charCodeAt(0);
2094
- for (i = 0; i < 8; i++) {
2095
- context_data_val = context_data_val << 1 | value & 1;
2096
- if (context_data_position == bitsPerChar - 1) {
2097
- context_data_position = 0;
2098
- context_data.push(getCharFromInt(context_data_val));
2099
- context_data_val = 0;
2100
- } else context_data_position++;
2101
- value = value >> 1;
2102
- }
2103
- } else {
2104
- value = 1;
2105
- for (i = 0; i < context_numBits; i++) {
2106
- context_data_val = context_data_val << 1 | value;
2107
- if (context_data_position == bitsPerChar - 1) {
2108
- context_data_position = 0;
2109
- context_data.push(getCharFromInt(context_data_val));
2110
- context_data_val = 0;
2111
- } else context_data_position++;
2112
- value = 0;
2113
- }
2114
- value = context_w.charCodeAt(0);
2115
- for (i = 0; i < 16; i++) {
2116
- context_data_val = context_data_val << 1 | value & 1;
2117
- if (context_data_position == bitsPerChar - 1) {
2118
- context_data_position = 0;
2119
- context_data.push(getCharFromInt(context_data_val));
2120
- context_data_val = 0;
2121
- } else context_data_position++;
2122
- value = value >> 1;
2123
- }
2124
- }
2125
- context_enlargeIn--;
2126
- if (context_enlargeIn == 0) {
2127
- context_enlargeIn = Math.pow(2, context_numBits);
2128
- context_numBits++;
2129
- }
2130
- delete context_dictionaryToCreate[context_w];
2131
- } else {
2132
- value = context_dictionary[context_w];
2133
- for (i = 0; i < context_numBits; i++) {
2134
- context_data_val = context_data_val << 1 | value & 1;
2135
- if (context_data_position == bitsPerChar - 1) {
2136
- context_data_position = 0;
2137
- context_data.push(getCharFromInt(context_data_val));
2138
- context_data_val = 0;
2139
- } else context_data_position++;
2140
- value = value >> 1;
2141
- }
2142
- }
2143
- context_enlargeIn--;
2144
- if (context_enlargeIn == 0) {
2145
- context_enlargeIn = Math.pow(2, context_numBits);
2146
- context_numBits++;
2147
- }
2148
- context_dictionary[context_wc] = context_dictSize++;
2149
- context_w = String(context_c);
2150
- }
2151
- }
2152
- if (context_w !== "") {
2153
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2154
- if (context_w.charCodeAt(0) < 256) {
2155
- for (i = 0; i < context_numBits; i++) {
2156
- context_data_val = context_data_val << 1;
2157
- if (context_data_position == bitsPerChar - 1) {
2158
- context_data_position = 0;
2159
- context_data.push(getCharFromInt(context_data_val));
2160
- context_data_val = 0;
2161
- } else context_data_position++;
2162
- }
2163
- value = context_w.charCodeAt(0);
2164
- for (i = 0; i < 8; i++) {
2165
- context_data_val = context_data_val << 1 | value & 1;
2166
- if (context_data_position == bitsPerChar - 1) {
2167
- context_data_position = 0;
2168
- context_data.push(getCharFromInt(context_data_val));
2169
- context_data_val = 0;
2170
- } else context_data_position++;
2171
- value = value >> 1;
2172
- }
2173
- } else {
2174
- value = 1;
2175
- for (i = 0; i < context_numBits; i++) {
2176
- context_data_val = context_data_val << 1 | value;
2177
- if (context_data_position == bitsPerChar - 1) {
2178
- context_data_position = 0;
2179
- context_data.push(getCharFromInt(context_data_val));
2180
- context_data_val = 0;
2181
- } else context_data_position++;
2182
- value = 0;
2183
- }
2184
- value = context_w.charCodeAt(0);
2185
- for (i = 0; i < 16; i++) {
2186
- context_data_val = context_data_val << 1 | value & 1;
2187
- if (context_data_position == bitsPerChar - 1) {
2188
- context_data_position = 0;
2189
- context_data.push(getCharFromInt(context_data_val));
2190
- context_data_val = 0;
2191
- } else context_data_position++;
2192
- value = value >> 1;
2193
- }
2194
- }
2195
- context_enlargeIn--;
2196
- if (context_enlargeIn == 0) {
2197
- context_enlargeIn = Math.pow(2, context_numBits);
2198
- context_numBits++;
2199
- }
2200
- delete context_dictionaryToCreate[context_w];
2201
- } else {
2202
- value = context_dictionary[context_w];
2203
- for (i = 0; i < context_numBits; i++) {
2204
- context_data_val = context_data_val << 1 | value & 1;
2205
- if (context_data_position == bitsPerChar - 1) {
2206
- context_data_position = 0;
2207
- context_data.push(getCharFromInt(context_data_val));
2208
- context_data_val = 0;
2209
- } else context_data_position++;
2210
- value = value >> 1;
2211
- }
2212
- }
2213
- context_enlargeIn--;
2214
- if (context_enlargeIn == 0) {
2215
- context_enlargeIn = Math.pow(2, context_numBits);
2216
- context_numBits++;
2217
- }
2218
- }
2219
- value = 2;
2220
- for (i = 0; i < context_numBits; i++) {
2221
- context_data_val = context_data_val << 1 | value & 1;
2222
- if (context_data_position == bitsPerChar - 1) {
2223
- context_data_position = 0;
2224
- context_data.push(getCharFromInt(context_data_val));
2225
- context_data_val = 0;
2226
- } else context_data_position++;
2227
- value = value >> 1;
2228
- }
2229
- while (true) {
2230
- context_data_val = context_data_val << 1;
2231
- if (context_data_position == bitsPerChar - 1) {
2232
- context_data.push(getCharFromInt(context_data_val));
2233
- break;
2234
- } else context_data_position++;
2235
- }
2236
- return context_data.join("");
2237
- },
2238
- decompress: function(compressed) {
2239
- if (compressed == null) return "";
2240
- if (compressed == "") return null;
2241
- return LZString._decompress(compressed.length, 32768, function(index) {
2242
- return compressed.charCodeAt(index);
2243
- });
2244
- },
2245
- _decompress: function(length, resetValue, getNextValue) {
2246
- var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
2247
- val: getNextValue(0),
2248
- position: resetValue,
2249
- index: 1
2250
- };
2251
- for (i = 0; i < 3; i += 1) dictionary[i] = i;
2252
- bits = 0;
2253
- maxpower = Math.pow(2, 2);
2254
- power = 1;
2255
- while (power != maxpower) {
2256
- resb = data.val & data.position;
2257
- data.position >>= 1;
2258
- if (data.position == 0) {
2259
- data.position = resetValue;
2260
- data.val = getNextValue(data.index++);
2261
- }
2262
- bits |= (resb > 0 ? 1 : 0) * power;
2263
- power <<= 1;
2264
- }
2265
- switch (bits) {
2266
- case 0:
2267
- bits = 0;
2268
- maxpower = Math.pow(2, 8);
2269
- power = 1;
2270
- while (power != maxpower) {
2271
- resb = data.val & data.position;
2272
- data.position >>= 1;
2273
- if (data.position == 0) {
2274
- data.position = resetValue;
2275
- data.val = getNextValue(data.index++);
2276
- }
2277
- bits |= (resb > 0 ? 1 : 0) * power;
2278
- power <<= 1;
2279
- }
2280
- c = f(bits);
2281
- break;
2282
- case 1:
2283
- bits = 0;
2284
- maxpower = Math.pow(2, 16);
2285
- power = 1;
2286
- while (power != maxpower) {
2287
- resb = data.val & data.position;
2288
- data.position >>= 1;
2289
- if (data.position == 0) {
2290
- data.position = resetValue;
2291
- data.val = getNextValue(data.index++);
2292
- }
2293
- bits |= (resb > 0 ? 1 : 0) * power;
2294
- power <<= 1;
2295
- }
2296
- c = f(bits);
2297
- break;
2298
- case 2: return "";
2299
- }
2300
- dictionary[3] = c;
2301
- w = c;
2302
- result.push(c);
2303
- while (true) {
2304
- if (data.index > length) return "";
2305
- bits = 0;
2306
- maxpower = Math.pow(2, numBits);
2307
- power = 1;
2308
- while (power != maxpower) {
2309
- resb = data.val & data.position;
2310
- data.position >>= 1;
2311
- if (data.position == 0) {
2312
- data.position = resetValue;
2313
- data.val = getNextValue(data.index++);
2314
- }
2315
- bits |= (resb > 0 ? 1 : 0) * power;
2316
- power <<= 1;
2317
- }
2318
- switch (c = bits) {
2319
- case 0:
2320
- bits = 0;
2321
- maxpower = Math.pow(2, 8);
2322
- power = 1;
2323
- while (power != maxpower) {
2324
- resb = data.val & data.position;
2325
- data.position >>= 1;
2326
- if (data.position == 0) {
2327
- data.position = resetValue;
2328
- data.val = getNextValue(data.index++);
2329
- }
2330
- bits |= (resb > 0 ? 1 : 0) * power;
2331
- power <<= 1;
2332
- }
2333
- dictionary[dictSize++] = f(bits);
2334
- c = dictSize - 1;
2335
- enlargeIn--;
2336
- break;
2337
- case 1:
2338
- bits = 0;
2339
- maxpower = Math.pow(2, 16);
2340
- power = 1;
2341
- while (power != maxpower) {
2342
- resb = data.val & data.position;
2343
- data.position >>= 1;
2344
- if (data.position == 0) {
2345
- data.position = resetValue;
2346
- data.val = getNextValue(data.index++);
2347
- }
2348
- bits |= (resb > 0 ? 1 : 0) * power;
2349
- power <<= 1;
2350
- }
2351
- dictionary[dictSize++] = f(bits);
2352
- c = dictSize - 1;
2353
- enlargeIn--;
2354
- break;
2355
- case 2: return result.join("");
2356
- }
2357
- if (enlargeIn == 0) {
2358
- enlargeIn = Math.pow(2, numBits);
2359
- numBits++;
2360
- }
2361
- if (dictionary[c]) entry = dictionary[c];
2362
- else if (c === dictSize) entry = w + w.charAt(0);
2363
- else return null;
2364
- result.push(entry);
2365
- dictionary[dictSize++] = w + entry.charAt(0);
2366
- enlargeIn--;
2367
- w = entry;
2368
- if (enlargeIn == 0) {
2369
- enlargeIn = Math.pow(2, numBits);
2370
- numBits++;
2371
- }
2372
- }
2373
- }
2374
- };
2375
- return LZString;
2376
- })();
2377
- if (typeof define === "function" && define.amd) define(function() {
2378
- return LZString;
2379
- });
2380
- else if (typeof module !== "undefined" && module != null) module.exports = LZString;
2381
- else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
2382
- return LZString;
2383
- });
2384
- })))(), 1);
2385
- var DocumentModelNotFoundError = class extends Error {
2386
- documentType;
2387
- name = "DocumentModelNotFoundError";
2388
- constructor(documentType) {
2389
- super(`Document model module for type ${documentType} not found`);
2390
- this.documentType = documentType;
2391
2203
  }
2392
- static isError(error) {
2393
- return Error.isError(error) && error.name === "DocumentModelNotFoundError";
2394
- }
2395
- };
2396
- var DocumentTypeMismatchError = class extends Error {
2397
- constructor(documentId, expectedType, actualType) {
2398
- super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
2399
- }
2400
- };
2401
- var NoSelectedDocumentError = class extends Error {
2402
- constructor() {
2403
- super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
2404
- }
2405
- };
2406
- function getUserPermissions() {
2407
- const user = window.ph?.renown?.user;
2408
- const allowList = window.ph?.allowList;
2409
- if (!allowList) return {
2410
- isAllowedToCreateDocuments: true,
2411
- isAllowedToEditDocuments: true
2412
- };
2413
- return {
2414
- isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
2415
- isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2416
- };
2417
- }
2418
- const BASE_STATE_KEYS = new Set(["auth"]);
2419
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2420
- async function downloadFile(document, fileName) {
2421
- try {
2422
- const data = await createZip(document);
2423
- const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
2424
- const link = window.document.createElement("a");
2425
- link.style.display = "none";
2426
- link.href = URL.createObjectURL(blob);
2427
- link.download = fileName;
2428
- window.document.body.appendChild(link);
2429
- link.click();
2430
- window.document.body.removeChild(link);
2204
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2205
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2206
+ return node !== void 0 && isFileNode(node);
2207
+ });
2208
+ for (const fileNodeToCopy of fileNodesToCopy) try {
2209
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2210
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2211
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
2212
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2431
2213
  } catch (e) {
2432
- logger.error(e instanceof Error ? e.message : String(e));
2433
- }
2434
- }
2435
- async function getDocumentExtension(document) {
2436
- const documentType = document.header.documentType;
2437
- let rawExtension;
2438
- if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2439
- else {
2440
- const reactorClient = window.ph?.reactorClient;
2441
- if (reactorClient) {
2442
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2443
- rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
2444
- }
2214
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2445
2215
  }
2446
- return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
2216
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2447
2217
  }
2448
2218
  /**
2449
- * Fetches all operations for a document using cursor-based pagination.
2450
- * The reactor client handles multi-scope cursors transparently via
2451
- * composite cursors, so all scopes are fetched in a single paginated stream.
2219
+ * Upgrades a document to a newer document model version. Defaults to the
2220
+ * latest registered version for the document's type.
2452
2221
  */
2453
- async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2454
- const scopes = Object.keys(document.state).filter((k) => !BASE_STATE_KEYS.has(k));
2455
- const operations = {};
2456
- for (const scope of scopes) operations[scope] = [];
2457
- let cursor = "";
2458
- do {
2459
- const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
2460
- cursor,
2461
- limit: pageSize
2462
- });
2463
- for (const op of page.results) {
2464
- const scope = op.action.scope ?? "global";
2465
- if (operations[scope]) operations[scope].push(op);
2466
- }
2467
- cursor = page.nextCursor ?? "";
2468
- } while (cursor);
2469
- return operations;
2470
- }
2471
- function extractInitialState(documentScopeOps) {
2472
- const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
2473
- if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
2474
- const input = upgradeOp.action.input;
2475
- const initialState = input.initialState ?? input.state;
2476
- if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
2477
- return initialState;
2478
- }
2479
- function filterDomainOperations(operations) {
2480
- return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2481
- }
2482
- async function exportFile(document, suggestedName) {
2483
- const reactorClient = window.ph?.reactorClient;
2222
+ async function upgradeDocument(documentId, toVersion) {
2223
+ const reactorClient = window.ph?.reactorClientModule?.client;
2484
2224
  if (!reactorClient) throw new Error("ReactorClient not initialized");
2485
- const operations = await fetchDocumentOperations(reactorClient, document);
2486
- const initialState = extractInitialState(operations["document"] ?? []);
2487
- const documentWithOps = {
2488
- ...document,
2489
- operations,
2490
- initialState
2491
- };
2492
- const extension = await getDocumentExtension(documentWithOps);
2493
- const baseName = suggestedName || documentWithOps.header.name || "Untitled";
2494
- const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
2495
- if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
2496
- try {
2497
- const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
2498
- await baseSaveToFileHandle(documentWithOps, fileHandle);
2499
- return fileHandle;
2500
- } catch (e) {
2501
- if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
2502
- }
2225
+ return reactorClient.upgradeDocument(documentId, toVersion);
2503
2226
  }
2504
2227
  /**
2505
- * Loads a document file and replays it with version-aware reducers from the registry.
2506
- * Falls back to single-version legacy replay when no upgrade manifest is registered for
2507
- * the document type.
2228
+ * The operation selection of `GetDocumentOperations`, lifted into a fragment so
2229
+ * the write path can reuse `remoteOperationToLocal` on the items it selects.
2508
2230
  */
2509
- async function loadFile(path) {
2510
- const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2511
- const reactorClient = window.ph?.reactorClient;
2512
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2513
- const documentType = baseDocument.header.documentType;
2514
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2515
- const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
2516
- if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
2517
- const reducers = {};
2518
- for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
2519
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2520
- let upgradeManifest;
2521
- if (registry) try {
2522
- upgradeManifest = registry.getUpgradeManifest(documentType);
2523
- } catch {}
2524
- return baseLoadFromInputVersioned(path, {
2525
- reducers,
2526
- upgradeManifest
2527
- });
2528
- }
2529
- async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
2530
- const { isAllowedToCreateDocuments } = getUserPermissions();
2531
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2532
- const reactorClient = window.ph?.reactorClient;
2533
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2534
- const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2535
- const newDocument = document ?? documentModelModule.utils.createDocument();
2536
- newDocument.header.name = name;
2537
- if (preferredEditor) newDocument.header.meta = {
2538
- ...newDocument.header.meta,
2539
- preferredEditor
2540
- };
2541
- let newDoc;
2542
- try {
2543
- newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2544
- } catch (e) {
2545
- logger.error("Error adding document: @error", e);
2546
- throw new Error("There was an error adding document", { cause: e });
2547
- }
2548
- return {
2549
- id: newDoc.header.id,
2550
- name: newDoc.header.name,
2551
- documentType,
2552
- parentFolder: parentFolder ?? null,
2553
- kind: "file"
2554
- };
2555
- }
2556
- async function addFile(file, driveId, name, parentFolder) {
2557
- logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2558
- const { isAllowedToCreateDocuments } = getUserPermissions();
2559
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2560
- const document = await loadFile(file);
2561
- let duplicateId = false;
2562
- const reactorClient = window.ph?.reactorClient;
2563
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2564
- try {
2565
- await reactorClient.get(document.header.id);
2566
- duplicateId = true;
2567
- } catch {}
2568
- const documentId = duplicateId ? generateId() : document.header.id;
2569
- const header = createPresignedHeader(documentId, document.header.documentType);
2570
- header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2571
- header.meta = document.header.meta;
2572
- header.name = name || document.header.name;
2573
- const initialDocument = {
2574
- ...document,
2575
- header,
2576
- state: document.initialState,
2577
- operations: Object.keys(document.operations).reduce((acc, key) => {
2578
- acc[key] = [];
2579
- return acc;
2580
- }, {})
2581
- };
2582
- await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2583
- await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
2584
- }
2585
- async function addFolder(driveId, name, parentFolder) {
2586
- const { isAllowedToCreateDocuments } = getUserPermissions();
2587
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2588
- const reactorClient = window.ph?.reactorClient;
2589
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2590
- await reactorClient.get(driveId);
2591
- const folderId = generateId();
2592
- const node = (await reactorClient.execute(driveId, "main", [addFolder$1({
2593
- id: folderId,
2594
- name,
2595
- parentFolder
2596
- })])).state.global.nodes.find((node) => node.id === folderId);
2597
- if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2598
- return node;
2599
- }
2600
- async function renameNode(driveId, nodeId, name) {
2601
- const { isAllowedToCreateDocuments } = getUserPermissions();
2602
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2603
- const reactorClient = window.ph?.reactorClient;
2604
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2605
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2606
- const node = (await reactorClient.execute(driveId, "main", [updateNode({
2607
- id: nodeId,
2608
- name
2609
- })])).state.global.nodes.find((n) => n.id === nodeId);
2610
- if (!node) throw new Error("There was an error renaming node in the drive");
2611
- return node;
2612
- }
2613
- async function renameDriveNode(driveId, nodeId, name) {
2614
- const { isAllowedToCreateDocuments } = getUserPermissions();
2615
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2616
- const reactorClient = window.ph?.reactorClient;
2617
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2618
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2619
- await reactorClient.execute(driveId, "main", [updateNode({
2620
- id: nodeId,
2621
- name
2622
- })]);
2623
- return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2624
- }
2625
- async function moveNodeById(args) {
2626
- const { driveId, srcId, targetId } = args;
2627
- if (!driveId || !srcId) return;
2628
- const { isAllowedToCreateDocuments } = getUserPermissions();
2629
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2630
- const reactorClient = window.ph?.reactorClient;
2631
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2632
- const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2633
- if (t(targetParentFolder, srcId)) return;
2634
- return await reactorClient.execute(driveId, "main", [moveNode({
2635
- srcFolder: srcId,
2636
- targetParentFolder
2637
- })]);
2638
- }
2639
- async function moveNode$1(driveId, src, target) {
2640
- const { isAllowedToCreateDocuments } = getUserPermissions();
2641
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2642
- const reactorClient = window.ph?.reactorClient;
2643
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2644
- return await reactorClient.execute(driveId, "main", [moveNode({
2645
- srcFolder: src.id,
2646
- targetParentFolder: target?.id
2647
- })]);
2648
- }
2649
- /**
2650
- * Duplicates a document under a new id using version-aware replay.
2651
- * Falls back gracefully when no upgrade manifest is registered for the document type.
2652
- */
2653
- async function _duplicateDocument(reactor, document, newId = generateId()) {
2654
- const documentType = document.header.documentType;
2655
- const { results: allModules } = await reactor.getDocumentModelModules();
2656
- const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2657
- const reducers = {};
2658
- for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2659
- if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2660
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2661
- let upgradeManifest;
2662
- if (registry) try {
2663
- upgradeManifest = registry.getUpgradeManifest(documentType);
2664
- } catch {}
2665
- const config = {
2666
- reducers,
2667
- upgradeManifest
2668
- };
2669
- const header = createPresignedHeader(newId, documentType);
2670
- return replayDocumentVersioned(document.initialState, document.operations, config, header);
2671
- }
2672
- async function copyNode$1(driveId, src, target) {
2673
- const reactor = window.ph?.reactorClient;
2674
- if (!reactor) return;
2675
- const { isAllowedToCreateDocuments } = getUserPermissions();
2676
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2677
- const drive = await reactor.get(driveId);
2678
- const copyNodesInput = generateNodesCopy({
2679
- srcId: src.id,
2680
- targetParentFolder: target?.id,
2681
- targetName: src.name
2682
- }, () => generateId(), drive.state.global.nodes);
2683
- const resolvedNamesMap = /* @__PURE__ */ new Map();
2684
- for (const copyNodeInput of copyNodesInput) {
2685
- const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2686
- if (node) {
2687
- const resolvedName = handleTargetNameCollisions({
2688
- nodes: drive.state.global.nodes,
2689
- srcName: copyNodeInput.targetName || node.name,
2690
- srcKind: isFileNode(node) ? "file" : "folder",
2691
- targetParentFolder: copyNodeInput.targetParentFolder || null
2692
- });
2693
- resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2694
- }
2695
- }
2696
- const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2697
- const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2698
- return node !== void 0 && isFileNode(node);
2699
- });
2700
- for (const fileNodeToCopy of fileNodesToCopy) try {
2701
- const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2702
- const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2703
- if (resolvedName) duplicatedDocument.header.name = resolvedName;
2704
- await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2705
- } catch (e) {
2706
- logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2707
- }
2708
- return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2709
- }
2710
- const modalEventFunctions = makePHEventFunctions("modal");
2711
- modalEventFunctions.useValue;
2712
- /** Sets the current modal */
2713
- const setPHModal = modalEventFunctions.setValue;
2714
- modalEventFunctions.addEventHandler;
2715
- /** Shows a modal */
2716
- function showPHModal(modal) {
2717
- setPHModal(modal);
2718
- }
2719
- /** Shows the create document modal */
2720
- function showCreateDocumentModal(documentType) {
2721
- setPHModal({
2722
- type: "createDocument",
2723
- documentType
2724
- });
2725
- }
2726
- /** Shows the delete node modal */
2727
- function showDeleteNodeModal(nodeOrId) {
2728
- setPHModal({
2729
- type: "deleteItem",
2730
- id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2731
- });
2732
- }
2733
- /** Document types that represent a "drive": a container of nodes. */
2734
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
2735
- const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2736
- /** Sets whether external controls are enabled for a given editor. */
2737
- const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2738
- /** Gets whether external controls are enabled for a given editor. */
2739
- const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2740
- isExternalControlsEnabledEventFunctions.addEventHandler;
2741
- const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2742
- /** Sets whether drag and drop is enabled for a given app. */
2743
- const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2744
- /** Gets whether drag and drop is enabled for a given app. */
2745
- const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2746
- isDragAndDropEnabledEventFunctions.addEventHandler;
2747
- const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2748
- /** Sets the allowed document types for a given app. */
2749
- const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2750
- /** Defines the document types a drive supports.
2751
- *
2752
- * Defaults to all of the document types registered in the reactor.
2753
- */
2754
- function useAllowedDocumentTypes() {
2755
- return allowedDocumentTypesEventFunctions.useValue();
2231
+ const ReactorOperationFieldsFragmentDoc = import_main.gql`
2232
+ fragment ReactorOperationFields on ReactorOperation {
2233
+ index
2234
+ timestampUtcMs
2235
+ hash
2236
+ skip
2237
+ error
2238
+ deniedReason
2239
+ id
2240
+ action {
2241
+ id
2242
+ type
2243
+ timestampUtcMs
2244
+ input
2245
+ scope
2246
+ context {
2247
+ signer {
2248
+ user {
2249
+ address
2250
+ networkId
2251
+ chainId
2252
+ }
2253
+ app {
2254
+ name
2255
+ key
2256
+ }
2257
+ signatures
2258
+ }
2259
+ }
2260
+ }
2261
+ }
2262
+ `;
2263
+ import_main.gql`
2264
+ mutation MutateDocumentWithOperations(
2265
+ $documentIdentifier: String!
2266
+ $actions: [ActionInput!]!
2267
+ $sinceRevision: Int
2268
+ $scopes: [String!]
2269
+ $branch: String
2270
+ ) {
2271
+ mutateDocument: execute(
2272
+ documentIdentifier: $documentIdentifier
2273
+ actions: $actions
2274
+ branch: $branch
2275
+ ) {
2276
+ ...PHDocumentFields
2277
+ operations(
2278
+ filter: {
2279
+ sinceRevision: $sinceRevision
2280
+ scopes: $scopes
2281
+ branch: $branch
2282
+ }
2283
+ ) {
2284
+ items {
2285
+ ...ReactorOperationFields
2286
+ }
2287
+ }
2288
+ }
2289
+ }
2290
+ ${PhDocumentFieldsFragmentDoc}
2291
+ ${ReactorOperationFieldsFragmentDoc}
2292
+ `;
2293
+ DocumentChangeType.Created, DOCUMENT_CHANGE_TYPE.Created, DocumentChangeType.Deleted, DOCUMENT_CHANGE_TYPE.Deleted, DocumentChangeType.Updated, DOCUMENT_CHANGE_TYPE.Updated, DocumentChangeType.ParentAdded, DOCUMENT_CHANGE_TYPE.ParentAdded, DocumentChangeType.ParentRemoved, DOCUMENT_CHANGE_TYPE.ParentRemoved, DocumentChangeType.ChildAdded, DOCUMENT_CHANGE_TYPE.ChildAdded, DocumentChangeType.ChildRemoved, DOCUMENT_CHANGE_TYPE.ChildRemoved;
2294
+ PropagationMode.Cascade, PropagationMode.Orphan;
2295
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2296
+ /** Sets whether external controls are enabled for a given editor. */
2297
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2298
+ /** Gets whether external controls are enabled for a given editor. */
2299
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2300
+ isExternalControlsEnabledEventFunctions.addEventHandler;
2301
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2302
+ /** Sets whether drag and drop is enabled for a given app. */
2303
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2304
+ /** Gets whether drag and drop is enabled for a given app. */
2305
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2306
+ isDragAndDropEnabledEventFunctions.addEventHandler;
2307
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2308
+ /** Sets the allowed document types for a given app. */
2309
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2310
+ /** Defines the document types a drive supports.
2311
+ *
2312
+ * Defaults to all of the document types registered in the reactor.
2313
+ */
2314
+ function useAllowedDocumentTypes() {
2315
+ return allowedDocumentTypesEventFunctions.useValue();
2756
2316
  }
2757
2317
  allowedDocumentTypesEventFunctions.addEventHandler;
2758
2318
  const phAppConfigSetters = {
@@ -2797,6 +2357,8 @@ const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabl
2797
2357
  const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
2798
2358
  const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
2799
2359
  const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
2360
+ const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
2361
+ const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
2800
2362
  const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
2801
2363
  const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
2802
2364
  const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
@@ -2894,6 +2456,8 @@ const nonUserConfigSetters = {
2894
2456
  renownUrl: setRenownUrl,
2895
2457
  renownNetworkId: setRenownNetworkId,
2896
2458
  renownChainId: setRenownChainId,
2459
+ switchboardUrl: setSwitchboardUrl,
2460
+ renownAdapters: setRenownAdapters,
2897
2461
  sentryRelease: setSentryRelease,
2898
2462
  sentryDsn: setSentryDsn,
2899
2463
  sentryEnv: setSentryEnv,
@@ -2942,6 +2506,8 @@ const nonUserConfigHooks = {
2942
2506
  renownUrl: useRenownUrl,
2943
2507
  renownNetworkId: useRenownNetworkId,
2944
2508
  renownChainId: useRenownChainId,
2509
+ switchboardUrl: useSwitchboardUrl,
2510
+ renownAdapters: useRenownAdapters,
2945
2511
  sentryRelease: useSentryRelease,
2946
2512
  sentryDsn: useSentryDsn,
2947
2513
  sentryEnv: useSentryEnv,
@@ -3122,215 +2688,931 @@ function deferDriveSelection(driveSlug) {
3122
2688
  scheduleTick();
3123
2689
  return;
3124
2690
  }
3125
- cancelPendingDriveSelection();
3126
- const pathname = resolveUrlPathname("/");
3127
- if (pathname === window.location.pathname) return;
3128
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3129
- }, DEFERRED_DRIVE_TICK_MS);
3130
- };
3131
- scheduleTick();
3132
- }
3133
- function useDropTarget() {
3134
- const [isDropTarget, setIsDropTarget] = useState(false);
3135
- const isDragAndDropEnabled = useIsDragAndDropEnabled();
3136
- const targetSetter = n$1(() => setIsDropTarget(true), {
3137
- triggerAt: "start",
3138
- minQuietPeriodMs: 100
2691
+ cancelPendingDriveSelection();
2692
+ const pathname = resolveUrlPathname("/");
2693
+ if (pathname === window.location.pathname) return;
2694
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2695
+ }, DEFERRED_DRIVE_TICK_MS);
2696
+ };
2697
+ scheduleTick();
2698
+ }
2699
+ function useDropTarget() {
2700
+ const [isDropTarget, setIsDropTarget] = useState(false);
2701
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
2702
+ const targetSetter = n$1(() => setIsDropTarget(true), {
2703
+ triggerAt: "start",
2704
+ minQuietPeriodMs: 100
2705
+ });
2706
+ const targetUnsetter = n$1(() => setIsDropTarget(false), {
2707
+ triggerAt: "start",
2708
+ minQuietPeriodMs: 100
2709
+ });
2710
+ function setTarget() {
2711
+ if (!isDragAndDropEnabled) return;
2712
+ targetUnsetter.cancel();
2713
+ targetSetter.call();
2714
+ }
2715
+ function unsetTarget() {
2716
+ if (!isDragAndDropEnabled) return;
2717
+ targetSetter.cancel();
2718
+ targetUnsetter.call();
2719
+ }
2720
+ return {
2721
+ isDropTarget,
2722
+ setTarget,
2723
+ unsetTarget
2724
+ };
2725
+ }
2726
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
2727
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
2728
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
2729
+ draggingNodeEventFunctions.addEventHandler;
2730
+ const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
2731
+ reducer: (_, newNode) => newNode,
2732
+ triggerAt: "start",
2733
+ minQuietPeriodMs: 100
2734
+ });
2735
+ const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
2736
+ triggerAt: "start",
2737
+ minQuietPeriodMs: 100
2738
+ });
2739
+ function setDragging(node) {
2740
+ draggingNodeUnsetter.cancel();
2741
+ draggingNodeSetter.call(node);
2742
+ }
2743
+ function unsetDragging() {
2744
+ draggingNodeSetter.cancel();
2745
+ draggingNodeUnsetter.call();
2746
+ }
2747
+ 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));
2748
+ function useDragNode(args) {
2749
+ const { srcId, parentId } = args;
2750
+ const driveId = useSelectedDriveId();
2751
+ const draggingNodeId = useDraggingNode()?.srcId;
2752
+ const params = {
2753
+ driveId,
2754
+ srcId,
2755
+ parentId
2756
+ };
2757
+ const draggable = isNodeDrag(params);
2758
+ const isDragging = t$4({
2759
+ srcId,
2760
+ draggingNodeId
2761
+ }, [
2762
+ () => draggable,
2763
+ ({ srcId }) => e$2(srcId),
2764
+ ({ draggingNodeId }) => e$2(draggingNodeId),
2765
+ ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
2766
+ ]);
2767
+ const onDragStart = () => {
2768
+ if (!draggable) return;
2769
+ setDragging(params);
2770
+ };
2771
+ const onDragEnd = () => {
2772
+ if (!draggable) return;
2773
+ unsetDragging();
2774
+ };
2775
+ return {
2776
+ isDragging,
2777
+ draggable,
2778
+ onDragStart,
2779
+ onDragEnd
2780
+ };
2781
+ }
2782
+ 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));
2783
+ function useDropNode(targetId) {
2784
+ const driveId = useSelectedDriveId();
2785
+ const { srcId, parentId } = useDraggingNode() ?? {};
2786
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
2787
+ const params = {
2788
+ driveId,
2789
+ parentId,
2790
+ targetId,
2791
+ srcId
2792
+ };
2793
+ function handleNodeDrop(event, cb) {
2794
+ if (!isNodeDrop(params)) return;
2795
+ event.preventDefault();
2796
+ event.stopPropagation();
2797
+ cb?.();
2798
+ }
2799
+ const onDragEnter = (event) => handleNodeDrop(event);
2800
+ const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
2801
+ const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
2802
+ const onDrop = (event) => handleNodeDrop(event, e(() => {
2803
+ unsetDragging();
2804
+ unsetTarget();
2805
+ moveNodeById(params).catch(console.error);
2806
+ }));
2807
+ return {
2808
+ isDropTarget,
2809
+ onDragEnter,
2810
+ onDragOver,
2811
+ onDragLeave,
2812
+ onDrop
2813
+ };
2814
+ }
2815
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
2816
+ graphQLReactorClientEventFunctions.useValue;
2817
+ graphQLReactorClientEventFunctions.setValue;
2818
+ graphQLReactorClientEventFunctions.addEventHandler;
2819
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
2820
+ packageDiscoveryFunctions.useValue;
2821
+ packageDiscoveryFunctions.setValue;
2822
+ packageDiscoveryFunctions.addEventHandler;
2823
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
2824
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
2825
+ /** Returns the reactor client module (in-process or worker-backed) */
2826
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
2827
+ reactorClientModuleEventFunctions.setValue;
2828
+ reactorClientModuleEventFunctions.addEventHandler;
2829
+ reactorClientEventFunctions.useValue;
2830
+ reactorClientEventFunctions.setValue;
2831
+ reactorClientEventFunctions.addEventHandler;
2832
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
2833
+ const useSyncList = () => {
2834
+ return useSync()?.list() ?? [];
2835
+ };
2836
+ const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
2837
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
2838
+ revisionHistoryEventFunctions.useValue;
2839
+ /** Sets revision history visibility */
2840
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
2841
+ revisionHistoryEventFunctions.addEventHandler;
2842
+ /** Shows the revision history */
2843
+ function showRevisionHistory() {
2844
+ setRevisionHistoryVisible(true);
2845
+ }
2846
+ /** Sorts nodes by name. */
2847
+ function sortNodesByName(nodes) {
2848
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
2849
+ }
2850
+ /** Returns whether a node is a file. */
2851
+ function isFileNodeKind(node) {
2852
+ if (!node) return false;
2853
+ return node.kind.toUpperCase() === "FILE";
2854
+ }
2855
+ /** Returns whether a node is a folder. */
2856
+ function isFolderNodeKind(node) {
2857
+ if (!node) return false;
2858
+ return node.kind.toUpperCase() === "FOLDER";
2859
+ }
2860
+ /** Returns the nodes in the selected drive. */
2861
+ function useNodesInSelectedDrive() {
2862
+ const [selectedDrive] = useSelectedDriveSafe();
2863
+ return selectedDrive?.state.global.nodes;
2864
+ }
2865
+ /** Returns the folder nodes in the selected drive. */
2866
+ function useFolderNodesInSelectedDrive() {
2867
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
2868
+ }
2869
+ /** Returns the selected node. */
2870
+ function useSelectedNode() {
2871
+ const selectedNodeId = useSelectedNodeId();
2872
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
2873
+ }
2874
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
2875
+ selectedTimelineItemEventFunctions.useValue;
2876
+ selectedTimelineItemEventFunctions.setValue;
2877
+ selectedTimelineItemEventFunctions.addEventHandler;
2878
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
2879
+ selectedTimelineRevisionEventFunctions.useValue;
2880
+ selectedTimelineRevisionEventFunctions.setValue;
2881
+ selectedTimelineRevisionEventFunctions.addEventHandler;
2882
+ const toastEventFunctions = makePHEventFunctions("toast");
2883
+ /** Returns the toast function */
2884
+ const usePHToast = toastEventFunctions.useValue;
2885
+ toastEventFunctions.setValue;
2886
+ toastEventFunctions.addEventHandler;
2887
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
2888
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
2889
+ /** Returns all of the Vetra packages loaded by the Connect instance */
2890
+ const useVetraPackages = () => {
2891
+ const packageManager = useVetraPackageManager();
2892
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
2893
+ };
2894
+ vetraPackageManagerFunctions.addEventHandler;
2895
+ function useDocumentModelModules() {
2896
+ 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);
2897
+ }
2898
+ /**
2899
+ * Resolves a document model module by document type, mirroring the registry's
2900
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
2901
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
2902
+ * with `version` given only an exact match is returned. The reactor resolves
2903
+ * modules the same way when a document is created, so metadata read through
2904
+ * this hook and the version a creation actually uses cannot disagree.
2905
+ */
2906
+ function useDocumentModelModuleById(id, version) {
2907
+ const documentModelModules = useDocumentModelModules();
2908
+ if (!id || !documentModelModules) return void 0;
2909
+ let latestModule;
2910
+ let latestVersion = -1;
2911
+ for (const module of documentModelModules) {
2912
+ if (module.documentModel.global.id !== id) continue;
2913
+ const moduleVersion = module.version ?? 1;
2914
+ if (version !== void 0) {
2915
+ if (moduleVersion === version) return module;
2916
+ continue;
2917
+ }
2918
+ if (moduleVersion > latestVersion) {
2919
+ latestVersion = moduleVersion;
2920
+ latestModule = module;
2921
+ }
2922
+ }
2923
+ return latestModule;
2924
+ }
2925
+ //#endregion
2926
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
2927
+ const normalizeDescriptors = (error) => {
2928
+ CORE_ERROR_PROPS.forEach((propName) => {
2929
+ normalizeDescriptor(error, propName);
2930
+ });
2931
+ };
2932
+ const CORE_ERROR_PROPS = [
2933
+ "name",
2934
+ "message",
2935
+ "stack",
2936
+ "cause",
2937
+ "errors"
2938
+ ];
2939
+ const normalizeDescriptor = (error, propName) => {
2940
+ const descriptor = getDescriptor(error, propName);
2941
+ if (descriptor === void 0) return;
2942
+ if (isReadonlyGetter(descriptor)) {
2943
+ setErrorProperty(error, propName, error[propName]);
2944
+ return;
2945
+ }
2946
+ if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
2947
+ };
2948
+ const getDescriptor = (value, propName) => {
2949
+ const descriptor = Object.getOwnPropertyDescriptor(value, propName);
2950
+ if (descriptor !== void 0) return descriptor;
2951
+ const prototype = Object.getPrototypeOf(value);
2952
+ return prototype === null ? void 0 : getDescriptor(prototype, propName);
2953
+ };
2954
+ const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
2955
+ const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
2956
+ const setErrorProperty = (error, propName, value) => {
2957
+ setErrorDescriptor(error, propName, { value });
2958
+ };
2959
+ const setErrorDescriptor = (error, propName, descriptor) => {
2960
+ Object.defineProperty(error, propName, {
2961
+ ...descriptor,
2962
+ ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
2963
+ enumerable: false,
2964
+ configurable: true
2965
+ });
2966
+ };
2967
+ //#endregion
2968
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
2969
+ const normalizeAggregate = (error, recurse) => {
2970
+ if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
2971
+ else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
2972
+ else if (error.errors !== void 0) deleteAggregateErrors(error);
2973
+ };
2974
+ const isDefined = (error) => error !== void 0;
2975
+ const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
2976
+ const deleteAggregateErrors = (error) => {
2977
+ delete error.errors;
2978
+ if (error.errors !== void 0) setErrorProperty(error, "errors", []);
2979
+ };
2980
+ //#endregion
2981
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
2982
+ const normalizeCause = (error, recurse) => {
2983
+ if (!("cause" in error)) return;
2984
+ const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
2985
+ if (cause === void 0) delete error.cause;
2986
+ else setErrorProperty(error, "cause", cause);
2987
+ };
2988
+ //#endregion
2989
+ //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
2990
+ const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
2991
+ const isInstanceOfError = (value) => {
2992
+ try {
2993
+ return value instanceof Error;
2994
+ } catch {
2995
+ return false;
2996
+ }
2997
+ };
2998
+ const hasErrorTag = (value) => {
2999
+ try {
3000
+ return ERROR_TAGS.has(Object.prototype.toString.call(value));
3001
+ } catch {
3002
+ return false;
3003
+ }
3004
+ };
3005
+ const ERROR_TAGS = new Set([
3006
+ "[object Error]",
3007
+ "[object DOMException]",
3008
+ "[object DOMError]",
3009
+ "[object Exception]"
3010
+ ]);
3011
+ //#endregion
3012
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
3013
+ function isPlainObject(value) {
3014
+ if (typeof value !== "object" || value === null) return false;
3015
+ const prototype = Object.getPrototypeOf(value);
3016
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
3017
+ }
3018
+ //#endregion
3019
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
3020
+ const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
3021
+ const isNonConfigurableProp = (error, propName) => {
3022
+ const descriptor = Object.getOwnPropertyDescriptor(error, propName);
3023
+ return descriptor !== void 0 && !descriptor.configurable;
3024
+ };
3025
+ const isThrowingProp = (error, propName) => {
3026
+ try {
3027
+ error[propName];
3028
+ return false;
3029
+ } catch {
3030
+ return true;
3031
+ }
3032
+ };
3033
+ //#endregion
3034
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
3035
+ const setStack = (error) => {
3036
+ setErrorProperty(error, "stack", getStack(error.message, error.name));
3037
+ };
3038
+ const getStack = (message = "", name = "Error") => {
3039
+ const { stack } = new (getErrorClass(name))(message);
3040
+ return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
3041
+ };
3042
+ const getErrorClass = (name) => {
3043
+ const descriptor = {
3044
+ value: name,
3045
+ enumerable: false,
3046
+ writable: true,
3047
+ configurable: true
3048
+ };
3049
+ const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
3050
+ Object.defineProperty(StackError.prototype, "name", descriptor);
3051
+ return StackError;
3052
+ };
3053
+ //#endregion
3054
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
3055
+ const copyObject = (object) => {
3056
+ const objectCopy = {};
3057
+ for (const propName of getPropsToCopy(object)) try {
3058
+ const value = object[propName];
3059
+ const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
3060
+ Object.defineProperty(objectCopy, propName, {
3061
+ value,
3062
+ enumerable,
3063
+ configurable,
3064
+ writable
3065
+ });
3066
+ } catch {}
3067
+ return objectCopy;
3068
+ };
3069
+ const getPropsToCopy = (object) => {
3070
+ const propNames = getOwnKeys(object);
3071
+ for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
3072
+ return propNames;
3073
+ };
3074
+ const getOwnKeys = (object) => {
3075
+ try {
3076
+ return Reflect.ownKeys(object);
3077
+ } catch {
3078
+ return [];
3079
+ }
3080
+ };
3081
+ const isInheritedProp = (object, propName) => {
3082
+ try {
3083
+ return propName in object && !Object.hasOwn(object, propName);
3084
+ } catch {
3085
+ return false;
3086
+ }
3087
+ };
3088
+ //#endregion
3089
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
3090
+ const objectifyError = (object) => {
3091
+ const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
3092
+ const messageA = getMessage(message, objectA);
3093
+ const error = newError(name, messageA);
3094
+ if (message === messageA) assignObjectProps(error, objectA);
3095
+ Object.entries({
3096
+ name,
3097
+ stack,
3098
+ cause,
3099
+ errors
3100
+ }).forEach(([propName, propValue]) => {
3101
+ setNewErrorProperty(error, propName, propValue);
3102
+ });
3103
+ if (stack === void 0) setStack(error);
3104
+ return error;
3105
+ };
3106
+ const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
3107
+ const safeJsonStringify = (object) => {
3108
+ try {
3109
+ return JSON.stringify(object);
3110
+ } catch {
3111
+ return safeStringify(object);
3112
+ }
3113
+ };
3114
+ const safeStringify = (object) => {
3115
+ try {
3116
+ return String(object);
3117
+ } catch {
3118
+ return "Invalid error";
3119
+ }
3120
+ };
3121
+ const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
3122
+ const MESSAGE_MAX_SIZE = 1e3;
3123
+ const newError = (name, message) => {
3124
+ if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
3125
+ if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
3126
+ return new Error(message);
3127
+ };
3128
+ const NATIVE_ERRORS = {
3129
+ Error,
3130
+ ReferenceError,
3131
+ TypeError,
3132
+ SyntaxError,
3133
+ RangeError,
3134
+ URIError,
3135
+ EvalError
3136
+ };
3137
+ const assignObjectProps = (error, object) => {
3138
+ for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
3139
+ };
3140
+ const setNewErrorProperty = (error, propName, propValue) => {
3141
+ if (propValue !== void 0) setErrorProperty(error, propName, propValue);
3142
+ };
3143
+ //#endregion
3144
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
3145
+ const stringifyError = (value) => {
3146
+ try {
3147
+ const error = new Error(String(value));
3148
+ setStack(error);
3149
+ return error;
3150
+ } catch (error_) {
3151
+ return error_;
3152
+ }
3153
+ };
3154
+ //#endregion
3155
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
3156
+ const { toString: objectToString } = Object.prototype;
3157
+ const createError = (value) => {
3158
+ if (isErrorPlainObj(value)) return objectifyError(value);
3159
+ if (!isErrorInstance(value)) return stringifyError(value);
3160
+ if (isInvalidError(value)) return objectifyError(value);
3161
+ return value;
3162
+ };
3163
+ const isErrorPlainObj = (value) => {
3164
+ try {
3165
+ return isPlainObject(value);
3166
+ } catch {
3167
+ return false;
3168
+ }
3169
+ };
3170
+ const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
3171
+ const isProxy = (value) => {
3172
+ try {
3173
+ return objectToString.call(value) === "[object Object]";
3174
+ } catch {
3175
+ return true;
3176
+ }
3177
+ };
3178
+ const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
3179
+ //#endregion
3180
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
3181
+ const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
3182
+ const recurseException = (error, parents, shallow) => {
3183
+ if (parents.includes(error)) return;
3184
+ const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
3185
+ const errorA = createError(error);
3186
+ normalizeProps(errorA, recurse);
3187
+ return errorA;
3188
+ };
3189
+ const identity = (error) => error;
3190
+ const normalizeProps = (error, recurse) => {
3191
+ normalizeName(error);
3192
+ normalizeMessage(error);
3193
+ normalizeStack(error);
3194
+ normalizeCause(error, recurse);
3195
+ normalizeAggregate(error, recurse);
3196
+ normalizeDescriptors(error);
3197
+ };
3198
+ const normalizeName = (error) => {
3199
+ if (isDefinedString(error.name)) return;
3200
+ const prototypeName = Object.getPrototypeOf(error).name;
3201
+ setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
3202
+ };
3203
+ const normalizeMessage = (error) => {
3204
+ if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
3205
+ };
3206
+ const normalizeStack = (error) => {
3207
+ if (!isDefinedString(error.stack)) setStack(error);
3208
+ };
3209
+ const isDefinedString = (value) => typeof value === "string" && value !== "";
3210
+ //#endregion
3211
+ //#region ../reactor-browser/dist/index.js
3212
+ var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3213
+ var LZString = (function() {
3214
+ var f = String.fromCharCode;
3215
+ var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3216
+ var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
3217
+ var baseReverseDic = {};
3218
+ function getBaseValue(alphabet, character) {
3219
+ if (!baseReverseDic[alphabet]) {
3220
+ baseReverseDic[alphabet] = {};
3221
+ for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
3222
+ }
3223
+ return baseReverseDic[alphabet][character];
3224
+ }
3225
+ var LZString = {
3226
+ compressToBase64: function(input) {
3227
+ if (input == null) return "";
3228
+ var res = LZString._compress(input, 6, function(a) {
3229
+ return keyStrBase64.charAt(a);
3230
+ });
3231
+ switch (res.length % 4) {
3232
+ default:
3233
+ case 0: return res;
3234
+ case 1: return res + "===";
3235
+ case 2: return res + "==";
3236
+ case 3: return res + "=";
3237
+ }
3238
+ },
3239
+ decompressFromBase64: function(input) {
3240
+ if (input == null) return "";
3241
+ if (input == "") return null;
3242
+ return LZString._decompress(input.length, 32, function(index) {
3243
+ return getBaseValue(keyStrBase64, input.charAt(index));
3244
+ });
3245
+ },
3246
+ compressToUTF16: function(input) {
3247
+ if (input == null) return "";
3248
+ return LZString._compress(input, 15, function(a) {
3249
+ return f(a + 32);
3250
+ }) + " ";
3251
+ },
3252
+ decompressFromUTF16: function(compressed) {
3253
+ if (compressed == null) return "";
3254
+ if (compressed == "") return null;
3255
+ return LZString._decompress(compressed.length, 16384, function(index) {
3256
+ return compressed.charCodeAt(index) - 32;
3257
+ });
3258
+ },
3259
+ compressToUint8Array: function(uncompressed) {
3260
+ var compressed = LZString.compress(uncompressed);
3261
+ var buf = new Uint8Array(compressed.length * 2);
3262
+ for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
3263
+ var current_value = compressed.charCodeAt(i);
3264
+ buf[i * 2] = current_value >>> 8;
3265
+ buf[i * 2 + 1] = current_value % 256;
3266
+ }
3267
+ return buf;
3268
+ },
3269
+ decompressFromUint8Array: function(compressed) {
3270
+ if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
3271
+ else {
3272
+ var buf = new Array(compressed.length / 2);
3273
+ for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
3274
+ var result = [];
3275
+ buf.forEach(function(c) {
3276
+ result.push(f(c));
3277
+ });
3278
+ return LZString.decompress(result.join(""));
3279
+ }
3280
+ },
3281
+ compressToEncodedURIComponent: function(input) {
3282
+ if (input == null) return "";
3283
+ return LZString._compress(input, 6, function(a) {
3284
+ return keyStrUriSafe.charAt(a);
3285
+ });
3286
+ },
3287
+ decompressFromEncodedURIComponent: function(input) {
3288
+ if (input == null) return "";
3289
+ if (input == "") return null;
3290
+ input = input.replace(/ /g, "+");
3291
+ return LZString._decompress(input.length, 32, function(index) {
3292
+ return getBaseValue(keyStrUriSafe, input.charAt(index));
3293
+ });
3294
+ },
3295
+ compress: function(uncompressed) {
3296
+ return LZString._compress(uncompressed, 16, function(a) {
3297
+ return f(a);
3298
+ });
3299
+ },
3300
+ _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
3301
+ if (uncompressed == null) return "";
3302
+ 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;
3303
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
3304
+ context_c = uncompressed.charAt(ii);
3305
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
3306
+ context_dictionary[context_c] = context_dictSize++;
3307
+ context_dictionaryToCreate[context_c] = true;
3308
+ }
3309
+ context_wc = context_w + context_c;
3310
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
3311
+ else {
3312
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3313
+ if (context_w.charCodeAt(0) < 256) {
3314
+ for (i = 0; i < context_numBits; i++) {
3315
+ context_data_val = context_data_val << 1;
3316
+ if (context_data_position == bitsPerChar - 1) {
3317
+ context_data_position = 0;
3318
+ context_data.push(getCharFromInt(context_data_val));
3319
+ context_data_val = 0;
3320
+ } else context_data_position++;
3321
+ }
3322
+ value = context_w.charCodeAt(0);
3323
+ for (i = 0; i < 8; i++) {
3324
+ context_data_val = context_data_val << 1 | value & 1;
3325
+ if (context_data_position == bitsPerChar - 1) {
3326
+ context_data_position = 0;
3327
+ context_data.push(getCharFromInt(context_data_val));
3328
+ context_data_val = 0;
3329
+ } else context_data_position++;
3330
+ value = value >> 1;
3331
+ }
3332
+ } else {
3333
+ value = 1;
3334
+ for (i = 0; i < context_numBits; i++) {
3335
+ context_data_val = context_data_val << 1 | value;
3336
+ if (context_data_position == bitsPerChar - 1) {
3337
+ context_data_position = 0;
3338
+ context_data.push(getCharFromInt(context_data_val));
3339
+ context_data_val = 0;
3340
+ } else context_data_position++;
3341
+ value = 0;
3342
+ }
3343
+ value = context_w.charCodeAt(0);
3344
+ for (i = 0; i < 16; i++) {
3345
+ context_data_val = context_data_val << 1 | value & 1;
3346
+ if (context_data_position == bitsPerChar - 1) {
3347
+ context_data_position = 0;
3348
+ context_data.push(getCharFromInt(context_data_val));
3349
+ context_data_val = 0;
3350
+ } else context_data_position++;
3351
+ value = value >> 1;
3352
+ }
3353
+ }
3354
+ context_enlargeIn--;
3355
+ if (context_enlargeIn == 0) {
3356
+ context_enlargeIn = Math.pow(2, context_numBits);
3357
+ context_numBits++;
3358
+ }
3359
+ delete context_dictionaryToCreate[context_w];
3360
+ } else {
3361
+ value = context_dictionary[context_w];
3362
+ for (i = 0; i < context_numBits; i++) {
3363
+ context_data_val = context_data_val << 1 | value & 1;
3364
+ if (context_data_position == bitsPerChar - 1) {
3365
+ context_data_position = 0;
3366
+ context_data.push(getCharFromInt(context_data_val));
3367
+ context_data_val = 0;
3368
+ } else context_data_position++;
3369
+ value = value >> 1;
3370
+ }
3371
+ }
3372
+ context_enlargeIn--;
3373
+ if (context_enlargeIn == 0) {
3374
+ context_enlargeIn = Math.pow(2, context_numBits);
3375
+ context_numBits++;
3376
+ }
3377
+ context_dictionary[context_wc] = context_dictSize++;
3378
+ context_w = String(context_c);
3379
+ }
3380
+ }
3381
+ if (context_w !== "") {
3382
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3383
+ if (context_w.charCodeAt(0) < 256) {
3384
+ for (i = 0; i < context_numBits; i++) {
3385
+ context_data_val = context_data_val << 1;
3386
+ if (context_data_position == bitsPerChar - 1) {
3387
+ context_data_position = 0;
3388
+ context_data.push(getCharFromInt(context_data_val));
3389
+ context_data_val = 0;
3390
+ } else context_data_position++;
3391
+ }
3392
+ value = context_w.charCodeAt(0);
3393
+ for (i = 0; i < 8; i++) {
3394
+ context_data_val = context_data_val << 1 | value & 1;
3395
+ if (context_data_position == bitsPerChar - 1) {
3396
+ context_data_position = 0;
3397
+ context_data.push(getCharFromInt(context_data_val));
3398
+ context_data_val = 0;
3399
+ } else context_data_position++;
3400
+ value = value >> 1;
3401
+ }
3402
+ } else {
3403
+ value = 1;
3404
+ for (i = 0; i < context_numBits; i++) {
3405
+ context_data_val = context_data_val << 1 | value;
3406
+ if (context_data_position == bitsPerChar - 1) {
3407
+ context_data_position = 0;
3408
+ context_data.push(getCharFromInt(context_data_val));
3409
+ context_data_val = 0;
3410
+ } else context_data_position++;
3411
+ value = 0;
3412
+ }
3413
+ value = context_w.charCodeAt(0);
3414
+ for (i = 0; i < 16; i++) {
3415
+ context_data_val = context_data_val << 1 | value & 1;
3416
+ if (context_data_position == bitsPerChar - 1) {
3417
+ context_data_position = 0;
3418
+ context_data.push(getCharFromInt(context_data_val));
3419
+ context_data_val = 0;
3420
+ } else context_data_position++;
3421
+ value = value >> 1;
3422
+ }
3423
+ }
3424
+ context_enlargeIn--;
3425
+ if (context_enlargeIn == 0) {
3426
+ context_enlargeIn = Math.pow(2, context_numBits);
3427
+ context_numBits++;
3428
+ }
3429
+ delete context_dictionaryToCreate[context_w];
3430
+ } else {
3431
+ value = context_dictionary[context_w];
3432
+ for (i = 0; i < context_numBits; i++) {
3433
+ context_data_val = context_data_val << 1 | value & 1;
3434
+ if (context_data_position == bitsPerChar - 1) {
3435
+ context_data_position = 0;
3436
+ context_data.push(getCharFromInt(context_data_val));
3437
+ context_data_val = 0;
3438
+ } else context_data_position++;
3439
+ value = value >> 1;
3440
+ }
3441
+ }
3442
+ context_enlargeIn--;
3443
+ if (context_enlargeIn == 0) {
3444
+ context_enlargeIn = Math.pow(2, context_numBits);
3445
+ context_numBits++;
3446
+ }
3447
+ }
3448
+ value = 2;
3449
+ for (i = 0; i < context_numBits; i++) {
3450
+ context_data_val = context_data_val << 1 | value & 1;
3451
+ if (context_data_position == bitsPerChar - 1) {
3452
+ context_data_position = 0;
3453
+ context_data.push(getCharFromInt(context_data_val));
3454
+ context_data_val = 0;
3455
+ } else context_data_position++;
3456
+ value = value >> 1;
3457
+ }
3458
+ while (true) {
3459
+ context_data_val = context_data_val << 1;
3460
+ if (context_data_position == bitsPerChar - 1) {
3461
+ context_data.push(getCharFromInt(context_data_val));
3462
+ break;
3463
+ } else context_data_position++;
3464
+ }
3465
+ return context_data.join("");
3466
+ },
3467
+ decompress: function(compressed) {
3468
+ if (compressed == null) return "";
3469
+ if (compressed == "") return null;
3470
+ return LZString._decompress(compressed.length, 32768, function(index) {
3471
+ return compressed.charCodeAt(index);
3472
+ });
3473
+ },
3474
+ _decompress: function(length, resetValue, getNextValue) {
3475
+ var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
3476
+ val: getNextValue(0),
3477
+ position: resetValue,
3478
+ index: 1
3479
+ };
3480
+ for (i = 0; i < 3; i += 1) dictionary[i] = i;
3481
+ bits = 0;
3482
+ maxpower = Math.pow(2, 2);
3483
+ power = 1;
3484
+ while (power != maxpower) {
3485
+ resb = data.val & data.position;
3486
+ data.position >>= 1;
3487
+ if (data.position == 0) {
3488
+ data.position = resetValue;
3489
+ data.val = getNextValue(data.index++);
3490
+ }
3491
+ bits |= (resb > 0 ? 1 : 0) * power;
3492
+ power <<= 1;
3493
+ }
3494
+ switch (bits) {
3495
+ case 0:
3496
+ bits = 0;
3497
+ maxpower = Math.pow(2, 8);
3498
+ power = 1;
3499
+ while (power != maxpower) {
3500
+ resb = data.val & data.position;
3501
+ data.position >>= 1;
3502
+ if (data.position == 0) {
3503
+ data.position = resetValue;
3504
+ data.val = getNextValue(data.index++);
3505
+ }
3506
+ bits |= (resb > 0 ? 1 : 0) * power;
3507
+ power <<= 1;
3508
+ }
3509
+ c = f(bits);
3510
+ break;
3511
+ case 1:
3512
+ bits = 0;
3513
+ maxpower = Math.pow(2, 16);
3514
+ power = 1;
3515
+ while (power != maxpower) {
3516
+ resb = data.val & data.position;
3517
+ data.position >>= 1;
3518
+ if (data.position == 0) {
3519
+ data.position = resetValue;
3520
+ data.val = getNextValue(data.index++);
3521
+ }
3522
+ bits |= (resb > 0 ? 1 : 0) * power;
3523
+ power <<= 1;
3524
+ }
3525
+ c = f(bits);
3526
+ break;
3527
+ case 2: return "";
3528
+ }
3529
+ dictionary[3] = c;
3530
+ w = c;
3531
+ result.push(c);
3532
+ while (true) {
3533
+ if (data.index > length) return "";
3534
+ bits = 0;
3535
+ maxpower = Math.pow(2, numBits);
3536
+ power = 1;
3537
+ while (power != maxpower) {
3538
+ resb = data.val & data.position;
3539
+ data.position >>= 1;
3540
+ if (data.position == 0) {
3541
+ data.position = resetValue;
3542
+ data.val = getNextValue(data.index++);
3543
+ }
3544
+ bits |= (resb > 0 ? 1 : 0) * power;
3545
+ power <<= 1;
3546
+ }
3547
+ switch (c = bits) {
3548
+ case 0:
3549
+ bits = 0;
3550
+ maxpower = Math.pow(2, 8);
3551
+ power = 1;
3552
+ while (power != maxpower) {
3553
+ resb = data.val & data.position;
3554
+ data.position >>= 1;
3555
+ if (data.position == 0) {
3556
+ data.position = resetValue;
3557
+ data.val = getNextValue(data.index++);
3558
+ }
3559
+ bits |= (resb > 0 ? 1 : 0) * power;
3560
+ power <<= 1;
3561
+ }
3562
+ dictionary[dictSize++] = f(bits);
3563
+ c = dictSize - 1;
3564
+ enlargeIn--;
3565
+ break;
3566
+ case 1:
3567
+ bits = 0;
3568
+ maxpower = Math.pow(2, 16);
3569
+ power = 1;
3570
+ while (power != maxpower) {
3571
+ resb = data.val & data.position;
3572
+ data.position >>= 1;
3573
+ if (data.position == 0) {
3574
+ data.position = resetValue;
3575
+ data.val = getNextValue(data.index++);
3576
+ }
3577
+ bits |= (resb > 0 ? 1 : 0) * power;
3578
+ power <<= 1;
3579
+ }
3580
+ dictionary[dictSize++] = f(bits);
3581
+ c = dictSize - 1;
3582
+ enlargeIn--;
3583
+ break;
3584
+ case 2: return result.join("");
3585
+ }
3586
+ if (enlargeIn == 0) {
3587
+ enlargeIn = Math.pow(2, numBits);
3588
+ numBits++;
3589
+ }
3590
+ if (dictionary[c]) entry = dictionary[c];
3591
+ else if (c === dictSize) entry = w + w.charAt(0);
3592
+ else return null;
3593
+ result.push(entry);
3594
+ dictionary[dictSize++] = w + entry.charAt(0);
3595
+ enlargeIn--;
3596
+ w = entry;
3597
+ if (enlargeIn == 0) {
3598
+ enlargeIn = Math.pow(2, numBits);
3599
+ numBits++;
3600
+ }
3601
+ }
3602
+ }
3603
+ };
3604
+ return LZString;
3605
+ })();
3606
+ if (typeof define === "function" && define.amd) define(function() {
3607
+ return LZString;
3139
3608
  });
3140
- const targetUnsetter = n$1(() => setIsDropTarget(false), {
3141
- triggerAt: "start",
3142
- minQuietPeriodMs: 100
3609
+ else if (typeof module !== "undefined" && module != null) module.exports = LZString;
3610
+ else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
3611
+ return LZString;
3143
3612
  });
3144
- function setTarget() {
3145
- if (!isDragAndDropEnabled) return;
3146
- targetUnsetter.cancel();
3147
- targetSetter.call();
3148
- }
3149
- function unsetTarget() {
3150
- if (!isDragAndDropEnabled) return;
3151
- targetSetter.cancel();
3152
- targetUnsetter.call();
3153
- }
3154
- return {
3155
- isDropTarget,
3156
- setTarget,
3157
- unsetTarget
3158
- };
3159
- }
3160
- const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3161
- const useDraggingNode = draggingNodeEventFunctions.useValue;
3162
- const setDraggingNode = draggingNodeEventFunctions.setValue;
3163
- draggingNodeEventFunctions.addEventHandler;
3164
- const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3165
- reducer: (_, newNode) => newNode,
3166
- triggerAt: "start",
3167
- minQuietPeriodMs: 100
3168
- });
3169
- const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3170
- triggerAt: "start",
3171
- minQuietPeriodMs: 100
3172
- });
3173
- function setDragging(node) {
3174
- draggingNodeUnsetter.cancel();
3175
- draggingNodeSetter.call(node);
3176
- }
3177
- function unsetDragging() {
3178
- draggingNodeSetter.cancel();
3179
- draggingNodeUnsetter.call();
3180
- }
3181
- 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));
3182
- function useDragNode(args) {
3183
- const { srcId, parentId } = args;
3184
- const driveId = useSelectedDriveId();
3185
- const draggingNodeId = useDraggingNode()?.srcId;
3186
- const params = {
3187
- driveId,
3188
- srcId,
3189
- parentId
3190
- };
3191
- const draggable = isNodeDrag(params);
3192
- const isDragging = t$4({
3193
- srcId,
3194
- draggingNodeId
3195
- }, [
3196
- () => draggable,
3197
- ({ srcId }) => e$2(srcId),
3198
- ({ draggingNodeId }) => e$2(draggingNodeId),
3199
- ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3200
- ]);
3201
- const onDragStart = () => {
3202
- if (!draggable) return;
3203
- setDragging(params);
3204
- };
3205
- const onDragEnd = () => {
3206
- if (!draggable) return;
3207
- unsetDragging();
3208
- };
3209
- return {
3210
- isDragging,
3211
- draggable,
3212
- onDragStart,
3213
- onDragEnd
3214
- };
3215
- }
3216
- 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));
3217
- function useDropNode(targetId) {
3218
- const driveId = useSelectedDriveId();
3219
- const { srcId, parentId } = useDraggingNode() ?? {};
3220
- const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3221
- const params = {
3222
- driveId,
3223
- parentId,
3224
- targetId,
3225
- srcId
3226
- };
3227
- function handleNodeDrop(event, cb) {
3228
- if (!isNodeDrop(params)) return;
3229
- event.preventDefault();
3230
- event.stopPropagation();
3231
- cb?.();
3232
- }
3233
- const onDragEnter = (event) => handleNodeDrop(event);
3234
- const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3235
- const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3236
- const onDrop = (event) => handleNodeDrop(event, e(() => {
3237
- unsetDragging();
3238
- unsetTarget();
3239
- moveNodeById(params).catch(console.error);
3240
- }));
3241
- return {
3242
- isDropTarget,
3243
- onDragEnter,
3244
- onDragOver,
3245
- onDragLeave,
3246
- onDrop
3247
- };
3248
- }
3249
- const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3250
- graphQLReactorClientEventFunctions.useValue;
3251
- graphQLReactorClientEventFunctions.setValue;
3252
- graphQLReactorClientEventFunctions.addEventHandler;
3253
- const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3254
- packageDiscoveryFunctions.useValue;
3255
- packageDiscoveryFunctions.setValue;
3256
- packageDiscoveryFunctions.addEventHandler;
3257
- const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3258
- const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3259
- /** Returns the reactor client module (in-process or worker-backed) */
3260
- const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3261
- reactorClientModuleEventFunctions.setValue;
3262
- reactorClientModuleEventFunctions.addEventHandler;
3263
- reactorClientEventFunctions.useValue;
3264
- reactorClientEventFunctions.setValue;
3265
- reactorClientEventFunctions.addEventHandler;
3266
- const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3267
- const useSyncList = () => {
3268
- return useSync()?.list() ?? [];
3269
- };
3270
- const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3271
- revisionHistoryEventFunctions.useValue;
3272
- /** Sets revision history visibility */
3273
- const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3274
- revisionHistoryEventFunctions.addEventHandler;
3275
- /** Shows the revision history */
3276
- function showRevisionHistory() {
3277
- setRevisionHistoryVisible(true);
3278
- }
3279
- /** Sorts nodes by name. */
3280
- function sortNodesByName(nodes) {
3281
- return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
3282
- }
3283
- /** Returns whether a node is a file. */
3284
- function isFileNodeKind(node) {
3285
- if (!node) return false;
3286
- return node.kind.toUpperCase() === "FILE";
3287
- }
3288
- /** Returns whether a node is a folder. */
3289
- function isFolderNodeKind(node) {
3290
- if (!node) return false;
3291
- return node.kind.toUpperCase() === "FOLDER";
3292
- }
3293
- /** Returns the nodes in the selected drive. */
3294
- function useNodesInSelectedDrive() {
3295
- const [selectedDrive] = useSelectedDriveSafe();
3296
- return selectedDrive?.state.global.nodes;
3297
- }
3298
- /** Returns the folder nodes in the selected drive. */
3299
- function useFolderNodesInSelectedDrive() {
3300
- return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
3301
- }
3302
- /** Returns the selected node. */
3303
- function useSelectedNode() {
3304
- const selectedNodeId = useSelectedNodeId();
3305
- return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3306
- }
3307
- const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3308
- selectedTimelineItemEventFunctions.useValue;
3309
- selectedTimelineItemEventFunctions.setValue;
3310
- selectedTimelineItemEventFunctions.addEventHandler;
3311
- const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3312
- selectedTimelineRevisionEventFunctions.useValue;
3313
- selectedTimelineRevisionEventFunctions.setValue;
3314
- selectedTimelineRevisionEventFunctions.addEventHandler;
3315
- const toastEventFunctions = makePHEventFunctions("toast");
3316
- /** Returns the toast function */
3317
- const usePHToast = toastEventFunctions.useValue;
3318
- toastEventFunctions.setValue;
3319
- toastEventFunctions.addEventHandler;
3320
- const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
3321
- const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
3322
- /** Returns all of the Vetra packages loaded by the Connect instance */
3323
- const useVetraPackages = () => {
3324
- const packageManager = useVetraPackageManager();
3325
- return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
3326
- };
3327
- vetraPackageManagerFunctions.addEventHandler;
3328
- function useDocumentModelModules() {
3329
- 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);
3330
- }
3331
- function useDocumentModelModuleById(id) {
3332
- return useDocumentModelModules()?.find((module) => module.documentModel.global.id === id);
3333
- }
3613
+ })))(), 1);
3614
+ /** Document types that represent a "drive": a container of nodes. */
3615
+ const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
3334
3616
  function useAllowedDocumentModelModules() {
3335
3617
  const documentModelModules = useDocumentModelModules();
3336
3618
  const allowedDocumentTypes = useAllowedDocumentTypes();
@@ -3406,6 +3688,50 @@ function useDocumentOfType(documentId, documentType) {
3406
3688
  if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);
3407
3689
  return [document, dispatch];
3408
3690
  }
3691
+ /**
3692
+ * Classifies a document's model version against the installed module
3693
+ * versions. Pure logic, extracted for testing.
3694
+ */
3695
+ function getDocumentVersionStatus(documentVersion, availableVersions, hasUpgradePath) {
3696
+ if (availableVersions.length === 0) return;
3697
+ const sorted = [...availableVersions].sort((a, b) => a - b);
3698
+ const latestVersion = sorted[sorted.length - 1];
3699
+ if (documentVersion > latestVersion) return {
3700
+ kind: "unsupported",
3701
+ documentVersion,
3702
+ availableVersions: sorted
3703
+ };
3704
+ if (documentVersion === latestVersion) return {
3705
+ kind: "current",
3706
+ documentVersion
3707
+ };
3708
+ return {
3709
+ kind: "upgrade-available",
3710
+ documentVersion,
3711
+ latestVersion,
3712
+ canUpgrade: hasUpgradePath(documentVersion, latestVersion)
3713
+ };
3714
+ }
3715
+ /**
3716
+ * Compares the given document's model version against the versions available
3717
+ * from installed Vetra packages. Returns undefined while packages load or
3718
+ * when the document type has no installed modules.
3719
+ */
3720
+ function useDocumentVersionStatus(document) {
3721
+ const modules = useDocumentModelModules();
3722
+ const registry = useModelRegistry();
3723
+ if (!document || !modules) return;
3724
+ const documentType = document.header.documentType;
3725
+ return getDocumentVersionStatus(document.state.document.version || 1, modules.filter((m) => m.documentModel.global.id === documentType).map((m) => m.version ?? 1), (fromVersion, toVersion) => {
3726
+ if (!registry) return false;
3727
+ try {
3728
+ registry.computeUpgradePath(documentType, fromVersion, toVersion);
3729
+ return true;
3730
+ } catch {
3731
+ return false;
3732
+ }
3733
+ });
3734
+ }
3409
3735
  const validateDocument = (document) => {
3410
3736
  const errors = [];
3411
3737
  if (document.header.documentType !== "powerhouse/document-model") return errors;
@@ -3515,7 +3841,7 @@ function useNodeActions() {
3515
3841
  }
3516
3842
  async function onAddFolder(name, parent) {
3517
3843
  if (!selectedDriveId) return;
3518
- return addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3844
+ return addFolder$1(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3519
3845
  }
3520
3846
  async function onRenameNode(newName, node) {
3521
3847
  if (!selectedDriveId) return;
@@ -3602,6 +3928,9 @@ function useSelectedNodePath() {
3602
3928
  function useNodeParentFolderById(id) {
3603
3929
  return useFolderById(useNodeById(id)?.parentFolder);
3604
3930
  }
3931
+ function useParentFolderForSelectedNode() {
3932
+ return useNodeParentFolderById(useSelectedNode()?.id);
3933
+ }
3605
3934
  /** Returns the selected document id */
3606
3935
  function useSelectedDocumentId() {
3607
3936
  const selectedNode = useSelectedNode();
@@ -3830,6 +4159,6 @@ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOU
3830
4159
  createDebouncedRefreshReactorData();
3831
4160
  createDebouncedRefreshReactorDataClient();
3832
4161
  //#endregion
3833
- export { useSetPHDocumentEditorConfig as A, usePHToast as C, useSelectedDriveSafe as D, useSelectedDriveId as E, t$2 as F, t$5 as I, useDocumentById as L, useUserPermissions as M, e$1 as N, useSelectedNodePath as O, e$4 as P, useNodesInSelectedDriveOrFolder as S, useSelectedDocumentSafe as T, useEditorModulesForDocumentType as _, preloadEditorModule as a, useNodeById as b, showCreateDocumentModal as c, useAllowedDocumentModelModules as d, useDisabledEditors as f, useEditorModules as g, useDropNode as h, isFolderNodeKind as i, useTheme as j, useSetPHAppConfig as k, showDeleteNodeModal as l, useDragNode as m, getSyncStatusSync as n, setSelectedDrive as o, useDownloadDocument as p, isFileNodeKind as r, setSelectedNode as s, addFolder as t, showRevisionHistory as u, useGetSwitchboardLink as v, useSelectedDocumentOfType as w, useNodeParentFolderById as x, useNodeActions as y };
4162
+ export { showRevisionHistory as A, t$2 as B, addFolder$1 as C, setSelectedNode as D, setSelectedDrive as E, useSelectedDriveId as F, useDocumentById as H, useSelectedDriveSafe as I, useStudioMode as L, useDragNode as M, useDropNode as N, showDeleteNodeModal as O, usePHToast as P, e$1 as R, addDocument as S, isFolderNodeKind as T, t$5 as V, useSelectedNodePath as _, useDownloadDocument as a, useTheme as b, useGetSwitchboardLink as c, useNodeParentFolderById as d, useNodesInSelectedDriveOrFolder as f, useSelectedFolder as g, useSelectedDocumentSafe as h, useDocumentVersionStatus as i, useDisabledEditors as j, showPHModal as k, useNodeActions as l, useSelectedDocumentOfType as m, preloadEditorModule as n, useEditorModules as o, useParentFolderForSelectedNode as p, useAllowedDocumentModelModules as r, useEditorModulesForDocumentType as s, getSyncStatusSync as t, useNodeById as u, useSetPHAppConfig as v, isFileNodeKind as w, useUserPermissions as x, useSetPHDocumentEditorConfig as y, e$4 as z };
3834
4163
 
3835
- //# sourceMappingURL=dist-DJEK2WVi.mjs.map
4164
+ //# sourceMappingURL=dist-CRrgpr8A.mjs.map