@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.27 → 6.2.2-dev.28

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 (81) hide show
  1. package/dist/browser/assets/{entry-Bi_sLHEE.js → entry-Dk9VPWLt.js} +2 -2
  2. package/dist/browser/assets/{projection-entry-CIeJkB70.js → projection-entry-MT1aNJTP.js} +2 -2
  3. package/dist/browser/{connect-MUhMejvS.js → connect-BOSfrted.js} +6 -6
  4. package/dist/browser/{connect-MUhMejvS.js.map → connect-BOSfrted.js.map} +1 -1
  5. package/dist/browser/{dist-UIW3bhlu.js → dist-CetbB2Ax.js} +1562 -1449
  6. package/dist/browser/dist-CetbB2Ax.js.map +1 -0
  7. package/dist/browser/{dist-D8H48e8N.js → dist-D0oeNPlN.js} +1 -1
  8. package/dist/browser/{dist-D8H48e8N.js.map → dist-D0oeNPlN.js.map} +1 -1
  9. package/dist/browser/{document-drive-UzuiuvrS.js → document-drive-QCAIGn3V.js} +16 -3
  10. package/dist/browser/{document-drive-UzuiuvrS.js.map → document-drive-QCAIGn3V.js.map} +1 -1
  11. package/dist/browser/document-models/index.js +1 -1
  12. package/dist/browser/{documents-tEyvFm5w.js → documents-j_qy61X1.js} +22 -621
  13. package/dist/browser/documents-j_qy61X1.js.map +1 -0
  14. package/dist/browser/{editor-Bo7N28yK.js → editor-D6FPj2FU.js} +5 -5
  15. package/dist/browser/{editor-Bo7N28yK.js.map → editor-D6FPj2FU.js.map} +1 -1
  16. package/dist/browser/{editor-CBsDDo5E.js → editor-Dsx6DjlJ.js} +9 -9
  17. package/dist/browser/{editor-CBsDDo5E.js.map → editor-Dsx6DjlJ.js.map} +1 -1
  18. package/dist/browser/editors/document-model-editor/module.js +1 -1
  19. package/dist/browser/editors/generic-drive-explorer/index.js +10 -10
  20. package/dist/browser/editors/generic-drive-explorer/index.js.map +1 -1
  21. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  22. package/dist/browser/{folder-view-CqTIG-gR.js → folder-view-C91sPkD7.js} +4 -4
  23. package/dist/browser/{folder-view-CqTIG-gR.js.map → folder-view-C91sPkD7.js.map} +1 -1
  24. package/dist/browser/{graphql-editor-C3Bo3g1y.js → graphql-editor-CdHcSp6b.js} +7 -6
  25. package/dist/browser/{graphql-editor-C3Bo3g1y.js.map → graphql-editor-CdHcSp6b.js.map} +1 -1
  26. package/dist/browser/{hooks-BWFXCdBN.js → hooks-BgIeO-WG.js} +2 -2
  27. package/dist/browser/{hooks-BWFXCdBN.js.map → hooks-BgIeO-WG.js.map} +1 -1
  28. package/dist/browser/index.js +2 -2
  29. package/dist/browser/{json-editor-mGzyqHBe.js → json-editor-DjoNgrAU.js} +4 -4
  30. package/dist/browser/{json-editor-mGzyqHBe.js.map → json-editor-DjoNgrAU.js.map} +1 -1
  31. package/dist/browser/{lib-B5wuTyK2.js → lib-Dx4DRbGl.js} +2 -2
  32. package/dist/browser/lib-Dx4DRbGl.js.map +1 -0
  33. package/dist/browser/{linting-DCToEa_x.js → linting-nOwKxGXw.js} +5 -4
  34. package/dist/browser/{linting-DCToEa_x.js.map → linting-nOwKxGXw.js.map} +1 -1
  35. package/dist/browser/printer-CEYr4JOg.js +604 -0
  36. package/dist/browser/printer-CEYr4JOg.js.map +1 -0
  37. package/dist/browser/{schema-context-CM52_Uom.js → schema-context-ClCYFYSx.js} +2 -2
  38. package/dist/browser/{schema-context-CM52_Uom.js.map → schema-context-ClCYFYSx.js.map} +1 -1
  39. package/dist/browser/{state-schemas-DXvb34Vy.js → state-schemas-CnCO6lVC.js} +7 -7
  40. package/dist/browser/{state-schemas-DXvb34Vy.js.map → state-schemas-CnCO6lVC.js.map} +1 -1
  41. package/dist/node/{connect-Dtv8QYvd.mjs → connect-D143FXSc.mjs} +5 -5
  42. package/dist/node/{connect-Dtv8QYvd.mjs.map → connect-D143FXSc.mjs.map} +1 -1
  43. package/dist/node/{dist-B9dsmZOQ.mjs → dist-Ch3Oiwow.mjs} +1567 -1449
  44. package/dist/node/dist-Ch3Oiwow.mjs.map +1 -0
  45. package/dist/node/{document-drive-DwU-AM0j.mjs → document-drive-DIiMiIkb.mjs} +16 -3
  46. package/dist/node/document-drive-DIiMiIkb.mjs.map +1 -0
  47. package/dist/node/document-models/index.mjs +1 -1
  48. package/dist/node/{documents-DCf53bzO.mjs → documents-Bh_lxLTV.mjs} +19 -19
  49. package/dist/node/{documents-DCf53bzO.mjs.map → documents-Bh_lxLTV.mjs.map} +1 -1
  50. package/dist/node/{editor-CqiZG2jA.mjs → editor-CSaAlHLA.mjs} +5 -5
  51. package/dist/node/{editor-CqiZG2jA.mjs.map → editor-CSaAlHLA.mjs.map} +1 -1
  52. package/dist/node/{editor-BHPkhGRc.mjs → editor-vRgf2dWH.mjs} +8 -8
  53. package/dist/node/{editor-BHPkhGRc.mjs.map → editor-vRgf2dWH.mjs.map} +1 -1
  54. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  55. package/dist/node/editors/generic-drive-explorer/index.mjs +10 -10
  56. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  57. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  58. package/dist/node/{folder-view-C5Gyifq_.mjs → folder-view-DQzUtql7.mjs} +3 -3
  59. package/dist/node/{folder-view-C5Gyifq_.mjs.map → folder-view-DQzUtql7.mjs.map} +1 -1
  60. package/dist/node/{graphql-editor-Cn9kF4fN.mjs → graphql-editor-U_ps05vi.mjs} +5 -5
  61. package/dist/node/{graphql-editor-Cn9kF4fN.mjs.map → graphql-editor-U_ps05vi.mjs.map} +1 -1
  62. package/dist/node/{hooks-D0DcS3MV.mjs → hooks-B7KF2A2g.mjs} +2 -2
  63. package/dist/node/{hooks-D0DcS3MV.mjs.map → hooks-B7KF2A2g.mjs.map} +1 -1
  64. package/dist/node/index.mjs +2 -2
  65. package/dist/node/{json-editor-D5HFrby8.mjs → json-editor-DJ9KSSQo.mjs} +4 -4
  66. package/dist/node/{json-editor-D5HFrby8.mjs.map → json-editor-DJ9KSSQo.mjs.map} +1 -1
  67. package/dist/node/{linting-BjvRPjCY.mjs → linting-D6drcQHM.mjs} +4 -4
  68. package/dist/node/{linting-BjvRPjCY.mjs.map → linting-D6drcQHM.mjs.map} +1 -1
  69. package/dist/node/{main-_cmzLLxO.mjs → main-CfVS_PlH.mjs} +2 -2
  70. package/dist/node/main-CfVS_PlH.mjs.map +1 -0
  71. package/dist/node/{schema-context-DL8jhi_d.mjs → schema-context-pefmG2VW.mjs} +2 -2
  72. package/dist/node/{schema-context-DL8jhi_d.mjs.map → schema-context-pefmG2VW.mjs.map} +1 -1
  73. package/dist/node/{state-schemas-CS_nVqVI.mjs → state-schemas-BVvdNjMt.mjs} +6 -6
  74. package/dist/node/{state-schemas-CS_nVqVI.mjs.map → state-schemas-BVvdNjMt.mjs.map} +1 -1
  75. package/package.json +6 -6
  76. package/dist/browser/dist-UIW3bhlu.js.map +0 -1
  77. package/dist/browser/documents-tEyvFm5w.js.map +0 -1
  78. package/dist/browser/lib-B5wuTyK2.js.map +0 -1
  79. package/dist/node/dist-B9dsmZOQ.mjs.map +0 -1
  80. package/dist/node/document-drive-DwU-AM0j.mjs.map +0 -1
  81. package/dist/node/main-_cmzLLxO.mjs.map +0 -1
@@ -1,9 +1,11 @@
1
1
  import { A as __toESM, D as __commonJSMin, t as capitalCase } from "./dist-B4FWbuEM.js";
2
- import { J as validateInitialState, M as replayDocumentVersioned, V as setName, X as validateStateSchemaName, Y as validateModules, Z as generateId, _ as baseLoadFromInput, a as handleTargetNameCollisions, b as buildSignedAction, c as moveNode, d as logger, h as assertAuthPreservedOnDuplicate, i as generateNodesCopy, l as updateNode, n as copyNode, o as isFileNode, s as isFolderNode, t as addFolder$1, v as baseLoadFromInputVersioned, w as createZip, x as createPresignedHeader, y as baseSaveToFileHandle } from "./document-drive-UzuiuvrS.js";
3
- import { a as SyncStatus, o as DriveCollectionId, s as ModuleNotFoundError, t as gql } from "./lib-B5wuTyK2.js";
4
- import { Children, cloneElement, createContext, forwardRef, isValidElement, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
2
+ import { H as setName, N as replayDocumentVersioned, Q as generateId, X as validateModules, Y as validateInitialState, Z as validateStateSchemaName, _ as baseLoadFromInput, a as handleTargetNameCollisions, b as buildSignedAction, c as moveNode, d as logger, h as assertAuthPreservedOnDuplicate, i as generateNodesCopy, l as updateNode, n as copyNode, o as isFileNode, s as isFolderNode, t as addFolder, v as baseLoadFromInputVersioned, w as createZip, x as createPresignedHeader, y as baseSaveToFileHandle } from "./document-drive-QCAIGn3V.js";
3
+ import { a as SyncStatus, o as DriveCollectionId, s as ModuleNotFoundError, t as gql } from "./lib-Dx4DRbGl.js";
4
+ import "./parser-CkF6Qt8V.js";
5
+ import "./printer-CEYr4JOg.js";
6
+ import { createContext, use, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
5
7
  import "react/jsx-runtime";
6
- //#region ../reactor-browser/dist/make-ph-event-functions-BHoLPif5.js
8
+ //#region ../reactor-browser/dist/make-ph-event-functions-DBq3iWYn.js
7
9
  const isServer$1 = typeof window === "undefined";
8
10
  function makePHEventFunctions(key) {
9
11
  const setEventName = `ph:set${capitalCase(key)}`;
@@ -51,7 +53,7 @@ function makePHEventFunctions(key) {
51
53
  };
52
54
  }
53
55
  //#endregion
54
- //#region ../reactor-browser/dist/document-by-id-dLYFX-xz.js
56
+ //#region ../reactor-browser/dist/document-by-id-RNQCGkYh.js
55
57
  async function queueActions(document, actionOrActions) {
56
58
  if (!document) throw new Error("No document provided");
57
59
  if (!actionOrActions) throw new Error("No actions provided");
@@ -97,12 +99,12 @@ async function uploadOperations(documentId, allOperations, pushOperations, optio
97
99
  logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
98
100
  }
99
101
  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
102
  const renown = window.ph?.renown;
104
103
  if (!renown?.user) return action;
105
104
  if (!action.context?.signer) return action;
105
+ const reactorClient = window.ph?.reactorClientModule?.client;
106
+ if (!reactorClient) return action;
107
+ const reducer = (await reactorClient.getDocumentModelModule(document.header.documentType)).reducer;
106
108
  const actionSigner = action.context.signer;
107
109
  return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
108
110
  }
@@ -180,6 +182,21 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
180
182
  if (onSuccess && result) onSuccess(result);
181
183
  return result;
182
184
  }
185
+ /**
186
+ * The reactor's `DocumentChangeType` members, typed as the enum so they can be
187
+ * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
188
+ * TypeScript string enum is nominal, so no string literal is assignable to it
189
+ * without one - and the two checks above are what make it safe.
190
+ */
191
+ const DOCUMENT_CHANGE_TYPE = {
192
+ Created: "created",
193
+ Deleted: "deleted",
194
+ Updated: "updated",
195
+ ParentAdded: "parent_added",
196
+ ParentRemoved: "parent_removed",
197
+ ChildAdded: "child_added",
198
+ ChildRemoved: "child_removed"
199
+ };
183
200
  const documentEventFunctions = makePHEventFunctions("documentCache");
184
201
  /** Returns all documents in the reactor. */
185
202
  const useDocumentCache = documentEventFunctions.useValue;
@@ -225,8 +242,25 @@ function useDocumentById(id) {
225
242
  const [, dispatch] = useDispatch(document);
226
243
  return [document, dispatch];
227
244
  }
245
+ Error;
246
+ JSON;
228
247
  //#endregion
229
- //#region ../reactor-browser/dist/client-_Gh2Uf0E.js
248
+ //#region ../reactor-browser/dist/client-B1Af81HB.js
249
+ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
250
+ DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
251
+ DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
252
+ DocumentChangeType["Created"] = "CREATED";
253
+ DocumentChangeType["Deleted"] = "DELETED";
254
+ DocumentChangeType["ParentAdded"] = "PARENT_ADDED";
255
+ DocumentChangeType["ParentRemoved"] = "PARENT_REMOVED";
256
+ DocumentChangeType["Updated"] = "UPDATED";
257
+ return DocumentChangeType;
258
+ }({});
259
+ let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
260
+ PropagationMode["Cascade"] = "CASCADE";
261
+ PropagationMode["Orphan"] = "ORPHAN";
262
+ return PropagationMode;
263
+ }({});
230
264
  const PhDocumentFieldsFragmentDoc = gql`
231
265
  fragment PHDocumentFields on PHDocument {
232
266
  id
@@ -737,13 +771,8 @@ function extractQueryParts(doc, fallbackBody) {
737
771
  extractSelectionSet(GetDocumentOperationsDocument, "documentOperations", "{ items { index } }");
738
772
  extractQueryParts(GetDocumentDocument, "document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }");
739
773
  //#endregion
740
- //#region ../renown/dist/types-C_qc_62W.js
741
- const LoginMethod = {
742
- WALLET: "wallet",
743
- GOOGLE: "google",
744
- EMAIL: "email",
745
- APPLE: "apple"
746
- };
774
+ //#region ../reactor-browser/dist/renown-BZabzj4l.js
775
+ const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
747
776
  const RenownInitialUserContext = createContext({ state: "unknown" });
748
777
  /** First-render auth as a three-state value; use this to skip a spinner when anonymous. */
749
778
  function useRenownInitialAuth() {
@@ -753,7 +782,6 @@ function useRenownInitialUser() {
753
782
  const initial = useRenownInitialAuth();
754
783
  return initial.state === "authenticated" ? initial.user : void 0;
755
784
  }
756
- const { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions("loading");
757
785
  const renownEventFunctions = makePHEventFunctions("renown");
758
786
  renownEventFunctions.addEventHandler;
759
787
  /** Returns the renown instance */
@@ -773,36 +801,6 @@ function useUser() {
773
801
  }, [instance]);
774
802
  return instance ? user : initialUser ?? user;
775
803
  }
776
- Object.freeze([]);
777
- function mergeProps(parentProps, childProps) {
778
- const merged = { ...parentProps };
779
- for (const key of Object.keys(childProps)) {
780
- const parentValue = parentProps[key];
781
- const childValue = childProps[key];
782
- if (key === "style") merged[key] = {
783
- ...parentValue,
784
- ...childValue
785
- };
786
- else if (key === "className") merged[key] = [parentValue, childValue].filter(Boolean).join(" ");
787
- else if (typeof parentValue === "function" && typeof childValue === "function") merged[key] = (...args) => {
788
- childValue(...args);
789
- parentValue(...args);
790
- };
791
- else if (childValue !== void 0) merged[key] = childValue;
792
- }
793
- return merged;
794
- }
795
- const Slot = forwardRef(({ children, ...props }, ref) => {
796
- const child = Children.only(children);
797
- if (!isValidElement(child)) return null;
798
- const childElement = child;
799
- const mergedProps = mergeProps(props, childElement.props);
800
- if (ref) mergedProps.ref = ref;
801
- return cloneElement(childElement, mergedProps);
802
- });
803
- Slot.displayName = "Slot";
804
- createContext(false);
805
- LoginMethod.WALLET, LoginMethod.GOOGLE, LoginMethod.EMAIL, LoginMethod.APPLE;
806
804
  //#endregion
807
805
  //#region ../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js
808
806
  function e$8(e, t, n) {
@@ -927,6 +925,32 @@ function e(e) {
927
925
  let t = !1, n;
928
926
  return () => (t ||= (n = e(), !0), n);
929
927
  }
928
+ var CloseCode = /* @__PURE__ */ ((CloseCode2) => {
929
+ CloseCode2[CloseCode2["InternalServerError"] = 4500] = "InternalServerError";
930
+ CloseCode2[CloseCode2["InternalClientError"] = 4005] = "InternalClientError";
931
+ CloseCode2[CloseCode2["BadRequest"] = 4400] = "BadRequest";
932
+ CloseCode2[CloseCode2["BadResponse"] = 4004] = "BadResponse";
933
+ CloseCode2[CloseCode2["Unauthorized"] = 4401] = "Unauthorized";
934
+ CloseCode2[CloseCode2["Forbidden"] = 4403] = "Forbidden";
935
+ CloseCode2[CloseCode2["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
936
+ CloseCode2[CloseCode2["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
937
+ CloseCode2[CloseCode2["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
938
+ CloseCode2[CloseCode2["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
939
+ CloseCode2[CloseCode2["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
940
+ return CloseCode2;
941
+ })(CloseCode || {});
942
+ var MessageType = /* @__PURE__ */ ((MessageType2) => {
943
+ MessageType2["ConnectionInit"] = "connection_init";
944
+ MessageType2["ConnectionAck"] = "connection_ack";
945
+ MessageType2["Ping"] = "ping";
946
+ MessageType2["Pong"] = "pong";
947
+ MessageType2["Subscribe"] = "subscribe";
948
+ MessageType2["Next"] = "next";
949
+ MessageType2["Error"] = "error";
950
+ MessageType2["Complete"] = "complete";
951
+ return MessageType2;
952
+ })(MessageType || {});
953
+ Error;
930
954
  //#endregion
931
955
  //#region ../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js
932
956
  let base64;
@@ -1714,1076 +1738,450 @@ slug.setLocale = function(locale) {
1714
1738
  defaultLocale = locales[locale] || {};
1715
1739
  };
1716
1740
  //#endregion
1717
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
1718
- const normalizeDescriptors = (error) => {
1719
- CORE_ERROR_PROPS.forEach((propName) => {
1720
- normalizeDescriptor(error, propName);
1721
- });
1722
- };
1723
- const CORE_ERROR_PROPS = [
1724
- "name",
1725
- "message",
1726
- "stack",
1727
- "cause",
1728
- "errors"
1729
- ];
1730
- const normalizeDescriptor = (error, propName) => {
1731
- const descriptor = getDescriptor(error, propName);
1732
- if (descriptor === void 0) return;
1733
- if (isReadonlyGetter(descriptor)) {
1734
- setErrorProperty(error, propName, error[propName]);
1735
- return;
1741
+ //#region ../reactor-browser/dist/document-model-modules-B2_aAWc7.js
1742
+ var DocumentModelNotFoundError = class extends Error {
1743
+ documentType;
1744
+ name = "DocumentModelNotFoundError";
1745
+ constructor(documentType) {
1746
+ super(`Document model module for type ${documentType} not found`);
1747
+ this.documentType = documentType;
1748
+ }
1749
+ static isError(error) {
1750
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
1736
1751
  }
1737
- if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
1738
- };
1739
- const getDescriptor = (value, propName) => {
1740
- const descriptor = Object.getOwnPropertyDescriptor(value, propName);
1741
- if (descriptor !== void 0) return descriptor;
1742
- const prototype = Object.getPrototypeOf(value);
1743
- return prototype === null ? void 0 : getDescriptor(prototype, propName);
1744
- };
1745
- const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
1746
- const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
1747
- const setErrorProperty = (error, propName, value) => {
1748
- setErrorDescriptor(error, propName, { value });
1749
- };
1750
- const setErrorDescriptor = (error, propName, descriptor) => {
1751
- Object.defineProperty(error, propName, {
1752
- ...descriptor,
1753
- ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
1754
- enumerable: false,
1755
- configurable: true
1756
- });
1757
- };
1758
- //#endregion
1759
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
1760
- const normalizeAggregate = (error, recurse) => {
1761
- if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
1762
- else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
1763
- else if (error.errors !== void 0) deleteAggregateErrors(error);
1764
- };
1765
- const isDefined = (error) => error !== void 0;
1766
- const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
1767
- const deleteAggregateErrors = (error) => {
1768
- delete error.errors;
1769
- if (error.errors !== void 0) setErrorProperty(error, "errors", []);
1770
- };
1771
- //#endregion
1772
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
1773
- const normalizeCause = (error, recurse) => {
1774
- if (!("cause" in error)) return;
1775
- const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
1776
- if (cause === void 0) delete error.cause;
1777
- else setErrorProperty(error, "cause", cause);
1778
1752
  };
1779
- //#endregion
1780
- //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
1781
- const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
1782
- const isInstanceOfError = (value) => {
1783
- try {
1784
- return value instanceof Error;
1785
- } catch {
1786
- return false;
1753
+ var DocumentTypeMismatchError = class extends Error {
1754
+ constructor(documentId, expectedType, actualType) {
1755
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
1787
1756
  }
1788
1757
  };
1789
- const hasErrorTag = (value) => {
1790
- try {
1791
- return ERROR_TAGS.has(Object.prototype.toString.call(value));
1792
- } catch {
1793
- return false;
1758
+ var NoSelectedDocumentError = class extends Error {
1759
+ constructor() {
1760
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
1794
1761
  }
1795
1762
  };
1796
- const ERROR_TAGS = new Set([
1797
- "[object Error]",
1798
- "[object DOMException]",
1799
- "[object DOMError]",
1800
- "[object Exception]"
1801
- ]);
1802
- //#endregion
1803
- //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
1804
- function isPlainObject(value) {
1805
- if (typeof value !== "object" || value === null) return false;
1806
- const prototype = Object.getPrototypeOf(value);
1807
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
1763
+ function getUserPermissions() {
1764
+ const user = window.ph?.renown?.user;
1765
+ const allowList = window.ph?.allowList;
1766
+ if (!allowList) return {
1767
+ isAllowedToCreateDocuments: true,
1768
+ isAllowedToEditDocuments: true
1769
+ };
1770
+ return {
1771
+ isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
1772
+ isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
1773
+ };
1808
1774
  }
1809
- //#endregion
1810
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
1811
- const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
1812
- const isNonConfigurableProp = (error, propName) => {
1813
- const descriptor = Object.getOwnPropertyDescriptor(error, propName);
1814
- return descriptor !== void 0 && !descriptor.configurable;
1815
- };
1816
- const isThrowingProp = (error, propName) => {
1775
+ const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
1776
+ async function downloadFile(document, fileName) {
1817
1777
  try {
1818
- error[propName];
1819
- return false;
1820
- } catch {
1821
- return true;
1778
+ const data = await createZip(document);
1779
+ const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
1780
+ const link = window.document.createElement("a");
1781
+ link.style.display = "none";
1782
+ link.href = URL.createObjectURL(blob);
1783
+ link.download = fileName;
1784
+ window.document.body.appendChild(link);
1785
+ link.click();
1786
+ window.document.body.removeChild(link);
1787
+ } catch (e) {
1788
+ logger.error(e instanceof Error ? e.message : String(e));
1822
1789
  }
1823
- };
1824
- //#endregion
1825
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
1826
- const setStack = (error) => {
1827
- setErrorProperty(error, "stack", getStack(error.message, error.name));
1828
- };
1829
- const getStack = (message = "", name = "Error") => {
1830
- const { stack } = new (getErrorClass(name))(message);
1831
- return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
1832
- };
1833
- const getErrorClass = (name) => {
1834
- const descriptor = {
1835
- value: name,
1836
- enumerable: false,
1837
- writable: true,
1838
- configurable: true
1839
- };
1840
- const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
1841
- Object.defineProperty(StackError.prototype, "name", descriptor);
1842
- return StackError;
1843
- };
1844
- //#endregion
1845
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
1846
- const copyObject = (object) => {
1847
- const objectCopy = {};
1848
- for (const propName of getPropsToCopy(object)) try {
1849
- const value = object[propName];
1850
- const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
1851
- Object.defineProperty(objectCopy, propName, {
1852
- value,
1853
- enumerable,
1854
- configurable,
1855
- writable
1790
+ }
1791
+ async function getDocumentExtension(document) {
1792
+ const documentType = document.header.documentType;
1793
+ let rawExtension;
1794
+ if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
1795
+ else {
1796
+ const reactorClient = window.ph?.reactorClientModule?.client;
1797
+ if (reactorClient) {
1798
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
1799
+ rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
1800
+ }
1801
+ }
1802
+ return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
1803
+ }
1804
+ /**
1805
+ * Fetches all operations for a document using cursor-based pagination.
1806
+ * The reactor client handles multi-scope cursors transparently via
1807
+ * composite cursors, so all scopes are fetched in a single paginated stream.
1808
+ */
1809
+ async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
1810
+ const scopes = Object.keys(document.state);
1811
+ const operations = {};
1812
+ for (const scope of scopes) operations[scope] = [];
1813
+ let cursor = "";
1814
+ do {
1815
+ const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
1816
+ cursor,
1817
+ limit: pageSize
1856
1818
  });
1857
- } catch {}
1858
- return objectCopy;
1859
- };
1860
- const getPropsToCopy = (object) => {
1861
- const propNames = getOwnKeys(object);
1862
- for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
1863
- return propNames;
1864
- };
1865
- const getOwnKeys = (object) => {
1819
+ for (const op of page.results) {
1820
+ const scope = op.action.scope ?? "global";
1821
+ if (operations[scope]) operations[scope].push(op);
1822
+ }
1823
+ cursor = page.nextCursor ?? "";
1824
+ } while (cursor);
1825
+ return operations;
1826
+ }
1827
+ function extractInitialState(documentScopeOps) {
1828
+ const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
1829
+ if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
1830
+ const input = upgradeOp.action.input;
1831
+ const initialState = input.initialState ?? input.state;
1832
+ if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
1833
+ return initialState;
1834
+ }
1835
+ function filterDomainOperations(operations) {
1836
+ return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
1837
+ }
1838
+ async function exportFile(document, suggestedName) {
1839
+ const reactorClient = window.ph?.reactorClient;
1840
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1841
+ const operations = await fetchDocumentOperations(reactorClient, document);
1842
+ const initialState = extractInitialState(operations["document"] ?? []);
1843
+ const documentWithOps = {
1844
+ ...document,
1845
+ operations,
1846
+ initialState
1847
+ };
1848
+ const extension = await getDocumentExtension(documentWithOps);
1849
+ const baseName = suggestedName || documentWithOps.header.name || "Untitled";
1850
+ const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
1851
+ if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
1866
1852
  try {
1867
- return Reflect.ownKeys(object);
1868
- } catch {
1869
- return [];
1853
+ const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
1854
+ await baseSaveToFileHandle(documentWithOps, fileHandle);
1855
+ return fileHandle;
1856
+ } catch (e) {
1857
+ if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
1870
1858
  }
1871
- };
1872
- const isInheritedProp = (object, propName) => {
1873
- try {
1874
- return propName in object && !Object.hasOwn(object, propName);
1875
- } catch {
1876
- return false;
1877
- }
1878
- };
1879
- //#endregion
1880
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
1881
- const objectifyError = (object) => {
1882
- const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
1883
- const messageA = getMessage(message, objectA);
1884
- const error = newError(name, messageA);
1885
- if (message === messageA) assignObjectProps(error, objectA);
1886
- Object.entries({
1887
- name,
1888
- stack,
1889
- cause,
1890
- errors
1891
- }).forEach(([propName, propValue]) => {
1892
- setNewErrorProperty(error, propName, propValue);
1859
+ }
1860
+ /**
1861
+ * Loads a document file and replays it with version-aware reducers from the registry.
1862
+ * Falls back to single-version legacy replay when no upgrade manifest is registered for
1863
+ * the document type.
1864
+ */
1865
+ async function loadFile(path) {
1866
+ const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
1867
+ const reactorClient = window.ph?.reactorClientModule?.client;
1868
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1869
+ const documentType = baseDocument.header.documentType;
1870
+ const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
1871
+ const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
1872
+ if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
1873
+ const reducers = {};
1874
+ for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
1875
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
1876
+ let upgradeManifest;
1877
+ if (registry) try {
1878
+ upgradeManifest = registry.getUpgradeManifest(documentType);
1879
+ } catch {}
1880
+ return baseLoadFromInputVersioned(path, {
1881
+ reducers,
1882
+ upgradeManifest
1893
1883
  });
1894
- if (stack === void 0) setStack(error);
1895
- return error;
1896
- };
1897
- const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
1898
- const safeJsonStringify = (object) => {
1899
- try {
1900
- return JSON.stringify(object);
1901
- } catch {
1902
- return safeStringify(object);
1903
- }
1904
- };
1905
- const safeStringify = (object) => {
1884
+ }
1885
+ async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
1886
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1887
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
1888
+ const reactorClient = window.ph?.reactorClientModule?.client;
1889
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1890
+ const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
1891
+ const newDocument = document ?? documentModelModule.utils.createDocument();
1892
+ newDocument.header.name = name;
1893
+ if (preferredEditor) newDocument.header.meta = {
1894
+ ...newDocument.header.meta,
1895
+ preferredEditor
1896
+ };
1897
+ let newDoc;
1906
1898
  try {
1907
- return String(object);
1908
- } catch {
1909
- return "Invalid error";
1899
+ newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
1900
+ } catch (e) {
1901
+ logger.error("Error adding document: @error", e);
1902
+ throw new Error("There was an error adding document", { cause: e });
1910
1903
  }
1911
- };
1912
- const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
1913
- const MESSAGE_MAX_SIZE = 1e3;
1914
- const newError = (name, message) => {
1915
- if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
1916
- if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
1917
- return new Error(message);
1918
- };
1919
- const NATIVE_ERRORS = {
1920
- Error,
1921
- ReferenceError,
1922
- TypeError,
1923
- SyntaxError,
1924
- RangeError,
1925
- URIError,
1926
- EvalError
1927
- };
1928
- const assignObjectProps = (error, object) => {
1929
- for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
1930
- };
1931
- const setNewErrorProperty = (error, propName, propValue) => {
1932
- if (propValue !== void 0) setErrorProperty(error, propName, propValue);
1933
- };
1934
- //#endregion
1935
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
1936
- const stringifyError = (value) => {
1904
+ return {
1905
+ id: newDoc.header.id,
1906
+ name: newDoc.header.name,
1907
+ documentType,
1908
+ parentFolder: parentFolder ?? null,
1909
+ kind: "file"
1910
+ };
1911
+ }
1912
+ async function addFile(file, driveId, name, parentFolder) {
1913
+ logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
1914
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1915
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
1916
+ const document = await loadFile(file);
1917
+ let duplicateId = false;
1918
+ const reactorClient = window.ph?.reactorClient;
1919
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1937
1920
  try {
1938
- const error = new Error(String(value));
1939
- setStack(error);
1940
- return error;
1941
- } catch (error_) {
1942
- return error_;
1921
+ await reactorClient.get(document.header.id);
1922
+ duplicateId = true;
1923
+ } catch {}
1924
+ const documentId = duplicateId ? generateId() : document.header.id;
1925
+ const header = createPresignedHeader(documentId, document.header.documentType);
1926
+ header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
1927
+ header.meta = document.header.meta;
1928
+ header.name = name || document.header.name;
1929
+ const initialDocument = {
1930
+ ...document,
1931
+ header,
1932
+ state: document.initialState,
1933
+ operations: Object.keys(document.operations).reduce((acc, key) => {
1934
+ acc[key] = [];
1935
+ return acc;
1936
+ }, {})
1937
+ };
1938
+ await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
1939
+ await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
1940
+ }
1941
+ async function addFolder$1(driveId, name, parentFolder) {
1942
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1943
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
1944
+ const reactorClient = window.ph?.reactorClient;
1945
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1946
+ await reactorClient.get(driveId);
1947
+ const folderId = generateId();
1948
+ const node = (await reactorClient.execute(driveId, "main", [addFolder({
1949
+ id: folderId,
1950
+ name,
1951
+ parentFolder
1952
+ })])).state.global.nodes.find((node) => node.id === folderId);
1953
+ if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
1954
+ return node;
1955
+ }
1956
+ async function renameNode(driveId, nodeId, name) {
1957
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1958
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
1959
+ const reactorClient = window.ph?.reactorClient;
1960
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1961
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
1962
+ const node = (await reactorClient.execute(driveId, "main", [updateNode({
1963
+ id: nodeId,
1964
+ name
1965
+ })])).state.global.nodes.find((n) => n.id === nodeId);
1966
+ if (!node) throw new Error("There was an error renaming node in the drive");
1967
+ return node;
1968
+ }
1969
+ async function renameDriveNode(driveId, nodeId, name) {
1970
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1971
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
1972
+ const reactorClient = window.ph?.reactorClient;
1973
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1974
+ if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
1975
+ await reactorClient.execute(driveId, "main", [updateNode({
1976
+ id: nodeId,
1977
+ name
1978
+ })]);
1979
+ return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
1980
+ }
1981
+ async function moveNodeById(args) {
1982
+ const { driveId, srcId, targetId } = args;
1983
+ if (!driveId || !srcId) return;
1984
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1985
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
1986
+ const reactorClient = window.ph?.reactorClient;
1987
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
1988
+ const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
1989
+ if (t(targetParentFolder, srcId)) return;
1990
+ return await reactorClient.execute(driveId, "main", [moveNode({
1991
+ srcFolder: srcId,
1992
+ targetParentFolder
1993
+ })]);
1994
+ }
1995
+ async function moveNode$1(driveId, src, target) {
1996
+ const { isAllowedToCreateDocuments } = getUserPermissions();
1997
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
1998
+ const reactorClient = window.ph?.reactorClient;
1999
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
2000
+ return await reactorClient.execute(driveId, "main", [moveNode({
2001
+ srcFolder: src.id,
2002
+ targetParentFolder: target?.id
2003
+ })]);
2004
+ }
2005
+ /**
2006
+ * Duplicates a document under a new id using version-aware replay.
2007
+ * Falls back gracefully when no upgrade manifest is registered for the document type.
2008
+ */
2009
+ async function _duplicateDocument(reactor, document, newId = generateId()) {
2010
+ const documentType = document.header.documentType;
2011
+ const { results: allModules } = await reactor.getDocumentModelModules();
2012
+ const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2013
+ const reducers = {};
2014
+ for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2015
+ if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2016
+ const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2017
+ let upgradeManifest;
2018
+ if (registry) try {
2019
+ upgradeManifest = registry.getUpgradeManifest(documentType);
2020
+ } catch {}
2021
+ const config = {
2022
+ reducers,
2023
+ upgradeManifest
2024
+ };
2025
+ const header = createPresignedHeader(newId, documentType);
2026
+ const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2027
+ assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2028
+ return duplicated;
2029
+ }
2030
+ async function copyNode$1(driveId, src, target) {
2031
+ const reactor = window.ph?.reactorClientModule?.client;
2032
+ if (!reactor) return;
2033
+ const { isAllowedToCreateDocuments } = getUserPermissions();
2034
+ if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2035
+ const drive = await reactor.get(driveId);
2036
+ const copyNodesInput = generateNodesCopy({
2037
+ srcId: src.id,
2038
+ targetParentFolder: target?.id,
2039
+ targetName: src.name
2040
+ }, () => generateId(), drive.state.global.nodes);
2041
+ const resolvedNamesMap = /* @__PURE__ */ new Map();
2042
+ for (const copyNodeInput of copyNodesInput) {
2043
+ const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2044
+ if (node) {
2045
+ const resolvedName = handleTargetNameCollisions({
2046
+ nodes: drive.state.global.nodes,
2047
+ srcName: copyNodeInput.targetName || node.name,
2048
+ srcKind: isFileNode(node) ? "file" : "folder",
2049
+ targetParentFolder: copyNodeInput.targetParentFolder || null
2050
+ });
2051
+ resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2052
+ }
1943
2053
  }
1944
- };
1945
- //#endregion
1946
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
1947
- const { toString: objectToString } = Object.prototype;
1948
- const createError = (value) => {
1949
- if (isErrorPlainObj(value)) return objectifyError(value);
1950
- if (!isErrorInstance(value)) return stringifyError(value);
1951
- if (isInvalidError(value)) return objectifyError(value);
1952
- return value;
1953
- };
1954
- const isErrorPlainObj = (value) => {
1955
- try {
1956
- return isPlainObject(value);
1957
- } catch {
1958
- return false;
1959
- }
1960
- };
1961
- const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
1962
- const isProxy = (value) => {
1963
- try {
1964
- return objectToString.call(value) === "[object Object]";
1965
- } catch {
1966
- return true;
2054
+ const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2055
+ const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2056
+ return node !== void 0 && isFileNode(node);
2057
+ });
2058
+ for (const fileNodeToCopy of fileNodesToCopy) try {
2059
+ const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2060
+ const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2061
+ if (resolvedName) duplicatedDocument.header.name = resolvedName;
2062
+ await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2063
+ } catch (e) {
2064
+ logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
1967
2065
  }
2066
+ return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2067
+ }
2068
+ const modalEventFunctions = makePHEventFunctions("modal");
2069
+ modalEventFunctions.useValue;
2070
+ /** Sets the current modal */
2071
+ const setPHModal = modalEventFunctions.setValue;
2072
+ modalEventFunctions.addEventHandler;
2073
+ /** Shows a modal */
2074
+ function showPHModal(modal) {
2075
+ setPHModal(modal);
2076
+ }
2077
+ /** Shows the create document modal */
2078
+ function showCreateDocumentModal(documentType) {
2079
+ setPHModal({
2080
+ type: "createDocument",
2081
+ documentType
2082
+ });
2083
+ }
2084
+ /** Shows the delete node modal */
2085
+ function showDeleteNodeModal(nodeOrId) {
2086
+ setPHModal({
2087
+ type: "deleteItem",
2088
+ id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2089
+ });
2090
+ }
2091
+ gql`
2092
+ mutation MutateDocumentWithOperations(
2093
+ $documentIdentifier: String!
2094
+ $actions: [JSONObject!]!
2095
+ $view: ViewFilterInput
2096
+ $sinceRevision: Int
2097
+ $scopes: [String!]
2098
+ $branch: String
2099
+ ) {
2100
+ mutateDocument(
2101
+ documentIdentifier: $documentIdentifier
2102
+ actions: $actions
2103
+ view: $view
2104
+ ) {
2105
+ ...PHDocumentFields
2106
+ operations(
2107
+ filter: {
2108
+ sinceRevision: $sinceRevision
2109
+ scopes: $scopes
2110
+ branch: $branch
2111
+ }
2112
+ ) {
2113
+ items {
2114
+ ...ReactorOperationFields
2115
+ }
2116
+ }
2117
+ }
2118
+ }
2119
+ ${PhDocumentFieldsFragmentDoc}
2120
+ ${gql`
2121
+ fragment ReactorOperationFields on ReactorOperation {
2122
+ index
2123
+ timestampUtcMs
2124
+ hash
2125
+ skip
2126
+ error
2127
+ id
2128
+ action {
2129
+ id
2130
+ type
2131
+ timestampUtcMs
2132
+ input
2133
+ scope
2134
+ context {
2135
+ signer {
2136
+ user {
2137
+ address
2138
+ networkId
2139
+ chainId
2140
+ }
2141
+ app {
2142
+ name
2143
+ key
2144
+ }
2145
+ signatures
2146
+ }
2147
+ }
2148
+ }
2149
+ }
2150
+ `}
2151
+ `;
2152
+ 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;
2153
+ PropagationMode.Cascade, PropagationMode.Orphan;
2154
+ const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2155
+ /** Sets whether external controls are enabled for a given editor. */
2156
+ const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2157
+ /** Gets whether external controls are enabled for a given editor. */
2158
+ const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2159
+ isExternalControlsEnabledEventFunctions.addEventHandler;
2160
+ const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2161
+ /** Sets whether drag and drop is enabled for a given app. */
2162
+ const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2163
+ /** Gets whether drag and drop is enabled for a given app. */
2164
+ const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2165
+ isDragAndDropEnabledEventFunctions.addEventHandler;
2166
+ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2167
+ /** Sets the allowed document types for a given app. */
2168
+ const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2169
+ /** Defines the document types a drive supports.
2170
+ *
2171
+ * Defaults to all of the document types registered in the reactor.
2172
+ */
2173
+ function useAllowedDocumentTypes() {
2174
+ return allowedDocumentTypesEventFunctions.useValue();
2175
+ }
2176
+ allowedDocumentTypesEventFunctions.addEventHandler;
2177
+ const phAppConfigSetters = {
2178
+ allowedDocumentTypes: setAllowedDocumentTypes,
2179
+ isDragAndDropEnabled: setIsDragAndDropEnabled
1968
2180
  };
1969
- const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
1970
- //#endregion
1971
- //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
1972
- const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
1973
- const recurseException = (error, parents, shallow) => {
1974
- if (parents.includes(error)) return;
1975
- const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
1976
- const errorA = createError(error);
1977
- normalizeProps(errorA, recurse);
1978
- return errorA;
1979
- };
1980
- const identity = (error) => error;
1981
- const normalizeProps = (error, recurse) => {
1982
- normalizeName(error);
1983
- normalizeMessage(error);
1984
- normalizeStack(error);
1985
- normalizeCause(error, recurse);
1986
- normalizeAggregate(error, recurse);
1987
- normalizeDescriptors(error);
1988
- };
1989
- const normalizeName = (error) => {
1990
- if (isDefinedString(error.name)) return;
1991
- const prototypeName = Object.getPrototypeOf(error).name;
1992
- setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
1993
- };
1994
- const normalizeMessage = (error) => {
1995
- if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
1996
- };
1997
- const normalizeStack = (error) => {
1998
- if (!isDefinedString(error.stack)) setStack(error);
1999
- };
2000
- const isDefinedString = (value) => typeof value === "string" && value !== "";
2001
- //#endregion
2002
- //#region ../reactor-browser/dist/index.js
2003
- var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
2004
- var LZString = (function() {
2005
- var f = String.fromCharCode;
2006
- var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
2007
- var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
2008
- var baseReverseDic = {};
2009
- function getBaseValue(alphabet, character) {
2010
- if (!baseReverseDic[alphabet]) {
2011
- baseReverseDic[alphabet] = {};
2012
- for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
2013
- }
2014
- return baseReverseDic[alphabet][character];
2015
- }
2016
- var LZString = {
2017
- compressToBase64: function(input) {
2018
- if (input == null) return "";
2019
- var res = LZString._compress(input, 6, function(a) {
2020
- return keyStrBase64.charAt(a);
2021
- });
2022
- switch (res.length % 4) {
2023
- default:
2024
- case 0: return res;
2025
- case 1: return res + "===";
2026
- case 2: return res + "==";
2027
- case 3: return res + "=";
2028
- }
2029
- },
2030
- decompressFromBase64: function(input) {
2031
- if (input == null) return "";
2032
- if (input == "") return null;
2033
- return LZString._decompress(input.length, 32, function(index) {
2034
- return getBaseValue(keyStrBase64, input.charAt(index));
2035
- });
2036
- },
2037
- compressToUTF16: function(input) {
2038
- if (input == null) return "";
2039
- return LZString._compress(input, 15, function(a) {
2040
- return f(a + 32);
2041
- }) + " ";
2042
- },
2043
- decompressFromUTF16: function(compressed) {
2044
- if (compressed == null) return "";
2045
- if (compressed == "") return null;
2046
- return LZString._decompress(compressed.length, 16384, function(index) {
2047
- return compressed.charCodeAt(index) - 32;
2048
- });
2049
- },
2050
- compressToUint8Array: function(uncompressed) {
2051
- var compressed = LZString.compress(uncompressed);
2052
- var buf = new Uint8Array(compressed.length * 2);
2053
- for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
2054
- var current_value = compressed.charCodeAt(i);
2055
- buf[i * 2] = current_value >>> 8;
2056
- buf[i * 2 + 1] = current_value % 256;
2057
- }
2058
- return buf;
2059
- },
2060
- decompressFromUint8Array: function(compressed) {
2061
- if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
2062
- else {
2063
- var buf = new Array(compressed.length / 2);
2064
- for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
2065
- var result = [];
2066
- buf.forEach(function(c) {
2067
- result.push(f(c));
2068
- });
2069
- return LZString.decompress(result.join(""));
2070
- }
2071
- },
2072
- compressToEncodedURIComponent: function(input) {
2073
- if (input == null) return "";
2074
- return LZString._compress(input, 6, function(a) {
2075
- return keyStrUriSafe.charAt(a);
2076
- });
2077
- },
2078
- decompressFromEncodedURIComponent: function(input) {
2079
- if (input == null) return "";
2080
- if (input == "") return null;
2081
- input = input.replace(/ /g, "+");
2082
- return LZString._decompress(input.length, 32, function(index) {
2083
- return getBaseValue(keyStrUriSafe, input.charAt(index));
2084
- });
2085
- },
2086
- compress: function(uncompressed) {
2087
- return LZString._compress(uncompressed, 16, function(a) {
2088
- return f(a);
2089
- });
2090
- },
2091
- _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
2092
- if (uncompressed == null) return "";
2093
- 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;
2094
- for (ii = 0; ii < uncompressed.length; ii += 1) {
2095
- context_c = uncompressed.charAt(ii);
2096
- if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
2097
- context_dictionary[context_c] = context_dictSize++;
2098
- context_dictionaryToCreate[context_c] = true;
2099
- }
2100
- context_wc = context_w + context_c;
2101
- if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
2102
- else {
2103
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2104
- if (context_w.charCodeAt(0) < 256) {
2105
- for (i = 0; i < context_numBits; i++) {
2106
- context_data_val = context_data_val << 1;
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
- }
2113
- value = context_w.charCodeAt(0);
2114
- for (i = 0; i < 8; i++) {
2115
- context_data_val = context_data_val << 1 | value & 1;
2116
- if (context_data_position == bitsPerChar - 1) {
2117
- context_data_position = 0;
2118
- context_data.push(getCharFromInt(context_data_val));
2119
- context_data_val = 0;
2120
- } else context_data_position++;
2121
- value = value >> 1;
2122
- }
2123
- } else {
2124
- value = 1;
2125
- for (i = 0; i < context_numBits; i++) {
2126
- context_data_val = context_data_val << 1 | value;
2127
- if (context_data_position == bitsPerChar - 1) {
2128
- context_data_position = 0;
2129
- context_data.push(getCharFromInt(context_data_val));
2130
- context_data_val = 0;
2131
- } else context_data_position++;
2132
- value = 0;
2133
- }
2134
- value = context_w.charCodeAt(0);
2135
- for (i = 0; i < 16; i++) {
2136
- context_data_val = context_data_val << 1 | value & 1;
2137
- if (context_data_position == bitsPerChar - 1) {
2138
- context_data_position = 0;
2139
- context_data.push(getCharFromInt(context_data_val));
2140
- context_data_val = 0;
2141
- } else context_data_position++;
2142
- value = value >> 1;
2143
- }
2144
- }
2145
- context_enlargeIn--;
2146
- if (context_enlargeIn == 0) {
2147
- context_enlargeIn = Math.pow(2, context_numBits);
2148
- context_numBits++;
2149
- }
2150
- delete context_dictionaryToCreate[context_w];
2151
- } else {
2152
- value = context_dictionary[context_w];
2153
- for (i = 0; i < context_numBits; i++) {
2154
- context_data_val = context_data_val << 1 | value & 1;
2155
- if (context_data_position == bitsPerChar - 1) {
2156
- context_data_position = 0;
2157
- context_data.push(getCharFromInt(context_data_val));
2158
- context_data_val = 0;
2159
- } else context_data_position++;
2160
- value = value >> 1;
2161
- }
2162
- }
2163
- context_enlargeIn--;
2164
- if (context_enlargeIn == 0) {
2165
- context_enlargeIn = Math.pow(2, context_numBits);
2166
- context_numBits++;
2167
- }
2168
- context_dictionary[context_wc] = context_dictSize++;
2169
- context_w = String(context_c);
2170
- }
2171
- }
2172
- if (context_w !== "") {
2173
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
2174
- if (context_w.charCodeAt(0) < 256) {
2175
- for (i = 0; i < context_numBits; i++) {
2176
- context_data_val = context_data_val << 1;
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
- }
2183
- value = context_w.charCodeAt(0);
2184
- for (i = 0; i < 8; i++) {
2185
- context_data_val = context_data_val << 1 | value & 1;
2186
- if (context_data_position == bitsPerChar - 1) {
2187
- context_data_position = 0;
2188
- context_data.push(getCharFromInt(context_data_val));
2189
- context_data_val = 0;
2190
- } else context_data_position++;
2191
- value = value >> 1;
2192
- }
2193
- } else {
2194
- value = 1;
2195
- for (i = 0; i < context_numBits; i++) {
2196
- context_data_val = context_data_val << 1 | value;
2197
- if (context_data_position == bitsPerChar - 1) {
2198
- context_data_position = 0;
2199
- context_data.push(getCharFromInt(context_data_val));
2200
- context_data_val = 0;
2201
- } else context_data_position++;
2202
- value = 0;
2203
- }
2204
- value = context_w.charCodeAt(0);
2205
- for (i = 0; i < 16; i++) {
2206
- context_data_val = context_data_val << 1 | value & 1;
2207
- if (context_data_position == bitsPerChar - 1) {
2208
- context_data_position = 0;
2209
- context_data.push(getCharFromInt(context_data_val));
2210
- context_data_val = 0;
2211
- } else context_data_position++;
2212
- value = value >> 1;
2213
- }
2214
- }
2215
- context_enlargeIn--;
2216
- if (context_enlargeIn == 0) {
2217
- context_enlargeIn = Math.pow(2, context_numBits);
2218
- context_numBits++;
2219
- }
2220
- delete context_dictionaryToCreate[context_w];
2221
- } else {
2222
- value = context_dictionary[context_w];
2223
- for (i = 0; i < context_numBits; i++) {
2224
- context_data_val = context_data_val << 1 | value & 1;
2225
- if (context_data_position == bitsPerChar - 1) {
2226
- context_data_position = 0;
2227
- context_data.push(getCharFromInt(context_data_val));
2228
- context_data_val = 0;
2229
- } else context_data_position++;
2230
- value = value >> 1;
2231
- }
2232
- }
2233
- context_enlargeIn--;
2234
- if (context_enlargeIn == 0) {
2235
- context_enlargeIn = Math.pow(2, context_numBits);
2236
- context_numBits++;
2237
- }
2238
- }
2239
- value = 2;
2240
- for (i = 0; i < context_numBits; i++) {
2241
- context_data_val = context_data_val << 1 | value & 1;
2242
- if (context_data_position == bitsPerChar - 1) {
2243
- context_data_position = 0;
2244
- context_data.push(getCharFromInt(context_data_val));
2245
- context_data_val = 0;
2246
- } else context_data_position++;
2247
- value = value >> 1;
2248
- }
2249
- while (true) {
2250
- context_data_val = context_data_val << 1;
2251
- if (context_data_position == bitsPerChar - 1) {
2252
- context_data.push(getCharFromInt(context_data_val));
2253
- break;
2254
- } else context_data_position++;
2255
- }
2256
- return context_data.join("");
2257
- },
2258
- decompress: function(compressed) {
2259
- if (compressed == null) return "";
2260
- if (compressed == "") return null;
2261
- return LZString._decompress(compressed.length, 32768, function(index) {
2262
- return compressed.charCodeAt(index);
2263
- });
2264
- },
2265
- _decompress: function(length, resetValue, getNextValue) {
2266
- var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
2267
- val: getNextValue(0),
2268
- position: resetValue,
2269
- index: 1
2270
- };
2271
- for (i = 0; i < 3; i += 1) dictionary[i] = i;
2272
- bits = 0;
2273
- maxpower = Math.pow(2, 2);
2274
- power = 1;
2275
- while (power != maxpower) {
2276
- resb = data.val & data.position;
2277
- data.position >>= 1;
2278
- if (data.position == 0) {
2279
- data.position = resetValue;
2280
- data.val = getNextValue(data.index++);
2281
- }
2282
- bits |= (resb > 0 ? 1 : 0) * power;
2283
- power <<= 1;
2284
- }
2285
- switch (bits) {
2286
- case 0:
2287
- bits = 0;
2288
- maxpower = Math.pow(2, 8);
2289
- power = 1;
2290
- while (power != maxpower) {
2291
- resb = data.val & data.position;
2292
- data.position >>= 1;
2293
- if (data.position == 0) {
2294
- data.position = resetValue;
2295
- data.val = getNextValue(data.index++);
2296
- }
2297
- bits |= (resb > 0 ? 1 : 0) * power;
2298
- power <<= 1;
2299
- }
2300
- c = f(bits);
2301
- break;
2302
- case 1:
2303
- bits = 0;
2304
- maxpower = Math.pow(2, 16);
2305
- power = 1;
2306
- while (power != maxpower) {
2307
- resb = data.val & data.position;
2308
- data.position >>= 1;
2309
- if (data.position == 0) {
2310
- data.position = resetValue;
2311
- data.val = getNextValue(data.index++);
2312
- }
2313
- bits |= (resb > 0 ? 1 : 0) * power;
2314
- power <<= 1;
2315
- }
2316
- c = f(bits);
2317
- break;
2318
- case 2: return "";
2319
- }
2320
- dictionary[3] = c;
2321
- w = c;
2322
- result.push(c);
2323
- while (true) {
2324
- if (data.index > length) return "";
2325
- bits = 0;
2326
- maxpower = Math.pow(2, numBits);
2327
- power = 1;
2328
- while (power != maxpower) {
2329
- resb = data.val & data.position;
2330
- data.position >>= 1;
2331
- if (data.position == 0) {
2332
- data.position = resetValue;
2333
- data.val = getNextValue(data.index++);
2334
- }
2335
- bits |= (resb > 0 ? 1 : 0) * power;
2336
- power <<= 1;
2337
- }
2338
- switch (c = bits) {
2339
- case 0:
2340
- bits = 0;
2341
- maxpower = Math.pow(2, 8);
2342
- power = 1;
2343
- while (power != maxpower) {
2344
- resb = data.val & data.position;
2345
- data.position >>= 1;
2346
- if (data.position == 0) {
2347
- data.position = resetValue;
2348
- data.val = getNextValue(data.index++);
2349
- }
2350
- bits |= (resb > 0 ? 1 : 0) * power;
2351
- power <<= 1;
2352
- }
2353
- dictionary[dictSize++] = f(bits);
2354
- c = dictSize - 1;
2355
- enlargeIn--;
2356
- break;
2357
- case 1:
2358
- bits = 0;
2359
- maxpower = Math.pow(2, 16);
2360
- power = 1;
2361
- while (power != maxpower) {
2362
- resb = data.val & data.position;
2363
- data.position >>= 1;
2364
- if (data.position == 0) {
2365
- data.position = resetValue;
2366
- data.val = getNextValue(data.index++);
2367
- }
2368
- bits |= (resb > 0 ? 1 : 0) * power;
2369
- power <<= 1;
2370
- }
2371
- dictionary[dictSize++] = f(bits);
2372
- c = dictSize - 1;
2373
- enlargeIn--;
2374
- break;
2375
- case 2: return result.join("");
2376
- }
2377
- if (enlargeIn == 0) {
2378
- enlargeIn = Math.pow(2, numBits);
2379
- numBits++;
2380
- }
2381
- if (dictionary[c]) entry = dictionary[c];
2382
- else if (c === dictSize) entry = w + w.charAt(0);
2383
- else return null;
2384
- result.push(entry);
2385
- dictionary[dictSize++] = w + entry.charAt(0);
2386
- enlargeIn--;
2387
- w = entry;
2388
- if (enlargeIn == 0) {
2389
- enlargeIn = Math.pow(2, numBits);
2390
- numBits++;
2391
- }
2392
- }
2393
- }
2394
- };
2395
- return LZString;
2396
- })();
2397
- if (typeof define === "function" && define.amd) define(function() {
2398
- return LZString;
2399
- });
2400
- else if (typeof module !== "undefined" && module != null) module.exports = LZString;
2401
- else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
2402
- return LZString;
2403
- });
2404
- })))(), 1);
2405
- var DocumentModelNotFoundError = class extends Error {
2406
- documentType;
2407
- name = "DocumentModelNotFoundError";
2408
- constructor(documentType) {
2409
- super(`Document model module for type ${documentType} not found`);
2410
- this.documentType = documentType;
2411
- }
2412
- static isError(error) {
2413
- return Error.isError(error) && error.name === "DocumentModelNotFoundError";
2414
- }
2415
- };
2416
- var DocumentTypeMismatchError = class extends Error {
2417
- constructor(documentId, expectedType, actualType) {
2418
- super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
2419
- }
2420
- };
2421
- var NoSelectedDocumentError = class extends Error {
2422
- constructor() {
2423
- super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
2424
- }
2425
- };
2426
- function getUserPermissions() {
2427
- const user = window.ph?.renown?.user;
2428
- const allowList = window.ph?.allowList;
2429
- if (!allowList) return {
2430
- isAllowedToCreateDocuments: true,
2431
- isAllowedToEditDocuments: true
2432
- };
2433
- return {
2434
- isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
2435
- isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
2436
- };
2437
- }
2438
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
2439
- async function downloadFile(document, fileName) {
2440
- try {
2441
- const data = await createZip(document);
2442
- const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
2443
- const link = window.document.createElement("a");
2444
- link.style.display = "none";
2445
- link.href = URL.createObjectURL(blob);
2446
- link.download = fileName;
2447
- window.document.body.appendChild(link);
2448
- link.click();
2449
- window.document.body.removeChild(link);
2450
- } catch (e) {
2451
- logger.error(e instanceof Error ? e.message : String(e));
2452
- }
2453
- }
2454
- async function getDocumentExtension(document) {
2455
- const documentType = document.header.documentType;
2456
- let rawExtension;
2457
- if (documentType === "powerhouse/document-model") rawExtension = document.state.global?.extension;
2458
- else {
2459
- const reactorClient = window.ph?.reactorClient;
2460
- if (reactorClient) {
2461
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2462
- rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
2463
- }
2464
- }
2465
- return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
2466
- }
2467
- /**
2468
- * Fetches all operations for a document using cursor-based pagination.
2469
- * The reactor client handles multi-scope cursors transparently via
2470
- * composite cursors, so all scopes are fetched in a single paginated stream.
2471
- */
2472
- async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
2473
- const scopes = Object.keys(document.state);
2474
- const operations = {};
2475
- for (const scope of scopes) operations[scope] = [];
2476
- let cursor = "";
2477
- do {
2478
- const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
2479
- cursor,
2480
- limit: pageSize
2481
- });
2482
- for (const op of page.results) {
2483
- const scope = op.action.scope ?? "global";
2484
- if (operations[scope]) operations[scope].push(op);
2485
- }
2486
- cursor = page.nextCursor ?? "";
2487
- } while (cursor);
2488
- return operations;
2489
- }
2490
- function extractInitialState(documentScopeOps) {
2491
- const upgradeOp = documentScopeOps.find((op) => op.action.type === "UPGRADE_DOCUMENT");
2492
- if (!upgradeOp) throw new Error("No UPGRADE_DOCUMENT operation found — document is invalid");
2493
- const input = upgradeOp.action.input;
2494
- const initialState = input.initialState ?? input.state;
2495
- if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
2496
- return initialState;
2497
- }
2498
- function filterDomainOperations(operations) {
2499
- return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
2500
- }
2501
- async function exportFile(document, suggestedName) {
2502
- const reactorClient = window.ph?.reactorClient;
2503
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2504
- const operations = await fetchDocumentOperations(reactorClient, document);
2505
- const initialState = extractInitialState(operations["document"] ?? []);
2506
- const documentWithOps = {
2507
- ...document,
2508
- operations,
2509
- initialState
2510
- };
2511
- const extension = await getDocumentExtension(documentWithOps);
2512
- const baseName = suggestedName || documentWithOps.header.name || "Untitled";
2513
- const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
2514
- if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
2515
- try {
2516
- const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
2517
- await baseSaveToFileHandle(documentWithOps, fileHandle);
2518
- return fileHandle;
2519
- } catch (e) {
2520
- if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
2521
- }
2522
- }
2523
- /**
2524
- * Loads a document file and replays it with version-aware reducers from the registry.
2525
- * Falls back to single-version legacy replay when no upgrade manifest is registered for
2526
- * the document type.
2527
- */
2528
- async function loadFile(path) {
2529
- const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
2530
- const reactorClient = window.ph?.reactorClient;
2531
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2532
- const documentType = baseDocument.header.documentType;
2533
- const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
2534
- const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
2535
- if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
2536
- const reducers = {};
2537
- for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
2538
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2539
- let upgradeManifest;
2540
- if (registry) try {
2541
- upgradeManifest = registry.getUpgradeManifest(documentType);
2542
- } catch {}
2543
- return baseLoadFromInputVersioned(path, {
2544
- reducers,
2545
- upgradeManifest
2546
- });
2547
- }
2548
- async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {
2549
- const { isAllowedToCreateDocuments } = getUserPermissions();
2550
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
2551
- const reactorClient = window.ph?.reactorClient;
2552
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2553
- const documentModelModule = await reactorClient.getDocumentModelModule(documentType);
2554
- const newDocument = document ?? documentModelModule.utils.createDocument();
2555
- newDocument.header.name = name;
2556
- if (preferredEditor) newDocument.header.meta = {
2557
- ...newDocument.header.meta,
2558
- preferredEditor
2559
- };
2560
- let newDoc;
2561
- try {
2562
- newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
2563
- } catch (e) {
2564
- logger.error("Error adding document: @error", e);
2565
- throw new Error("There was an error adding document", { cause: e });
2566
- }
2567
- return {
2568
- id: newDoc.header.id,
2569
- name: newDoc.header.name,
2570
- documentType,
2571
- parentFolder: parentFolder ?? null,
2572
- kind: "file"
2573
- };
2574
- }
2575
- async function addFile(file, driveId, name, parentFolder) {
2576
- logger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
2577
- const { isAllowedToCreateDocuments } = getUserPermissions();
2578
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
2579
- const document = await loadFile(file);
2580
- let duplicateId = false;
2581
- const reactorClient = window.ph?.reactorClient;
2582
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2583
- try {
2584
- await reactorClient.get(document.header.id);
2585
- duplicateId = true;
2586
- } catch {}
2587
- const documentId = duplicateId ? generateId() : document.header.id;
2588
- const header = createPresignedHeader(documentId, document.header.documentType);
2589
- header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
2590
- header.meta = document.header.meta;
2591
- header.name = name || document.header.name;
2592
- const initialDocument = {
2593
- ...document,
2594
- header,
2595
- state: document.initialState,
2596
- operations: Object.keys(document.operations).reduce((acc, key) => {
2597
- acc[key] = [];
2598
- return acc;
2599
- }, {})
2600
- };
2601
- await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
2602
- await uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);
2603
- }
2604
- async function addFolder(driveId, name, parentFolder) {
2605
- const { isAllowedToCreateDocuments } = getUserPermissions();
2606
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
2607
- const reactorClient = window.ph?.reactorClient;
2608
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2609
- await reactorClient.get(driveId);
2610
- const folderId = generateId();
2611
- const node = (await reactorClient.execute(driveId, "main", [addFolder$1({
2612
- id: folderId,
2613
- name,
2614
- parentFolder
2615
- })])).state.global.nodes.find((node) => node.id === folderId);
2616
- if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
2617
- return node;
2618
- }
2619
- async function renameNode(driveId, nodeId, name) {
2620
- const { isAllowedToCreateDocuments } = getUserPermissions();
2621
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2622
- const reactorClient = window.ph?.reactorClient;
2623
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2624
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2625
- const node = (await reactorClient.execute(driveId, "main", [updateNode({
2626
- id: nodeId,
2627
- name
2628
- })])).state.global.nodes.find((n) => n.id === nodeId);
2629
- if (!node) throw new Error("There was an error renaming node in the drive");
2630
- return node;
2631
- }
2632
- async function renameDriveNode(driveId, nodeId, name) {
2633
- const { isAllowedToCreateDocuments } = getUserPermissions();
2634
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
2635
- const reactorClient = window.ph?.reactorClient;
2636
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2637
- if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
2638
- await reactorClient.execute(driveId, "main", [updateNode({
2639
- id: nodeId,
2640
- name
2641
- })]);
2642
- return (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);
2643
- }
2644
- async function moveNodeById(args) {
2645
- const { driveId, srcId, targetId } = args;
2646
- if (!driveId || !srcId) return;
2647
- const { isAllowedToCreateDocuments } = getUserPermissions();
2648
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2649
- const reactorClient = window.ph?.reactorClient;
2650
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2651
- const targetParentFolder = t$3(targetId, [e$3(e$4), e$6(void 0)], [t(driveId), e$6(void 0)], e$6(targetId));
2652
- if (t(targetParentFolder, srcId)) return;
2653
- return await reactorClient.execute(driveId, "main", [moveNode({
2654
- srcFolder: srcId,
2655
- targetParentFolder
2656
- })]);
2657
- }
2658
- async function moveNode$1(driveId, src, target) {
2659
- const { isAllowedToCreateDocuments } = getUserPermissions();
2660
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
2661
- const reactorClient = window.ph?.reactorClient;
2662
- if (!reactorClient) throw new Error("ReactorClient not initialized");
2663
- return await reactorClient.execute(driveId, "main", [moveNode({
2664
- srcFolder: src.id,
2665
- targetParentFolder: target?.id
2666
- })]);
2667
- }
2668
- /**
2669
- * Duplicates a document under a new id using version-aware replay.
2670
- * Falls back gracefully when no upgrade manifest is registered for the document type.
2671
- */
2672
- async function _duplicateDocument(reactor, document, newId = generateId()) {
2673
- const documentType = document.header.documentType;
2674
- const { results: allModules } = await reactor.getDocumentModelModules();
2675
- const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
2676
- const reducers = {};
2677
- for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
2678
- if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
2679
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
2680
- let upgradeManifest;
2681
- if (registry) try {
2682
- upgradeManifest = registry.getUpgradeManifest(documentType);
2683
- } catch {}
2684
- const config = {
2685
- reducers,
2686
- upgradeManifest
2687
- };
2688
- const header = createPresignedHeader(newId, documentType);
2689
- const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
2690
- assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
2691
- return duplicated;
2692
- }
2693
- async function copyNode$1(driveId, src, target) {
2694
- const reactor = window.ph?.reactorClient;
2695
- if (!reactor) return;
2696
- const { isAllowedToCreateDocuments } = getUserPermissions();
2697
- if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
2698
- const drive = await reactor.get(driveId);
2699
- const copyNodesInput = generateNodesCopy({
2700
- srcId: src.id,
2701
- targetParentFolder: target?.id,
2702
- targetName: src.name
2703
- }, () => generateId(), drive.state.global.nodes);
2704
- const resolvedNamesMap = /* @__PURE__ */ new Map();
2705
- for (const copyNodeInput of copyNodesInput) {
2706
- const node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);
2707
- if (node) {
2708
- const resolvedName = handleTargetNameCollisions({
2709
- nodes: drive.state.global.nodes,
2710
- srcName: copyNodeInput.targetName || node.name,
2711
- srcKind: isFileNode(node) ? "file" : "folder",
2712
- targetParentFolder: copyNodeInput.targetParentFolder || null
2713
- });
2714
- resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
2715
- }
2716
- }
2717
- const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
2718
- const node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);
2719
- return node !== void 0 && isFileNode(node);
2720
- });
2721
- for (const fileNodeToCopy of fileNodesToCopy) try {
2722
- const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
2723
- const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
2724
- if (resolvedName) duplicatedDocument.header.name = resolvedName;
2725
- await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
2726
- } catch (e) {
2727
- logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
2728
- }
2729
- return await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));
2730
- }
2731
- const modalEventFunctions = makePHEventFunctions("modal");
2732
- modalEventFunctions.useValue;
2733
- /** Sets the current modal */
2734
- const setPHModal = modalEventFunctions.setValue;
2735
- modalEventFunctions.addEventHandler;
2736
- /** Shows a modal */
2737
- function showPHModal(modal) {
2738
- setPHModal(modal);
2739
- }
2740
- /** Shows the create document modal */
2741
- function showCreateDocumentModal(documentType) {
2742
- setPHModal({
2743
- type: "createDocument",
2744
- documentType
2745
- });
2746
- }
2747
- /** Shows the delete node modal */
2748
- function showDeleteNodeModal(nodeOrId) {
2749
- setPHModal({
2750
- type: "deleteItem",
2751
- id: typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id
2752
- });
2753
- }
2754
- /** Document types that represent a "drive": a container of nodes. */
2755
- const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
2756
- const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
2757
- /** Sets whether external controls are enabled for a given editor. */
2758
- const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
2759
- /** Gets whether external controls are enabled for a given editor. */
2760
- const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
2761
- isExternalControlsEnabledEventFunctions.addEventHandler;
2762
- const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
2763
- /** Sets whether drag and drop is enabled for a given app. */
2764
- const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
2765
- /** Gets whether drag and drop is enabled for a given app. */
2766
- const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
2767
- isDragAndDropEnabledEventFunctions.addEventHandler;
2768
- const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
2769
- /** Sets the allowed document types for a given app. */
2770
- const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
2771
- /** Defines the document types a drive supports.
2772
- *
2773
- * Defaults to all of the document types registered in the reactor.
2774
- */
2775
- function useAllowedDocumentTypes() {
2776
- return allowedDocumentTypesEventFunctions.useValue();
2777
- }
2778
- allowedDocumentTypesEventFunctions.addEventHandler;
2779
- const phAppConfigSetters = {
2780
- allowedDocumentTypes: setAllowedDocumentTypes,
2781
- isDragAndDropEnabled: setIsDragAndDropEnabled
2782
- };
2783
- const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
2784
- const phAppConfigHooks = {
2785
- allowedDocumentTypes: useAllowedDocumentTypes,
2786
- isDragAndDropEnabled: useIsDragAndDropEnabled
2181
+ const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
2182
+ const phAppConfigHooks = {
2183
+ allowedDocumentTypes: useAllowedDocumentTypes,
2184
+ isDragAndDropEnabled: useIsDragAndDropEnabled
2787
2185
  };
2788
2186
  const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
2789
2187
  const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
@@ -2990,374 +2388,1089 @@ const nonUserConfigHooks = {
2990
2388
  ...phDocumentEditorConfigHooks,
2991
2389
  ...nonUserConfigHooks
2992
2390
  });
2993
- const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
2994
- attachmentServiceEventFunctions.useValue;
2995
- attachmentServiceEventFunctions.setValue;
2996
- attachmentServiceEventFunctions.addEventHandler;
2997
- const featuresEventFunctions = makePHEventFunctions("features");
2998
- featuresEventFunctions.useValue;
2999
- featuresEventFunctions.setValue;
3000
- featuresEventFunctions.addEventHandler;
3001
- function resolveUrlPathname(path) {
3002
- return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2391
+ const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
2392
+ attachmentServiceEventFunctions.useValue;
2393
+ attachmentServiceEventFunctions.setValue;
2394
+ attachmentServiceEventFunctions.addEventHandler;
2395
+ const featuresEventFunctions = makePHEventFunctions("features");
2396
+ featuresEventFunctions.useValue;
2397
+ featuresEventFunctions.setValue;
2398
+ featuresEventFunctions.addEventHandler;
2399
+ function resolveUrlPathname(path) {
2400
+ return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
2401
+ }
2402
+ /** Returns the current path without the base path */
2403
+ function getPathWithoutBase(path) {
2404
+ const basePath = window.ph?.basePath ?? "/";
2405
+ return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
2406
+ }
2407
+ /** Makes a URL component for a node. */
2408
+ function makeNodeSlug(node) {
2409
+ if (!node) return "";
2410
+ const nodeName = node.name;
2411
+ if (!nodeName) return slug(node.id);
2412
+ return slug(`${nodeName}-${node.id}`);
2413
+ }
2414
+ /** Extracts the node slug from a path.
2415
+ *
2416
+ * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
2417
+ */
2418
+ function extractNodeSlugFromPath(path) {
2419
+ const currentPath = getPathWithoutBase(path);
2420
+ return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
2421
+ }
2422
+ /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
2423
+ function findUuid(input) {
2424
+ if (!input) return void 0;
2425
+ return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
2426
+ }
2427
+ function extractNodeIdFromSlug(nodeSlug) {
2428
+ return findUuid(nodeSlug);
2429
+ }
2430
+ /** Extracts the drive slug from a path.
2431
+ * Used for extracting drive ids from drive slugs in the URL.
2432
+ * Expects the path to be in the format `/d/<drive-slug>`.
2433
+ */
2434
+ function extractDriveSlugFromPath(path) {
2435
+ const currentPath = getPathWithoutBase(path);
2436
+ return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
2437
+ }
2438
+ /**
2439
+ * Creates a URL string with the given pathname while preserving existing query parameters.
2440
+ */
2441
+ function createUrlWithPreservedParams(pathname) {
2442
+ const search = window.location.search;
2443
+ return search ? `${pathname}${search}` : pathname;
2444
+ }
2445
+ const drivesEventFunctions = makePHEventFunctions("drives");
2446
+ /** Returns all of the drives in the reactor */
2447
+ const useDrives = drivesEventFunctions.useValue;
2448
+ /** Sets the drives in the reactor */
2449
+ const setDrives = drivesEventFunctions.setValue;
2450
+ drivesEventFunctions.addEventHandler;
2451
+ const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
2452
+ const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
2453
+ const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
2454
+ selectedNodeIdEventFunctions.addEventHandler;
2455
+ /** Sets the selected node (file or folder). */
2456
+ function setSelectedNode(nodeOrNodeSlug) {
2457
+ const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
2458
+ setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
2459
+ const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
2460
+ if (!driveSlugFromPath) return;
2461
+ if (!nodeSlug) {
2462
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
2463
+ if (pathname === window.location.pathname) return;
2464
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2465
+ return;
2466
+ }
2467
+ const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
2468
+ if (pathname === window.location.pathname) return;
2469
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2470
+ }
2471
+ const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
2472
+ /** Returns the selected drive id */
2473
+ const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
2474
+ /** Sets the selected drive id */
2475
+ const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
2476
+ selectedDriveIdEventFunctions.addEventHandler;
2477
+ /** Returns the selected drive, or undefined if no drive is selected */
2478
+ function useSelectedDriveSafe() {
2479
+ const selectedDriveId = useSelectedDriveId();
2480
+ const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
2481
+ const [drive, dispatch] = useDispatch(selectedDrive);
2482
+ if (!selectedDrive) return [void 0, void 0];
2483
+ return [drive, dispatch];
2484
+ }
2485
+ function setSelectedDrive(driveOrDriveSlug) {
2486
+ const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
2487
+ const drives = window.ph?.drives;
2488
+ const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
2489
+ if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
2490
+ if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
2491
+ deferDriveSelection(driveSlug);
2492
+ return;
2493
+ }
2494
+ cancelPendingDriveSelection();
2495
+ setSelectedDriveId(driveId);
2496
+ if (!driveId) {
2497
+ const pathname = resolveUrlPathname("/");
2498
+ if (pathname === window.location.pathname) return;
2499
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2500
+ return;
2501
+ }
2502
+ const pathname = resolveUrlPathname(`/d/${driveSlug}`);
2503
+ if (pathname === window.location.pathname) return;
2504
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2505
+ }
2506
+ const DEFERRED_DRIVE_TICK_MS = 2e3;
2507
+ const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
2508
+ function isInitialSyncInFlight() {
2509
+ const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
2510
+ if (!remotes?.length) return false;
2511
+ return remotes.some((remote) => {
2512
+ try {
2513
+ const snapshot = remote.channel.getConnectionState();
2514
+ return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
2515
+ } catch {
2516
+ return false;
2517
+ }
2518
+ });
2519
+ }
2520
+ let pendingHandler;
2521
+ let pendingTimeout;
2522
+ function cancelPendingDriveSelection() {
2523
+ if (pendingHandler) {
2524
+ window.removeEventListener("ph:drivesUpdated", pendingHandler);
2525
+ pendingHandler = void 0;
2526
+ }
2527
+ if (pendingTimeout) {
2528
+ clearTimeout(pendingTimeout);
2529
+ pendingTimeout = void 0;
2530
+ }
2531
+ }
2532
+ function deferDriveSelection(driveSlug) {
2533
+ cancelPendingDriveSelection();
2534
+ const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
2535
+ const handler = () => {
2536
+ if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
2537
+ cancelPendingDriveSelection();
2538
+ setSelectedDrive(driveSlug);
2539
+ setSelectedNode(nodeSlug);
2540
+ };
2541
+ pendingHandler = handler;
2542
+ window.addEventListener("ph:drivesUpdated", handler);
2543
+ const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
2544
+ const scheduleTick = () => {
2545
+ pendingTimeout = setTimeout(() => {
2546
+ if (Date.now() < deadline && isInitialSyncInFlight()) {
2547
+ scheduleTick();
2548
+ return;
2549
+ }
2550
+ cancelPendingDriveSelection();
2551
+ const pathname = resolveUrlPathname("/");
2552
+ if (pathname === window.location.pathname) return;
2553
+ window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2554
+ }, DEFERRED_DRIVE_TICK_MS);
2555
+ };
2556
+ scheduleTick();
2557
+ }
2558
+ function useDropTarget() {
2559
+ const [isDropTarget, setIsDropTarget] = useState(false);
2560
+ const isDragAndDropEnabled = useIsDragAndDropEnabled();
2561
+ const targetSetter = n$1(() => setIsDropTarget(true), {
2562
+ triggerAt: "start",
2563
+ minQuietPeriodMs: 100
2564
+ });
2565
+ const targetUnsetter = n$1(() => setIsDropTarget(false), {
2566
+ triggerAt: "start",
2567
+ minQuietPeriodMs: 100
2568
+ });
2569
+ function setTarget() {
2570
+ if (!isDragAndDropEnabled) return;
2571
+ targetUnsetter.cancel();
2572
+ targetSetter.call();
2573
+ }
2574
+ function unsetTarget() {
2575
+ if (!isDragAndDropEnabled) return;
2576
+ targetSetter.cancel();
2577
+ targetUnsetter.call();
2578
+ }
2579
+ return {
2580
+ isDropTarget,
2581
+ setTarget,
2582
+ unsetTarget
2583
+ };
2584
+ }
2585
+ const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
2586
+ const useDraggingNode = draggingNodeEventFunctions.useValue;
2587
+ const setDraggingNode = draggingNodeEventFunctions.setValue;
2588
+ draggingNodeEventFunctions.addEventHandler;
2589
+ const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
2590
+ reducer: (_, newNode) => newNode,
2591
+ triggerAt: "start",
2592
+ minQuietPeriodMs: 100
2593
+ });
2594
+ const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
2595
+ triggerAt: "start",
2596
+ minQuietPeriodMs: 100
2597
+ });
2598
+ function setDragging(node) {
2599
+ draggingNodeUnsetter.cancel();
2600
+ draggingNodeSetter.call(node);
3003
2601
  }
3004
- /** Returns the current path without the base path */
3005
- function getPathWithoutBase(path) {
3006
- const basePath = window.ph?.basePath ?? "/";
3007
- return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
2602
+ function unsetDragging() {
2603
+ draggingNodeSetter.cancel();
2604
+ draggingNodeUnsetter.call();
3008
2605
  }
3009
- /** Makes a URL component for a node. */
3010
- function makeNodeSlug(node) {
3011
- if (!node) return "";
3012
- const nodeName = node.name;
3013
- if (!nodeName) return slug(node.id);
3014
- return slug(`${nodeName}-${node.id}`);
2606
+ 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));
2607
+ function useDragNode(args) {
2608
+ const { srcId, parentId } = args;
2609
+ const driveId = useSelectedDriveId();
2610
+ const draggingNodeId = useDraggingNode()?.srcId;
2611
+ const params = {
2612
+ driveId,
2613
+ srcId,
2614
+ parentId
2615
+ };
2616
+ const draggable = isNodeDrag(params);
2617
+ const isDragging = t$4({
2618
+ srcId,
2619
+ draggingNodeId
2620
+ }, [
2621
+ () => draggable,
2622
+ ({ srcId }) => e$2(srcId),
2623
+ ({ draggingNodeId }) => e$2(draggingNodeId),
2624
+ ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
2625
+ ]);
2626
+ const onDragStart = () => {
2627
+ if (!draggable) return;
2628
+ setDragging(params);
2629
+ };
2630
+ const onDragEnd = () => {
2631
+ if (!draggable) return;
2632
+ unsetDragging();
2633
+ };
2634
+ return {
2635
+ isDragging,
2636
+ draggable,
2637
+ onDragStart,
2638
+ onDragEnd
2639
+ };
3015
2640
  }
3016
- /** Extracts the node slug from a path.
3017
- *
3018
- * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
3019
- */
3020
- function extractNodeSlugFromPath(path) {
3021
- const currentPath = getPathWithoutBase(path);
3022
- return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
2641
+ 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));
2642
+ function useDropNode(targetId) {
2643
+ const driveId = useSelectedDriveId();
2644
+ const { srcId, parentId } = useDraggingNode() ?? {};
2645
+ const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
2646
+ const params = {
2647
+ driveId,
2648
+ parentId,
2649
+ targetId,
2650
+ srcId
2651
+ };
2652
+ function handleNodeDrop(event, cb) {
2653
+ if (!isNodeDrop(params)) return;
2654
+ event.preventDefault();
2655
+ event.stopPropagation();
2656
+ cb?.();
2657
+ }
2658
+ const onDragEnter = (event) => handleNodeDrop(event);
2659
+ const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
2660
+ const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
2661
+ const onDrop = (event) => handleNodeDrop(event, e(() => {
2662
+ unsetDragging();
2663
+ unsetTarget();
2664
+ moveNodeById(params).catch(console.error);
2665
+ }));
2666
+ return {
2667
+ isDropTarget,
2668
+ onDragEnter,
2669
+ onDragOver,
2670
+ onDragLeave,
2671
+ onDrop
2672
+ };
3023
2673
  }
3024
- /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
3025
- function findUuid(input) {
3026
- if (!input) return void 0;
3027
- return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
2674
+ const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
2675
+ graphQLReactorClientEventFunctions.useValue;
2676
+ graphQLReactorClientEventFunctions.setValue;
2677
+ graphQLReactorClientEventFunctions.addEventHandler;
2678
+ const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
2679
+ packageDiscoveryFunctions.useValue;
2680
+ packageDiscoveryFunctions.setValue;
2681
+ packageDiscoveryFunctions.addEventHandler;
2682
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
2683
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
2684
+ /** Returns the reactor client module (in-process or worker-backed) */
2685
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
2686
+ reactorClientModuleEventFunctions.setValue;
2687
+ reactorClientModuleEventFunctions.addEventHandler;
2688
+ reactorClientEventFunctions.useValue;
2689
+ reactorClientEventFunctions.setValue;
2690
+ reactorClientEventFunctions.addEventHandler;
2691
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
2692
+ const useSyncList = () => {
2693
+ return useSync()?.list() ?? [];
2694
+ };
2695
+ const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
2696
+ revisionHistoryEventFunctions.useValue;
2697
+ /** Sets revision history visibility */
2698
+ const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
2699
+ revisionHistoryEventFunctions.addEventHandler;
2700
+ /** Shows the revision history */
2701
+ function showRevisionHistory() {
2702
+ setRevisionHistoryVisible(true);
3028
2703
  }
3029
- function extractNodeIdFromSlug(nodeSlug) {
3030
- return findUuid(nodeSlug);
2704
+ /** Sorts nodes by name. */
2705
+ function sortNodesByName(nodes) {
2706
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
2707
+ }
2708
+ /** Returns whether a node is a file. */
2709
+ function isFileNodeKind(node) {
2710
+ if (!node) return false;
2711
+ return node.kind.toUpperCase() === "FILE";
2712
+ }
2713
+ /** Returns whether a node is a folder. */
2714
+ function isFolderNodeKind(node) {
2715
+ if (!node) return false;
2716
+ return node.kind.toUpperCase() === "FOLDER";
2717
+ }
2718
+ /** Returns the nodes in the selected drive. */
2719
+ function useNodesInSelectedDrive() {
2720
+ const [selectedDrive] = useSelectedDriveSafe();
2721
+ return selectedDrive?.state.global.nodes;
2722
+ }
2723
+ /** Returns the folder nodes in the selected drive. */
2724
+ function useFolderNodesInSelectedDrive() {
2725
+ return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
2726
+ }
2727
+ /** Returns the selected node. */
2728
+ function useSelectedNode() {
2729
+ const selectedNodeId = useSelectedNodeId();
2730
+ return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3031
2731
  }
3032
- /** Extracts the drive slug from a path.
3033
- * Used for extracting drive ids from drive slugs in the URL.
3034
- * Expects the path to be in the format `/d/<drive-slug>`.
3035
- */
3036
- function extractDriveSlugFromPath(path) {
3037
- const currentPath = getPathWithoutBase(path);
3038
- return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
2732
+ const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
2733
+ selectedTimelineItemEventFunctions.useValue;
2734
+ selectedTimelineItemEventFunctions.setValue;
2735
+ selectedTimelineItemEventFunctions.addEventHandler;
2736
+ const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
2737
+ selectedTimelineRevisionEventFunctions.useValue;
2738
+ selectedTimelineRevisionEventFunctions.setValue;
2739
+ selectedTimelineRevisionEventFunctions.addEventHandler;
2740
+ const toastEventFunctions = makePHEventFunctions("toast");
2741
+ /** Returns the toast function */
2742
+ const usePHToast = toastEventFunctions.useValue;
2743
+ toastEventFunctions.setValue;
2744
+ toastEventFunctions.addEventHandler;
2745
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
2746
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
2747
+ /** Returns all of the Vetra packages loaded by the Connect instance */
2748
+ const useVetraPackages = () => {
2749
+ const packageManager = useVetraPackageManager();
2750
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
2751
+ };
2752
+ vetraPackageManagerFunctions.addEventHandler;
2753
+ function useDocumentModelModules() {
2754
+ 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);
3039
2755
  }
3040
2756
  /**
3041
- * Creates a URL string with the given pathname while preserving existing query parameters.
2757
+ * Resolves a document model module by document type, mirroring the registry's
2758
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
2759
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
2760
+ * with `version` given only an exact match is returned. The reactor resolves
2761
+ * modules the same way when a document is created, so metadata read through
2762
+ * this hook and the version a creation actually uses cannot disagree.
3042
2763
  */
3043
- function createUrlWithPreservedParams(pathname) {
3044
- const search = window.location.search;
3045
- return search ? `${pathname}${search}` : pathname;
2764
+ function useDocumentModelModuleById(id, version) {
2765
+ const documentModelModules = useDocumentModelModules();
2766
+ if (!id || !documentModelModules) return void 0;
2767
+ let latestModule;
2768
+ let latestVersion = -1;
2769
+ for (const module of documentModelModules) {
2770
+ if (module.documentModel.global.id !== id) continue;
2771
+ const moduleVersion = module.version ?? 1;
2772
+ if (version !== void 0) {
2773
+ if (moduleVersion === version) return module;
2774
+ continue;
2775
+ }
2776
+ if (moduleVersion > latestVersion) {
2777
+ latestVersion = moduleVersion;
2778
+ latestModule = module;
2779
+ }
2780
+ }
2781
+ return latestModule;
3046
2782
  }
3047
- const drivesEventFunctions = makePHEventFunctions("drives");
3048
- /** Returns all of the drives in the reactor */
3049
- const useDrives = drivesEventFunctions.useValue;
3050
- /** Sets the drives in the reactor */
3051
- const setDrives = drivesEventFunctions.setValue;
3052
- drivesEventFunctions.addEventHandler;
3053
- const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
3054
- const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
3055
- const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
3056
- selectedNodeIdEventFunctions.addEventHandler;
3057
- /** Sets the selected node (file or folder). */
3058
- function setSelectedNode(nodeOrNodeSlug) {
3059
- const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
3060
- setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
3061
- const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
3062
- if (!driveSlugFromPath) return;
3063
- if (!nodeSlug) {
3064
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
3065
- if (pathname === window.location.pathname) return;
3066
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
2783
+ //#endregion
2784
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js
2785
+ const normalizeDescriptors = (error) => {
2786
+ CORE_ERROR_PROPS.forEach((propName) => {
2787
+ normalizeDescriptor(error, propName);
2788
+ });
2789
+ };
2790
+ const CORE_ERROR_PROPS = [
2791
+ "name",
2792
+ "message",
2793
+ "stack",
2794
+ "cause",
2795
+ "errors"
2796
+ ];
2797
+ const normalizeDescriptor = (error, propName) => {
2798
+ const descriptor = getDescriptor(error, propName);
2799
+ if (descriptor === void 0) return;
2800
+ if (isReadonlyGetter(descriptor)) {
2801
+ setErrorProperty(error, propName, error[propName]);
3067
2802
  return;
3068
2803
  }
3069
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
3070
- if (pathname === window.location.pathname) return;
3071
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3072
- }
3073
- const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
3074
- /** Returns the selected drive id */
3075
- const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
3076
- /** Sets the selected drive id */
3077
- const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
3078
- selectedDriveIdEventFunctions.addEventHandler;
3079
- /** Returns the selected drive, or undefined if no drive is selected */
3080
- function useSelectedDriveSafe() {
3081
- const selectedDriveId = useSelectedDriveId();
3082
- const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
3083
- const [drive, dispatch] = useDispatch(selectedDrive);
3084
- if (!selectedDrive) return [void 0, void 0];
3085
- return [drive, dispatch];
2804
+ if (isInvalidDescriptor(descriptor)) setErrorDescriptor(error, propName, descriptor);
2805
+ };
2806
+ const getDescriptor = (value, propName) => {
2807
+ const descriptor = Object.getOwnPropertyDescriptor(value, propName);
2808
+ if (descriptor !== void 0) return descriptor;
2809
+ const prototype = Object.getPrototypeOf(value);
2810
+ return prototype === null ? void 0 : getDescriptor(prototype, propName);
2811
+ };
2812
+ const isReadonlyGetter = ({ get, set }) => get !== void 0 && set === void 0;
2813
+ const isInvalidDescriptor = ({ enumerable, writable }) => enumerable || !writable;
2814
+ const setErrorProperty = (error, propName, value) => {
2815
+ setErrorDescriptor(error, propName, { value });
2816
+ };
2817
+ const setErrorDescriptor = (error, propName, descriptor) => {
2818
+ Object.defineProperty(error, propName, {
2819
+ ...descriptor,
2820
+ ..."get" in descriptor || "set" in descriptor ? {} : { writable: true },
2821
+ enumerable: false,
2822
+ configurable: true
2823
+ });
2824
+ };
2825
+ //#endregion
2826
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js
2827
+ const normalizeAggregate = (error, recurse) => {
2828
+ if (Array.isArray(error.errors)) setErrorProperty(error, "errors", error.errors.filter(isDefined).map(recurse).filter(Boolean));
2829
+ else if (isAggregateError(error)) setErrorProperty(error, "errors", []);
2830
+ else if (error.errors !== void 0) deleteAggregateErrors(error);
2831
+ };
2832
+ const isDefined = (error) => error !== void 0;
2833
+ const isAggregateError = (error) => "AggregateError" in globalThis && (error.name === "AggregateError" || error instanceof AggregateError);
2834
+ const deleteAggregateErrors = (error) => {
2835
+ delete error.errors;
2836
+ if (error.errors !== void 0) setErrorProperty(error, "errors", []);
2837
+ };
2838
+ //#endregion
2839
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js
2840
+ const normalizeCause = (error, recurse) => {
2841
+ if (!("cause" in error)) return;
2842
+ const cause = error.cause === void 0 ? error.cause : recurse(error.cause);
2843
+ if (cause === void 0) delete error.cause;
2844
+ else setErrorProperty(error, "cause", cause);
2845
+ };
2846
+ //#endregion
2847
+ //#region ../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js
2848
+ const isErrorInstance = (value) => isInstanceOfError(value) || hasErrorTag(value);
2849
+ const isInstanceOfError = (value) => {
2850
+ try {
2851
+ return value instanceof Error;
2852
+ } catch {
2853
+ return false;
2854
+ }
2855
+ };
2856
+ const hasErrorTag = (value) => {
2857
+ try {
2858
+ return ERROR_TAGS.has(Object.prototype.toString.call(value));
2859
+ } catch {
2860
+ return false;
2861
+ }
2862
+ };
2863
+ const ERROR_TAGS = new Set([
2864
+ "[object Error]",
2865
+ "[object DOMException]",
2866
+ "[object DOMError]",
2867
+ "[object Exception]"
2868
+ ]);
2869
+ //#endregion
2870
+ //#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
2871
+ function isPlainObject(value) {
2872
+ if (typeof value !== "object" || value === null) return false;
2873
+ const prototype = Object.getPrototypeOf(value);
2874
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
3086
2875
  }
3087
- function setSelectedDrive(driveOrDriveSlug) {
3088
- const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
3089
- const drives = window.ph?.drives;
3090
- const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
3091
- if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
3092
- if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
3093
- deferDriveSelection(driveSlug);
3094
- return;
2876
+ //#endregion
2877
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js
2878
+ const isNonModifiableError = (error) => !Object.isExtensible(error) || CORE_ERROR_PROPS.some((propName) => isNonConfigurableProp(error, propName) || isThrowingProp(error, propName));
2879
+ const isNonConfigurableProp = (error, propName) => {
2880
+ const descriptor = Object.getOwnPropertyDescriptor(error, propName);
2881
+ return descriptor !== void 0 && !descriptor.configurable;
2882
+ };
2883
+ const isThrowingProp = (error, propName) => {
2884
+ try {
2885
+ error[propName];
2886
+ return false;
2887
+ } catch {
2888
+ return true;
2889
+ }
2890
+ };
2891
+ //#endregion
2892
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js
2893
+ const setStack = (error) => {
2894
+ setErrorProperty(error, "stack", getStack(error.message, error.name));
2895
+ };
2896
+ const getStack = (message = "", name = "Error") => {
2897
+ const { stack } = new (getErrorClass(name))(message);
2898
+ return typeof stack === "string" && stack !== "" ? stack : `${name}: ${message}`;
2899
+ };
2900
+ const getErrorClass = (name) => {
2901
+ const descriptor = {
2902
+ value: name,
2903
+ enumerable: false,
2904
+ writable: true,
2905
+ configurable: true
2906
+ };
2907
+ const StackError = Object.defineProperty(class extends Error {}, "name", descriptor);
2908
+ Object.defineProperty(StackError.prototype, "name", descriptor);
2909
+ return StackError;
2910
+ };
2911
+ //#endregion
2912
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js
2913
+ const copyObject = (object) => {
2914
+ const objectCopy = {};
2915
+ for (const propName of getPropsToCopy(object)) try {
2916
+ const value = object[propName];
2917
+ const { enumerable, configurable, writable = true } = getDescriptor(object, propName);
2918
+ Object.defineProperty(objectCopy, propName, {
2919
+ value,
2920
+ enumerable,
2921
+ configurable,
2922
+ writable
2923
+ });
2924
+ } catch {}
2925
+ return objectCopy;
2926
+ };
2927
+ const getPropsToCopy = (object) => {
2928
+ const propNames = getOwnKeys(object);
2929
+ for (const propName of CORE_ERROR_PROPS) if (isInheritedProp(object, propName)) propNames.push(propName);
2930
+ return propNames;
2931
+ };
2932
+ const getOwnKeys = (object) => {
2933
+ try {
2934
+ return Reflect.ownKeys(object);
2935
+ } catch {
2936
+ return [];
2937
+ }
2938
+ };
2939
+ const isInheritedProp = (object, propName) => {
2940
+ try {
2941
+ return propName in object && !Object.hasOwn(object, propName);
2942
+ } catch {
2943
+ return false;
2944
+ }
2945
+ };
2946
+ //#endregion
2947
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js
2948
+ const objectifyError = (object) => {
2949
+ const { name, message, stack, cause, errors, ...objectA } = copyObject(object);
2950
+ const messageA = getMessage(message, objectA);
2951
+ const error = newError(name, messageA);
2952
+ if (message === messageA) assignObjectProps(error, objectA);
2953
+ Object.entries({
2954
+ name,
2955
+ stack,
2956
+ cause,
2957
+ errors
2958
+ }).forEach(([propName, propValue]) => {
2959
+ setNewErrorProperty(error, propName, propValue);
2960
+ });
2961
+ if (stack === void 0) setStack(error);
2962
+ return error;
2963
+ };
2964
+ const getMessage = (message, object) => typeof message === "string" && message !== "" ? message : truncateMessage(safeJsonStringify(object));
2965
+ const safeJsonStringify = (object) => {
2966
+ try {
2967
+ return JSON.stringify(object);
2968
+ } catch {
2969
+ return safeStringify(object);
3095
2970
  }
3096
- cancelPendingDriveSelection();
3097
- setSelectedDriveId(driveId);
3098
- if (!driveId) {
3099
- const pathname = resolveUrlPathname("/");
3100
- if (pathname === window.location.pathname) return;
3101
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3102
- return;
2971
+ };
2972
+ const safeStringify = (object) => {
2973
+ try {
2974
+ return String(object);
2975
+ } catch {
2976
+ return "Invalid error";
3103
2977
  }
3104
- const pathname = resolveUrlPathname(`/d/${driveSlug}`);
3105
- if (pathname === window.location.pathname) return;
3106
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3107
- }
3108
- const DEFERRED_DRIVE_TICK_MS = 2e3;
3109
- const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
3110
- function isInitialSyncInFlight() {
3111
- const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
3112
- if (!remotes?.length) return false;
3113
- return remotes.some((remote) => {
3114
- try {
3115
- const snapshot = remote.channel.getConnectionState();
3116
- return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
3117
- } catch {
3118
- return false;
3119
- }
3120
- });
3121
- }
3122
- let pendingHandler;
3123
- let pendingTimeout;
3124
- function cancelPendingDriveSelection() {
3125
- if (pendingHandler) {
3126
- window.removeEventListener("ph:drivesUpdated", pendingHandler);
3127
- pendingHandler = void 0;
2978
+ };
2979
+ const truncateMessage = (message) => message.length < MESSAGE_MAX_SIZE ? message : `${message.slice(0, MESSAGE_MAX_SIZE)}...`;
2980
+ const MESSAGE_MAX_SIZE = 1e3;
2981
+ const newError = (name, message) => {
2982
+ if (name === "AggregateError" && "AggregateError" in globalThis) return new AggregateError([], message);
2983
+ if (name in NATIVE_ERRORS) return new NATIVE_ERRORS[name](message);
2984
+ return new Error(message);
2985
+ };
2986
+ const NATIVE_ERRORS = {
2987
+ Error,
2988
+ ReferenceError,
2989
+ TypeError,
2990
+ SyntaxError,
2991
+ RangeError,
2992
+ URIError,
2993
+ EvalError
2994
+ };
2995
+ const assignObjectProps = (error, object) => {
2996
+ for (const propName in object) if (!(propName in error)) error[propName] = object[propName];
2997
+ };
2998
+ const setNewErrorProperty = (error, propName, propValue) => {
2999
+ if (propValue !== void 0) setErrorProperty(error, propName, propValue);
3000
+ };
3001
+ //#endregion
3002
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js
3003
+ const stringifyError = (value) => {
3004
+ try {
3005
+ const error = new Error(String(value));
3006
+ setStack(error);
3007
+ return error;
3008
+ } catch (error_) {
3009
+ return error_;
3128
3010
  }
3129
- if (pendingTimeout) {
3130
- clearTimeout(pendingTimeout);
3131
- pendingTimeout = void 0;
3011
+ };
3012
+ //#endregion
3013
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js
3014
+ const { toString: objectToString } = Object.prototype;
3015
+ const createError = (value) => {
3016
+ if (isErrorPlainObj(value)) return objectifyError(value);
3017
+ if (!isErrorInstance(value)) return stringifyError(value);
3018
+ if (isInvalidError(value)) return objectifyError(value);
3019
+ return value;
3020
+ };
3021
+ const isErrorPlainObj = (value) => {
3022
+ try {
3023
+ return isPlainObject(value);
3024
+ } catch {
3025
+ return false;
3132
3026
  }
3133
- }
3134
- function deferDriveSelection(driveSlug) {
3135
- cancelPendingDriveSelection();
3136
- const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
3137
- const handler = () => {
3138
- if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
3139
- cancelPendingDriveSelection();
3140
- setSelectedDrive(driveSlug);
3141
- setSelectedNode(nodeSlug);
3142
- };
3143
- pendingHandler = handler;
3144
- window.addEventListener("ph:drivesUpdated", handler);
3145
- const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
3146
- const scheduleTick = () => {
3147
- pendingTimeout = setTimeout(() => {
3148
- if (Date.now() < deadline && isInitialSyncInFlight()) {
3149
- scheduleTick();
3150
- return;
3027
+ };
3028
+ const isInvalidError = (value) => isProxy(value) || isNonModifiableError(value) || hasInvalidConstructor(value);
3029
+ const isProxy = (value) => {
3030
+ try {
3031
+ return objectToString.call(value) === "[object Object]";
3032
+ } catch {
3033
+ return true;
3034
+ }
3035
+ };
3036
+ const hasInvalidConstructor = (error) => typeof error.constructor !== "function" || typeof error.constructor.name !== "string" || error.constructor.name === "" || error.constructor.prototype !== Object.getPrototypeOf(error);
3037
+ //#endregion
3038
+ //#region ../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js
3039
+ const normalizeException = (error, { shallow = false } = {}) => recurseException(error, [], shallow);
3040
+ const recurseException = (error, parents, shallow) => {
3041
+ if (parents.includes(error)) return;
3042
+ const recurse = shallow ? identity : (innerError) => recurseException(innerError, [...parents, error], shallow);
3043
+ const errorA = createError(error);
3044
+ normalizeProps(errorA, recurse);
3045
+ return errorA;
3046
+ };
3047
+ const identity = (error) => error;
3048
+ const normalizeProps = (error, recurse) => {
3049
+ normalizeName(error);
3050
+ normalizeMessage(error);
3051
+ normalizeStack(error);
3052
+ normalizeCause(error, recurse);
3053
+ normalizeAggregate(error, recurse);
3054
+ normalizeDescriptors(error);
3055
+ };
3056
+ const normalizeName = (error) => {
3057
+ if (isDefinedString(error.name)) return;
3058
+ const prototypeName = Object.getPrototypeOf(error).name;
3059
+ setErrorProperty(error, "name", isDefinedString(prototypeName) ? prototypeName : error.constructor.name);
3060
+ };
3061
+ const normalizeMessage = (error) => {
3062
+ if (!isDefinedString(error.message)) setErrorProperty(error, "message", "");
3063
+ };
3064
+ const normalizeStack = (error) => {
3065
+ if (!isDefinedString(error.stack)) setStack(error);
3066
+ };
3067
+ const isDefinedString = (value) => typeof value === "string" && value !== "";
3068
+ //#endregion
3069
+ //#region ../reactor-browser/dist/index.js
3070
+ var import_lz_string = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3071
+ var LZString = (function() {
3072
+ var f = String.fromCharCode;
3073
+ var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3074
+ var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
3075
+ var baseReverseDic = {};
3076
+ function getBaseValue(alphabet, character) {
3077
+ if (!baseReverseDic[alphabet]) {
3078
+ baseReverseDic[alphabet] = {};
3079
+ for (var i = 0; i < alphabet.length; i++) baseReverseDic[alphabet][alphabet.charAt(i)] = i;
3080
+ }
3081
+ return baseReverseDic[alphabet][character];
3082
+ }
3083
+ var LZString = {
3084
+ compressToBase64: function(input) {
3085
+ if (input == null) return "";
3086
+ var res = LZString._compress(input, 6, function(a) {
3087
+ return keyStrBase64.charAt(a);
3088
+ });
3089
+ switch (res.length % 4) {
3090
+ default:
3091
+ case 0: return res;
3092
+ case 1: return res + "===";
3093
+ case 2: return res + "==";
3094
+ case 3: return res + "=";
3095
+ }
3096
+ },
3097
+ decompressFromBase64: function(input) {
3098
+ if (input == null) return "";
3099
+ if (input == "") return null;
3100
+ return LZString._decompress(input.length, 32, function(index) {
3101
+ return getBaseValue(keyStrBase64, input.charAt(index));
3102
+ });
3103
+ },
3104
+ compressToUTF16: function(input) {
3105
+ if (input == null) return "";
3106
+ return LZString._compress(input, 15, function(a) {
3107
+ return f(a + 32);
3108
+ }) + " ";
3109
+ },
3110
+ decompressFromUTF16: function(compressed) {
3111
+ if (compressed == null) return "";
3112
+ if (compressed == "") return null;
3113
+ return LZString._decompress(compressed.length, 16384, function(index) {
3114
+ return compressed.charCodeAt(index) - 32;
3115
+ });
3116
+ },
3117
+ compressToUint8Array: function(uncompressed) {
3118
+ var compressed = LZString.compress(uncompressed);
3119
+ var buf = new Uint8Array(compressed.length * 2);
3120
+ for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
3121
+ var current_value = compressed.charCodeAt(i);
3122
+ buf[i * 2] = current_value >>> 8;
3123
+ buf[i * 2 + 1] = current_value % 256;
3124
+ }
3125
+ return buf;
3126
+ },
3127
+ decompressFromUint8Array: function(compressed) {
3128
+ if (compressed === null || compressed === void 0) return LZString.decompress(compressed);
3129
+ else {
3130
+ var buf = new Array(compressed.length / 2);
3131
+ for (var i = 0, TotalLen = buf.length; i < TotalLen; i++) buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1];
3132
+ var result = [];
3133
+ buf.forEach(function(c) {
3134
+ result.push(f(c));
3135
+ });
3136
+ return LZString.decompress(result.join(""));
3137
+ }
3138
+ },
3139
+ compressToEncodedURIComponent: function(input) {
3140
+ if (input == null) return "";
3141
+ return LZString._compress(input, 6, function(a) {
3142
+ return keyStrUriSafe.charAt(a);
3143
+ });
3144
+ },
3145
+ decompressFromEncodedURIComponent: function(input) {
3146
+ if (input == null) return "";
3147
+ if (input == "") return null;
3148
+ input = input.replace(/ /g, "+");
3149
+ return LZString._decompress(input.length, 32, function(index) {
3150
+ return getBaseValue(keyStrUriSafe, input.charAt(index));
3151
+ });
3152
+ },
3153
+ compress: function(uncompressed) {
3154
+ return LZString._compress(uncompressed, 16, function(a) {
3155
+ return f(a);
3156
+ });
3157
+ },
3158
+ _compress: function(uncompressed, bitsPerChar, getCharFromInt) {
3159
+ if (uncompressed == null) return "";
3160
+ 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;
3161
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
3162
+ context_c = uncompressed.charAt(ii);
3163
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
3164
+ context_dictionary[context_c] = context_dictSize++;
3165
+ context_dictionaryToCreate[context_c] = true;
3166
+ }
3167
+ context_wc = context_w + context_c;
3168
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) context_w = context_wc;
3169
+ else {
3170
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3171
+ if (context_w.charCodeAt(0) < 256) {
3172
+ for (i = 0; i < context_numBits; i++) {
3173
+ context_data_val = context_data_val << 1;
3174
+ if (context_data_position == bitsPerChar - 1) {
3175
+ context_data_position = 0;
3176
+ context_data.push(getCharFromInt(context_data_val));
3177
+ context_data_val = 0;
3178
+ } else context_data_position++;
3179
+ }
3180
+ value = context_w.charCodeAt(0);
3181
+ for (i = 0; i < 8; i++) {
3182
+ context_data_val = context_data_val << 1 | value & 1;
3183
+ if (context_data_position == bitsPerChar - 1) {
3184
+ context_data_position = 0;
3185
+ context_data.push(getCharFromInt(context_data_val));
3186
+ context_data_val = 0;
3187
+ } else context_data_position++;
3188
+ value = value >> 1;
3189
+ }
3190
+ } else {
3191
+ value = 1;
3192
+ for (i = 0; i < context_numBits; i++) {
3193
+ context_data_val = context_data_val << 1 | value;
3194
+ if (context_data_position == bitsPerChar - 1) {
3195
+ context_data_position = 0;
3196
+ context_data.push(getCharFromInt(context_data_val));
3197
+ context_data_val = 0;
3198
+ } else context_data_position++;
3199
+ value = 0;
3200
+ }
3201
+ value = context_w.charCodeAt(0);
3202
+ for (i = 0; i < 16; i++) {
3203
+ context_data_val = context_data_val << 1 | value & 1;
3204
+ if (context_data_position == bitsPerChar - 1) {
3205
+ context_data_position = 0;
3206
+ context_data.push(getCharFromInt(context_data_val));
3207
+ context_data_val = 0;
3208
+ } else context_data_position++;
3209
+ value = value >> 1;
3210
+ }
3211
+ }
3212
+ context_enlargeIn--;
3213
+ if (context_enlargeIn == 0) {
3214
+ context_enlargeIn = Math.pow(2, context_numBits);
3215
+ context_numBits++;
3216
+ }
3217
+ delete context_dictionaryToCreate[context_w];
3218
+ } else {
3219
+ value = context_dictionary[context_w];
3220
+ for (i = 0; i < context_numBits; i++) {
3221
+ context_data_val = context_data_val << 1 | value & 1;
3222
+ if (context_data_position == bitsPerChar - 1) {
3223
+ context_data_position = 0;
3224
+ context_data.push(getCharFromInt(context_data_val));
3225
+ context_data_val = 0;
3226
+ } else context_data_position++;
3227
+ value = value >> 1;
3228
+ }
3229
+ }
3230
+ context_enlargeIn--;
3231
+ if (context_enlargeIn == 0) {
3232
+ context_enlargeIn = Math.pow(2, context_numBits);
3233
+ context_numBits++;
3234
+ }
3235
+ context_dictionary[context_wc] = context_dictSize++;
3236
+ context_w = String(context_c);
3237
+ }
3238
+ }
3239
+ if (context_w !== "") {
3240
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
3241
+ if (context_w.charCodeAt(0) < 256) {
3242
+ for (i = 0; i < context_numBits; i++) {
3243
+ context_data_val = context_data_val << 1;
3244
+ if (context_data_position == bitsPerChar - 1) {
3245
+ context_data_position = 0;
3246
+ context_data.push(getCharFromInt(context_data_val));
3247
+ context_data_val = 0;
3248
+ } else context_data_position++;
3249
+ }
3250
+ value = context_w.charCodeAt(0);
3251
+ for (i = 0; i < 8; i++) {
3252
+ context_data_val = context_data_val << 1 | value & 1;
3253
+ if (context_data_position == bitsPerChar - 1) {
3254
+ context_data_position = 0;
3255
+ context_data.push(getCharFromInt(context_data_val));
3256
+ context_data_val = 0;
3257
+ } else context_data_position++;
3258
+ value = value >> 1;
3259
+ }
3260
+ } else {
3261
+ value = 1;
3262
+ for (i = 0; i < context_numBits; i++) {
3263
+ context_data_val = context_data_val << 1 | value;
3264
+ if (context_data_position == bitsPerChar - 1) {
3265
+ context_data_position = 0;
3266
+ context_data.push(getCharFromInt(context_data_val));
3267
+ context_data_val = 0;
3268
+ } else context_data_position++;
3269
+ value = 0;
3270
+ }
3271
+ value = context_w.charCodeAt(0);
3272
+ for (i = 0; i < 16; i++) {
3273
+ context_data_val = context_data_val << 1 | value & 1;
3274
+ if (context_data_position == bitsPerChar - 1) {
3275
+ context_data_position = 0;
3276
+ context_data.push(getCharFromInt(context_data_val));
3277
+ context_data_val = 0;
3278
+ } else context_data_position++;
3279
+ value = value >> 1;
3280
+ }
3281
+ }
3282
+ context_enlargeIn--;
3283
+ if (context_enlargeIn == 0) {
3284
+ context_enlargeIn = Math.pow(2, context_numBits);
3285
+ context_numBits++;
3286
+ }
3287
+ delete context_dictionaryToCreate[context_w];
3288
+ } else {
3289
+ value = context_dictionary[context_w];
3290
+ for (i = 0; i < context_numBits; i++) {
3291
+ context_data_val = context_data_val << 1 | value & 1;
3292
+ if (context_data_position == bitsPerChar - 1) {
3293
+ context_data_position = 0;
3294
+ context_data.push(getCharFromInt(context_data_val));
3295
+ context_data_val = 0;
3296
+ } else context_data_position++;
3297
+ value = value >> 1;
3298
+ }
3299
+ }
3300
+ context_enlargeIn--;
3301
+ if (context_enlargeIn == 0) {
3302
+ context_enlargeIn = Math.pow(2, context_numBits);
3303
+ context_numBits++;
3304
+ }
3305
+ }
3306
+ value = 2;
3307
+ for (i = 0; i < context_numBits; i++) {
3308
+ context_data_val = context_data_val << 1 | value & 1;
3309
+ if (context_data_position == bitsPerChar - 1) {
3310
+ context_data_position = 0;
3311
+ context_data.push(getCharFromInt(context_data_val));
3312
+ context_data_val = 0;
3313
+ } else context_data_position++;
3314
+ value = value >> 1;
3315
+ }
3316
+ while (true) {
3317
+ context_data_val = context_data_val << 1;
3318
+ if (context_data_position == bitsPerChar - 1) {
3319
+ context_data.push(getCharFromInt(context_data_val));
3320
+ break;
3321
+ } else context_data_position++;
3322
+ }
3323
+ return context_data.join("");
3324
+ },
3325
+ decompress: function(compressed) {
3326
+ if (compressed == null) return "";
3327
+ if (compressed == "") return null;
3328
+ return LZString._decompress(compressed.length, 32768, function(index) {
3329
+ return compressed.charCodeAt(index);
3330
+ });
3331
+ },
3332
+ _decompress: function(length, resetValue, getNextValue) {
3333
+ var dictionary = [], enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = {
3334
+ val: getNextValue(0),
3335
+ position: resetValue,
3336
+ index: 1
3337
+ };
3338
+ for (i = 0; i < 3; i += 1) dictionary[i] = i;
3339
+ bits = 0;
3340
+ maxpower = Math.pow(2, 2);
3341
+ power = 1;
3342
+ while (power != maxpower) {
3343
+ resb = data.val & data.position;
3344
+ data.position >>= 1;
3345
+ if (data.position == 0) {
3346
+ data.position = resetValue;
3347
+ data.val = getNextValue(data.index++);
3348
+ }
3349
+ bits |= (resb > 0 ? 1 : 0) * power;
3350
+ power <<= 1;
3351
+ }
3352
+ switch (bits) {
3353
+ case 0:
3354
+ bits = 0;
3355
+ maxpower = Math.pow(2, 8);
3356
+ power = 1;
3357
+ while (power != maxpower) {
3358
+ resb = data.val & data.position;
3359
+ data.position >>= 1;
3360
+ if (data.position == 0) {
3361
+ data.position = resetValue;
3362
+ data.val = getNextValue(data.index++);
3363
+ }
3364
+ bits |= (resb > 0 ? 1 : 0) * power;
3365
+ power <<= 1;
3366
+ }
3367
+ c = f(bits);
3368
+ break;
3369
+ case 1:
3370
+ bits = 0;
3371
+ maxpower = Math.pow(2, 16);
3372
+ power = 1;
3373
+ while (power != maxpower) {
3374
+ resb = data.val & data.position;
3375
+ data.position >>= 1;
3376
+ if (data.position == 0) {
3377
+ data.position = resetValue;
3378
+ data.val = getNextValue(data.index++);
3379
+ }
3380
+ bits |= (resb > 0 ? 1 : 0) * power;
3381
+ power <<= 1;
3382
+ }
3383
+ c = f(bits);
3384
+ break;
3385
+ case 2: return "";
3386
+ }
3387
+ dictionary[3] = c;
3388
+ w = c;
3389
+ result.push(c);
3390
+ while (true) {
3391
+ if (data.index > length) return "";
3392
+ bits = 0;
3393
+ maxpower = Math.pow(2, numBits);
3394
+ power = 1;
3395
+ while (power != maxpower) {
3396
+ resb = data.val & data.position;
3397
+ data.position >>= 1;
3398
+ if (data.position == 0) {
3399
+ data.position = resetValue;
3400
+ data.val = getNextValue(data.index++);
3401
+ }
3402
+ bits |= (resb > 0 ? 1 : 0) * power;
3403
+ power <<= 1;
3404
+ }
3405
+ switch (c = bits) {
3406
+ case 0:
3407
+ bits = 0;
3408
+ maxpower = Math.pow(2, 8);
3409
+ power = 1;
3410
+ while (power != maxpower) {
3411
+ resb = data.val & data.position;
3412
+ data.position >>= 1;
3413
+ if (data.position == 0) {
3414
+ data.position = resetValue;
3415
+ data.val = getNextValue(data.index++);
3416
+ }
3417
+ bits |= (resb > 0 ? 1 : 0) * power;
3418
+ power <<= 1;
3419
+ }
3420
+ dictionary[dictSize++] = f(bits);
3421
+ c = dictSize - 1;
3422
+ enlargeIn--;
3423
+ break;
3424
+ case 1:
3425
+ bits = 0;
3426
+ maxpower = Math.pow(2, 16);
3427
+ power = 1;
3428
+ while (power != maxpower) {
3429
+ resb = data.val & data.position;
3430
+ data.position >>= 1;
3431
+ if (data.position == 0) {
3432
+ data.position = resetValue;
3433
+ data.val = getNextValue(data.index++);
3434
+ }
3435
+ bits |= (resb > 0 ? 1 : 0) * power;
3436
+ power <<= 1;
3437
+ }
3438
+ dictionary[dictSize++] = f(bits);
3439
+ c = dictSize - 1;
3440
+ enlargeIn--;
3441
+ break;
3442
+ case 2: return result.join("");
3443
+ }
3444
+ if (enlargeIn == 0) {
3445
+ enlargeIn = Math.pow(2, numBits);
3446
+ numBits++;
3447
+ }
3448
+ if (dictionary[c]) entry = dictionary[c];
3449
+ else if (c === dictSize) entry = w + w.charAt(0);
3450
+ else return null;
3451
+ result.push(entry);
3452
+ dictionary[dictSize++] = w + entry.charAt(0);
3453
+ enlargeIn--;
3454
+ w = entry;
3455
+ if (enlargeIn == 0) {
3456
+ enlargeIn = Math.pow(2, numBits);
3457
+ numBits++;
3458
+ }
3459
+ }
3151
3460
  }
3152
- cancelPendingDriveSelection();
3153
- const pathname = resolveUrlPathname("/");
3154
- if (pathname === window.location.pathname) return;
3155
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
3156
- }, DEFERRED_DRIVE_TICK_MS);
3157
- };
3158
- scheduleTick();
3159
- }
3160
- function useDropTarget() {
3161
- const [isDropTarget, setIsDropTarget] = useState(false);
3162
- const isDragAndDropEnabled = useIsDragAndDropEnabled();
3163
- const targetSetter = n$1(() => setIsDropTarget(true), {
3164
- triggerAt: "start",
3165
- minQuietPeriodMs: 100
3461
+ };
3462
+ return LZString;
3463
+ })();
3464
+ if (typeof define === "function" && define.amd) define(function() {
3465
+ return LZString;
3166
3466
  });
3167
- const targetUnsetter = n$1(() => setIsDropTarget(false), {
3168
- triggerAt: "start",
3169
- minQuietPeriodMs: 100
3467
+ else if (typeof module !== "undefined" && module != null) module.exports = LZString;
3468
+ else if (typeof angular !== "undefined" && angular != null) angular.module("LZString", []).factory("LZString", function() {
3469
+ return LZString;
3170
3470
  });
3171
- function setTarget() {
3172
- if (!isDragAndDropEnabled) return;
3173
- targetUnsetter.cancel();
3174
- targetSetter.call();
3175
- }
3176
- function unsetTarget() {
3177
- if (!isDragAndDropEnabled) return;
3178
- targetSetter.cancel();
3179
- targetUnsetter.call();
3180
- }
3181
- return {
3182
- isDropTarget,
3183
- setTarget,
3184
- unsetTarget
3185
- };
3186
- }
3187
- const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
3188
- const useDraggingNode = draggingNodeEventFunctions.useValue;
3189
- const setDraggingNode = draggingNodeEventFunctions.setValue;
3190
- draggingNodeEventFunctions.addEventHandler;
3191
- const draggingNodeSetter = n$1((node) => setDraggingNode(node), {
3192
- reducer: (_, newNode) => newNode,
3193
- triggerAt: "start",
3194
- minQuietPeriodMs: 100
3195
- });
3196
- const draggingNodeUnsetter = n$1(() => setDraggingNode(void 0), {
3197
- triggerAt: "start",
3198
- minQuietPeriodMs: 100
3199
- });
3200
- function setDragging(node) {
3201
- draggingNodeUnsetter.cancel();
3202
- draggingNodeSetter.call(node);
3203
- }
3204
- function unsetDragging() {
3205
- draggingNodeSetter.cancel();
3206
- draggingNodeUnsetter.call();
3207
- }
3208
- 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));
3209
- function useDragNode(args) {
3210
- const { srcId, parentId } = args;
3211
- const driveId = useSelectedDriveId();
3212
- const draggingNodeId = useDraggingNode()?.srcId;
3213
- const params = {
3214
- driveId,
3215
- srcId,
3216
- parentId
3217
- };
3218
- const draggable = isNodeDrag(params);
3219
- const isDragging = t$4({
3220
- srcId,
3221
- draggingNodeId
3222
- }, [
3223
- () => draggable,
3224
- ({ srcId }) => e$2(srcId),
3225
- ({ draggingNodeId }) => e$2(draggingNodeId),
3226
- ({ srcId, draggingNodeId }) => t(srcId, draggingNodeId)
3227
- ]);
3228
- const onDragStart = () => {
3229
- if (!draggable) return;
3230
- setDragging(params);
3231
- };
3232
- const onDragEnd = () => {
3233
- if (!draggable) return;
3234
- unsetDragging();
3235
- };
3236
- return {
3237
- isDragging,
3238
- draggable,
3239
- onDragStart,
3240
- onDragEnd
3241
- };
3242
- }
3243
- 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));
3244
- function useDropNode(targetId) {
3245
- const driveId = useSelectedDriveId();
3246
- const { srcId, parentId } = useDraggingNode() ?? {};
3247
- const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
3248
- const params = {
3249
- driveId,
3250
- parentId,
3251
- targetId,
3252
- srcId
3253
- };
3254
- function handleNodeDrop(event, cb) {
3255
- if (!isNodeDrop(params)) return;
3256
- event.preventDefault();
3257
- event.stopPropagation();
3258
- cb?.();
3259
- }
3260
- const onDragEnter = (event) => handleNodeDrop(event);
3261
- const onDragOver = (event) => handleNodeDrop(event, e(setTarget));
3262
- const onDragLeave = (event) => handleNodeDrop(event, e(unsetTarget));
3263
- const onDrop = (event) => handleNodeDrop(event, e(() => {
3264
- unsetDragging();
3265
- unsetTarget();
3266
- moveNodeById(params).catch(console.error);
3267
- }));
3268
- return {
3269
- isDropTarget,
3270
- onDragEnter,
3271
- onDragOver,
3272
- onDragLeave,
3273
- onDrop
3274
- };
3275
- }
3276
- const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
3277
- graphQLReactorClientEventFunctions.useValue;
3278
- graphQLReactorClientEventFunctions.setValue;
3279
- graphQLReactorClientEventFunctions.addEventHandler;
3280
- const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
3281
- packageDiscoveryFunctions.useValue;
3282
- packageDiscoveryFunctions.setValue;
3283
- packageDiscoveryFunctions.addEventHandler;
3284
- const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
3285
- const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
3286
- /** Returns the reactor client module (in-process or worker-backed) */
3287
- const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
3288
- reactorClientModuleEventFunctions.setValue;
3289
- reactorClientModuleEventFunctions.addEventHandler;
3290
- reactorClientEventFunctions.useValue;
3291
- reactorClientEventFunctions.setValue;
3292
- reactorClientEventFunctions.addEventHandler;
3293
- const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
3294
- const useSyncList = () => {
3295
- return useSync()?.list() ?? [];
3296
- };
3297
- const revisionHistoryEventFunctions = makePHEventFunctions("revisionHistoryVisible");
3298
- revisionHistoryEventFunctions.useValue;
3299
- /** Sets revision history visibility */
3300
- const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;
3301
- revisionHistoryEventFunctions.addEventHandler;
3302
- /** Shows the revision history */
3303
- function showRevisionHistory() {
3304
- setRevisionHistoryVisible(true);
3305
- }
3306
- /** Sorts nodes by name. */
3307
- function sortNodesByName(nodes) {
3308
- return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
3309
- }
3310
- /** Returns whether a node is a file. */
3311
- function isFileNodeKind(node) {
3312
- if (!node) return false;
3313
- return node.kind.toUpperCase() === "FILE";
3314
- }
3315
- /** Returns whether a node is a folder. */
3316
- function isFolderNodeKind(node) {
3317
- if (!node) return false;
3318
- return node.kind.toUpperCase() === "FOLDER";
3319
- }
3320
- /** Returns the nodes in the selected drive. */
3321
- function useNodesInSelectedDrive() {
3322
- const [selectedDrive] = useSelectedDriveSafe();
3323
- return selectedDrive?.state.global.nodes;
3324
- }
3325
- /** Returns the folder nodes in the selected drive. */
3326
- function useFolderNodesInSelectedDrive() {
3327
- return useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));
3328
- }
3329
- /** Returns the selected node. */
3330
- function useSelectedNode() {
3331
- const selectedNodeId = useSelectedNodeId();
3332
- return useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);
3333
- }
3334
- const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
3335
- selectedTimelineItemEventFunctions.useValue;
3336
- selectedTimelineItemEventFunctions.setValue;
3337
- selectedTimelineItemEventFunctions.addEventHandler;
3338
- const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
3339
- selectedTimelineRevisionEventFunctions.useValue;
3340
- selectedTimelineRevisionEventFunctions.setValue;
3341
- selectedTimelineRevisionEventFunctions.addEventHandler;
3342
- const toastEventFunctions = makePHEventFunctions("toast");
3343
- /** Returns the toast function */
3344
- const usePHToast = toastEventFunctions.useValue;
3345
- toastEventFunctions.setValue;
3346
- toastEventFunctions.addEventHandler;
3347
- const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
3348
- const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
3349
- /** Returns all of the Vetra packages loaded by the Connect instance */
3350
- const useVetraPackages = () => {
3351
- const packageManager = useVetraPackageManager();
3352
- return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);
3353
- };
3354
- vetraPackageManagerFunctions.addEventHandler;
3355
- function useDocumentModelModules() {
3356
- 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);
3357
- }
3358
- function useDocumentModelModuleById(id) {
3359
- return useDocumentModelModules()?.find((module) => module.documentModel.global.id === id);
3360
- }
3471
+ })))(), 1);
3472
+ /** Document types that represent a "drive": a container of nodes. */
3473
+ const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
3361
3474
  function useAllowedDocumentModelModules() {
3362
3475
  const documentModelModules = useDocumentModelModules();
3363
3476
  const allowedDocumentTypes = useAllowedDocumentTypes();
@@ -3542,7 +3655,7 @@ function useNodeActions() {
3542
3655
  }
3543
3656
  async function onAddFolder(name, parent) {
3544
3657
  if (!selectedDriveId) return;
3545
- return addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3658
+ return addFolder$1(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);
3546
3659
  }
3547
3660
  async function onRenameNode(newName, node) {
3548
3661
  if (!selectedDriveId) return;
@@ -3857,6 +3970,6 @@ function createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOU
3857
3970
  createDebouncedRefreshReactorData();
3858
3971
  createDebouncedRefreshReactorDataClient();
3859
3972
  //#endregion
3860
- 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 };
3973
+ export { usePHToast as A, setSelectedNode as C, useDisabledEditors as D, showRevisionHistory as E, t$2 as F, t$5 as I, useDocumentById as L, useSelectedDriveSafe as M, e$1 as N, useDragNode as O, e$4 as P, setSelectedDrive as S, showDeleteNodeModal as T, useTheme as _, useEditorModules as a, isFileNodeKind as b, useNodeActions as c, useNodesInSelectedDriveOrFolder as d, useSelectedDocumentOfType as f, useSetPHDocumentEditorConfig as g, useSetPHAppConfig as h, useDownloadDocument as i, useSelectedDriveId as j, useDropNode as k, useNodeById as l, useSelectedNodePath as m, preloadEditorModule as n, useEditorModulesForDocumentType as o, useSelectedDocumentSafe as p, useAllowedDocumentModelModules as r, useGetSwitchboardLink as s, getSyncStatusSync as t, useNodeParentFolderById as u, useUserPermissions as v, showCreateDocumentModal as w, isFolderNodeKind as x, addFolder$1 as y };
3861
3974
 
3862
- //# sourceMappingURL=dist-UIW3bhlu.js.map
3975
+ //# sourceMappingURL=dist-CetbB2Ax.js.map