@powerhousedao/reactor-browser 6.2.3-dev.69 → 6.2.3-dev.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attachment-service-BHS3EJAr.d.ts → attachment-service-CAf9N-15.d.ts} +5 -3
- package/dist/{attachment-service-BHS3EJAr.d.ts.map → attachment-service-CAf9N-15.d.ts.map} +1 -1
- package/dist/{dispatch-BmdzdTwb.js → dispatch-Dd_WEz35.js} +19 -11
- package/dist/{dispatch-BmdzdTwb.js.map → dispatch-Dd_WEz35.js.map} +1 -1
- package/dist/{document-by-id-BqNuTx4S.js → document-by-id-DqAyjr9P.js} +2 -2
- package/dist/{document-by-id-BqNuTx4S.js.map → document-by-id-DqAyjr9P.js.map} +1 -1
- package/dist/{document-model-modules-BwnWiVeC.js → document-model-modules-DROQT_yu.js} +85 -100
- package/dist/document-model-modules-DROQT_yu.js.map +1 -0
- package/dist/{document-operations-DciiZwkC.js → document-operations-C6khz2If.js} +6 -6
- package/dist/{document-operations-DciiZwkC.js.map → document-operations-C6khz2If.js.map} +1 -1
- package/dist/{global-Cgi-GJpN.d.ts → global-D-VZTZRz.d.ts} +3 -4
- package/dist/global-D-VZTZRz.d.ts.map +1 -0
- package/dist/{index-B8MXPz3f.d.ts → index-XfcUiODQ.d.ts} +2 -2
- package/dist/{index-B8MXPz3f.d.ts.map → index-XfcUiODQ.d.ts.map} +1 -1
- package/dist/index.d.ts +95 -70
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +26 -16
- package/dist/index.js.map +1 -1
- package/dist/{make-ph-event-functions-C1JTfEw1.js → make-ph-event-functions-B5GU5xcR.js} +4 -75
- package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
- package/dist/{navigation-BUPIObES.js → navigation-BqphkrOB.js} +3 -20
- package/dist/navigation-BqphkrOB.js.map +1 -0
- package/dist/{renown-Dem71OWZ.js → renown-BtjgHBjH.js} +4 -4
- package/dist/{renown-Dem71OWZ.js.map → renown-BtjgHBjH.js.map} +1 -1
- package/dist/{renown-CGQYQsvH.js → renown-BxkZYzbQ.js} +2 -2
- package/dist/{renown-CGQYQsvH.js.map → renown-BxkZYzbQ.js.map} +1 -1
- package/dist/src/ai/index.js +2 -2
- package/dist/src/analytics/index.js +1 -1
- package/dist/src/graphql-client/entry.d.ts +2 -2
- package/dist/src/graphql-client/entry.js +3 -3
- package/dist/src/renown/index.d.ts +1 -1
- package/dist/src/renown/index.js +2 -2
- package/dist/{switchboard-CiYrfAcM.js → switchboard-cwUp3FxP.js} +44 -11
- package/dist/switchboard-cwUp3FxP.js.map +1 -0
- package/package.json +9 -9
- package/dist/document-model-modules-BwnWiVeC.js.map +0 -1
- package/dist/global-Cgi-GJpN.d.ts.map +0 -1
- package/dist/make-ph-event-functions-C1JTfEw1.js.map +0 -1
- package/dist/navigation-BUPIObES.js.map +0 -1
- package/dist/switchboard-CiYrfAcM.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { _t as OperationsCacheEntry, dt as IReactorBrowserClient, gt as IOperationCache } from "../../global-
|
|
2
|
-
import { $ as
|
|
1
|
+
import { _t as OperationsCacheEntry, dt as IReactorBrowserClient, gt as IOperationCache } from "../../global-D-VZTZRz.js";
|
|
2
|
+
import { $ as ReactorOperationFieldsFragmentDoc, A as useDocument, B as isAuthRefusalClose, Ct as GetDocumentQueryResult, Dt as phDocumentFromMutation, Et as phDocumentFromGetDocument, F as useGetDocumentAsync, G as packageFromDocumentModels, H as startDocumentChangesSubscription, I as useGetDocuments, J as signStampedAction, Jt as IDLE_OPERATIONS_ENTRY, K as resolveDocumentModelModule, L as ConnectionParams, M as useDocumentSafe, N as useDocuments, Ot as revisionMapFromRevisionsList, P as useGetDocument, Q as MutateDocumentWithOperationsVariables, R as DocumentChangesEventPayload, St as GetDocumentQueryFields, Tt as isoStringFromDateTime, U as subscriptionsUrlFromGraphqlUrl, V as makeAuthConnectionParams, W as StaticPackageManager, X as MutateDocumentWithOperationsDocument, Xt as isOperationCache, Y as stampAction, Yt as addPromiseState, Z as MutateDocumentWithOperationsResult, Zt as readPromiseState, _t as GraphQLOperationNotSupportedError, a as DocumentOperationsState, at as GraphQLReactorClient, bt as ambientRenownTokenProvider, c as useDocumentModelModuleById, ct as isGraphQLReactorClient, d as UseDispatchResult, dt as SubgraphSdkFactory, et as GraphQLReactorProvider, ft as SubgraphSdkRegistry, gt as BatchJobFailedError, ht as subgraphUrlFromGraphqlUrl, i as DocumentOperationsResult, it as DriveIdCall, j as useDocumentCache, k as setDocumentCache, l as useDocumentModelModules, lt as viewFilterInputFromViewFilter, mt as describeGraphQLDocument, nt as ensurePHEventHandlers, o as UseDocumentOperationsOptions, ot as GraphQLReactorClientOptions, p as useDispatch, pt as TypedGraphQLDocument, q as prepareSignedActions, qt as DocumentCache, r as useAttachmentService, rt as useSwitchboardClient, s as useDocumentOperations, st as findIsServableOverGraphQL, tt as GraphQLReactorProviderProps, u as DispatchFn, ut as GraphQLRequestOptions, vt as GraphQLWrongBackendError, w as useReactorClient, wt as RevisionsListSelection, xt as makeAuthMiddleware, y as setReactorClient, yt as BearerTokenProvider, z as DocumentChangesSubscriptionOptions } from "../../attachment-service-CAf9N-15.js";
|
|
3
3
|
import { k as SdkFunctionWrapper } from "../../types-0Fh1tNjy.js";
|
|
4
4
|
export { BatchJobFailedError, BearerTokenProvider, ConnectionParams, type DispatchFn, DocumentCache, DocumentChangesEventPayload, DocumentChangesSubscriptionOptions, type DocumentOperationsResult, type DocumentOperationsState, DriveIdCall, GetDocumentQueryFields, GetDocumentQueryResult, GraphQLOperationNotSupportedError, GraphQLReactorClient, GraphQLReactorClientOptions, GraphQLReactorProvider, GraphQLReactorProviderProps, GraphQLRequestOptions, GraphQLWrongBackendError, IDLE_OPERATIONS_ENTRY, type IOperationCache, type IReactorBrowserClient, MutateDocumentWithOperationsDocument, MutateDocumentWithOperationsResult, MutateDocumentWithOperationsVariables, type OperationsCacheEntry, ReactorOperationFieldsFragmentDoc, RevisionsListSelection, type SdkFunctionWrapper, StaticPackageManager, SubgraphSdkFactory, SubgraphSdkRegistry, TypedGraphQLDocument, type UseDispatchResult, type UseDocumentOperationsOptions, addPromiseState, ambientRenownTokenProvider, describeGraphQLDocument, ensurePHEventHandlers, findIsServableOverGraphQL, isAuthRefusalClose, isGraphQLReactorClient, isOperationCache, isoStringFromDateTime, makeAuthConnectionParams, makeAuthMiddleware, packageFromDocumentModels, phDocumentFromGetDocument, phDocumentFromMutation, prepareSignedActions, readPromiseState, resolveDocumentModelModule, revisionMapFromRevisionsList, setDocumentCache, setReactorClient, signStampedAction, stampAction, startDocumentChangesSubscription, subgraphUrlFromGraphqlUrl, subscriptionsUrlFromGraphqlUrl, useAttachmentService, useDispatch, useDocument, useDocumentCache, useDocumentModelModuleById, useDocumentModelModules, useDocumentOperations, useDocumentSafe, useDocuments, useGetDocument, useGetDocumentAsync, useGetDocuments, useReactorClient, useSwitchboardClient, viewFilterInputFromViewFilter };
|
|
5
5
|
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import {
|
|
3
|
-
import { $r as signStampedAction, Br as isGraphQLReactorClient, Gr as subscriptionsUrlFromGraphqlUrl, Hr as isAuthRefusalClose, I as useAttachmentService, Jr as subgraphUrlFromGraphqlUrl, Ki as useReactorClient, Kr as SubgraphSdkRegistry, Qr as prepareSignedActions, Rr as GraphQLReactorClient, Ur as makeAuthConnectionParams, Vi as setReactorClient, Vr as viewFilterInputFromViewFilter, Wr as startDocumentChangesSubscription, Xr as packageFromDocumentModels, Yr as StaticPackageManager, Zr as resolveDocumentModelModule, ai as GraphQLWrongBackendError, ci as phDocumentFromMutation, ei as stampAction, i as useSwitchboardClient, ii as GraphQLOperationNotSupportedError, li as revisionMapFromRevisionsList, n as GraphQLReactorProvider, ni as ReactorOperationFieldsFragmentDoc, oi as isoStringFromDateTime, qr as describeGraphQLDocument, r as ensurePHEventHandlers, ri as BatchJobFailedError, si as phDocumentFromGetDocument, t as useDocumentOperations, ti as MutateDocumentWithOperationsDocument, zr as findIsServableOverGraphQL } from "../../document-operations-
|
|
1
|
+
import { a as useDocument, c as useDocuments, d as useGetDocuments, f as DocumentCache, g as readPromiseState, h as isOperationCache, i as setDocumentCache, l as useGetDocument, m as addPromiseState, n as useDispatch, o as useDocumentCache, p as IDLE_OPERATIONS_ENTRY, s as useDocumentSafe, u as useGetDocumentAsync } from "../../dispatch-Dd_WEz35.js";
|
|
2
|
+
import { H as makeAuthMiddleware, V as ambientRenownTokenProvider, n as useDocumentModelModules, t as useDocumentModelModuleById } from "../../document-model-modules-DROQT_yu.js";
|
|
3
|
+
import { $r as signStampedAction, Br as isGraphQLReactorClient, Gr as subscriptionsUrlFromGraphqlUrl, Hr as isAuthRefusalClose, I as useAttachmentService, Jr as subgraphUrlFromGraphqlUrl, Ki as useReactorClient, Kr as SubgraphSdkRegistry, Qr as prepareSignedActions, Rr as GraphQLReactorClient, Ur as makeAuthConnectionParams, Vi as setReactorClient, Vr as viewFilterInputFromViewFilter, Wr as startDocumentChangesSubscription, Xr as packageFromDocumentModels, Yr as StaticPackageManager, Zr as resolveDocumentModelModule, ai as GraphQLWrongBackendError, ci as phDocumentFromMutation, ei as stampAction, i as useSwitchboardClient, ii as GraphQLOperationNotSupportedError, li as revisionMapFromRevisionsList, n as GraphQLReactorProvider, ni as ReactorOperationFieldsFragmentDoc, oi as isoStringFromDateTime, qr as describeGraphQLDocument, r as ensurePHEventHandlers, ri as BatchJobFailedError, si as phDocumentFromGetDocument, t as useDocumentOperations, ti as MutateDocumentWithOperationsDocument, zr as findIsServableOverGraphQL } from "../../document-operations-C6khz2If.js";
|
|
4
4
|
export { BatchJobFailedError, DocumentCache, GraphQLOperationNotSupportedError, GraphQLReactorClient, GraphQLReactorProvider, GraphQLWrongBackendError, IDLE_OPERATIONS_ENTRY, MutateDocumentWithOperationsDocument, ReactorOperationFieldsFragmentDoc, StaticPackageManager, SubgraphSdkRegistry, addPromiseState, ambientRenownTokenProvider, describeGraphQLDocument, ensurePHEventHandlers, findIsServableOverGraphQL, isAuthRefusalClose, isGraphQLReactorClient, isOperationCache, isoStringFromDateTime, makeAuthConnectionParams, makeAuthMiddleware, packageFromDocumentModels, phDocumentFromGetDocument, phDocumentFromMutation, prepareSignedActions, readPromiseState, resolveDocumentModelModule, revisionMapFromRevisionsList, setDocumentCache, setReactorClient, signStampedAction, stampAction, startDocumentChangesSubscription, subgraphUrlFromGraphqlUrl, subscriptionsUrlFromGraphqlUrl, useAttachmentService, useDispatch, useDocument, useDocumentCache, useDocumentModelModuleById, useDocumentModelModules, useDocumentOperations, useDocumentSafe, useDocuments, useGetDocument, useGetDocumentAsync, useGetDocuments, useReactorClient, useSwitchboardClient, viewFilterInputFromViewFilter };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { A as RENOWN_RETURN_URL_STRIPPED_PARAMS, B as UserIcon, C as CREDENTIAL_SCHEMA_EIP712_TYPE, D as ISSUER_TYPE, E as DOMAIN_TYPE, F as ChevronDownIcon, G as RenownLoginButtonProps, H as RenownUserButtonMenuItem, I as CopyIcon, K as RenownAuthButton, L as DisconnectIcon, M as VERIFIABLE_CREDENTIAL_EIP712_TYPE, N as initConnectCrypto, O as RENOWN_CHAIN_ID, P as initRenownCrypto, Q as useRenown, R as RenownLogo, S as useRenownInitialUser, T as CREDENTIAL_TYPES, U as RenownUserButtonProps, V as RenownUserButton, W as RenownLoginButton, _ as RENOWN_INITIAL_UNKNOWN, a as RenownWalletProviderProps, at as RenownAuthResolution, b as RenownInitialUserProviderProps, c as Renown, ct as useRenownAuthAsync, d as useRenownInit, f as RenownSessionCookieOptions, g as RENOWN_INITIAL_ANONYMOUS, h as useRenownSessionSynced, i as RenownWalletProvider, it as RenownAuthAsync, j as RENOWN_URL, k as RENOWN_NETWORK_ID, l as RenownProps, m as useRenownSessionCookie, n as RenownLoginMethod, nt as openRenown, o as RenownProvider, ot as RenownAuthStatus, p as RenownSessionCookieState, q as RenownAuthButtonProps, r as useRenownLoginMethods, rt as RenownAuth, s as RenownProviderProps, st as useRenownAuth, t as useRenownWalletAdapter, u as RenownInitOptions, v as RenownInitialAuth, w as CREDENTIAL_SUBJECT_TYPE, x as useRenownInitialAuth, y as RenownInitialUserProvider, z as SpinnerIcon } from "../../index-
|
|
1
|
+
import { A as RENOWN_RETURN_URL_STRIPPED_PARAMS, B as UserIcon, C as CREDENTIAL_SCHEMA_EIP712_TYPE, D as ISSUER_TYPE, E as DOMAIN_TYPE, F as ChevronDownIcon, G as RenownLoginButtonProps, H as RenownUserButtonMenuItem, I as CopyIcon, K as RenownAuthButton, L as DisconnectIcon, M as VERIFIABLE_CREDENTIAL_EIP712_TYPE, N as initConnectCrypto, O as RENOWN_CHAIN_ID, P as initRenownCrypto, Q as useRenown, R as RenownLogo, S as useRenownInitialUser, T as CREDENTIAL_TYPES, U as RenownUserButtonProps, V as RenownUserButton, W as RenownLoginButton, _ as RENOWN_INITIAL_UNKNOWN, a as RenownWalletProviderProps, at as RenownAuthResolution, b as RenownInitialUserProviderProps, c as Renown, ct as useRenownAuthAsync, d as useRenownInit, f as RenownSessionCookieOptions, g as RENOWN_INITIAL_ANONYMOUS, h as useRenownSessionSynced, i as RenownWalletProvider, it as RenownAuthAsync, j as RENOWN_URL, k as RENOWN_NETWORK_ID, l as RenownProps, m as useRenownSessionCookie, n as RenownLoginMethod, nt as openRenown, o as RenownProvider, ot as RenownAuthStatus, p as RenownSessionCookieState, q as RenownAuthButtonProps, r as useRenownLoginMethods, rt as RenownAuth, s as RenownProviderProps, st as useRenownAuth, t as useRenownWalletAdapter, u as RenownInitOptions, v as RenownInitialAuth, w as CREDENTIAL_SUBJECT_TYPE, x as useRenownInitialAuth, y as RenownInitialUserProvider, z as SpinnerIcon } from "../../index-XfcUiODQ.js";
|
|
2
2
|
export { CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, ChevronDownIcon, CopyIcon, DOMAIN_TYPE, DisconnectIcon, ISSUER_TYPE, RENOWN_CHAIN_ID, RENOWN_INITIAL_ANONYMOUS, RENOWN_INITIAL_UNKNOWN, RENOWN_NETWORK_ID, RENOWN_RETURN_URL_STRIPPED_PARAMS, RENOWN_URL, Renown, type RenownAuth, type RenownAuthAsync, RenownAuthButton, type RenownAuthButtonProps, type RenownAuthResolution, type RenownAuthStatus, type RenownInitOptions, type RenownInitialAuth, RenownInitialUserProvider, type RenownInitialUserProviderProps, RenownLoginButton, type RenownLoginButtonProps, type RenownLoginMethod, RenownLogo, type RenownProps, RenownProvider, type RenownProviderProps, type RenownSessionCookieOptions, type RenownSessionCookieState, RenownUserButton, type RenownUserButtonMenuItem, type RenownUserButtonProps, RenownWalletProvider, type RenownWalletProviderProps, SpinnerIcon, UserIcon, VERIFIABLE_CREDENTIAL_EIP712_TYPE, initConnectCrypto, initRenownCrypto, openRenown, useRenown, useRenownAuth, useRenownAuthAsync, useRenownInit, useRenownInitialAuth, useRenownInitialUser, useRenownLoginMethods, useRenownSessionCookie, useRenownSessionSynced, useRenownWalletAdapter };
|
|
3
3
|
export {};
|
package/dist/src/renown/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as useRenown, c as RENOWN_INITIAL_UNKNOWN, d as useRenownInitialUser, l as RenownInitialUserProvider, s as RENOWN_INITIAL_ANONYMOUS, u as useRenownInitialAuth } from "../../renown-
|
|
2
|
-
import { A as RENOWN_CHAIN_ID, D as CREDENTIAL_TYPES, E as CREDENTIAL_SUBJECT_TYPE, M as RENOWN_RETURN_URL_STRIPPED_PARAMS, N as RENOWN_URL, O as DOMAIN_TYPE, P as VERIFIABLE_CREDENTIAL_EIP712_TYPE, T as CREDENTIAL_SCHEMA_EIP712_TYPE, _ as RenownLogo, a as Renown, b as useRenownAuth, c as useRenownSessionSynced, d as RenownAuthButton, f as RenownUserButton, g as DisconnectIcon, h as CopyIcon, i as RenownWalletProvider, j as RENOWN_NETWORK_ID, k as ISSUER_TYPE, l as initConnectCrypto, m as ChevronDownIcon, n as useRenownLoginMethods, o as useRenownInit, p as RenownLoginButton, r as RenownProvider, s as useRenownSessionCookie, t as useRenownWalletAdapter, u as initRenownCrypto, v as SpinnerIcon, w as openRenown, x as useRenownAuthAsync, y as UserIcon } from "../../renown-
|
|
1
|
+
import { a as useRenown, c as RENOWN_INITIAL_UNKNOWN, d as useRenownInitialUser, l as RenownInitialUserProvider, s as RENOWN_INITIAL_ANONYMOUS, u as useRenownInitialAuth } from "../../renown-BxkZYzbQ.js";
|
|
2
|
+
import { A as RENOWN_CHAIN_ID, D as CREDENTIAL_TYPES, E as CREDENTIAL_SUBJECT_TYPE, M as RENOWN_RETURN_URL_STRIPPED_PARAMS, N as RENOWN_URL, O as DOMAIN_TYPE, P as VERIFIABLE_CREDENTIAL_EIP712_TYPE, T as CREDENTIAL_SCHEMA_EIP712_TYPE, _ as RenownLogo, a as Renown, b as useRenownAuth, c as useRenownSessionSynced, d as RenownAuthButton, f as RenownUserButton, g as DisconnectIcon, h as CopyIcon, i as RenownWalletProvider, j as RENOWN_NETWORK_ID, k as ISSUER_TYPE, l as initConnectCrypto, m as ChevronDownIcon, n as useRenownLoginMethods, o as useRenownInit, p as RenownLoginButton, r as RenownProvider, s as useRenownSessionCookie, t as useRenownWalletAdapter, u as initRenownCrypto, v as SpinnerIcon, w as openRenown, x as useRenownAuthAsync, y as UserIcon } from "../../renown-BtjgHBjH.js";
|
|
3
3
|
export { CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, ChevronDownIcon, CopyIcon, DOMAIN_TYPE, DisconnectIcon, ISSUER_TYPE, RENOWN_CHAIN_ID, RENOWN_INITIAL_ANONYMOUS, RENOWN_INITIAL_UNKNOWN, RENOWN_NETWORK_ID, RENOWN_RETURN_URL_STRIPPED_PARAMS, RENOWN_URL, Renown, RenownAuthButton, RenownInitialUserProvider, RenownLoginButton, RenownLogo, RenownProvider, RenownUserButton, RenownWalletProvider, SpinnerIcon, UserIcon, VERIFIABLE_CREDENTIAL_EIP712_TYPE, initConnectCrypto, initRenownCrypto, openRenown, useRenown, useRenownAuth, useRenownAuthAsync, useRenownInit, useRenownInitialAuth, useRenownInitialUser, useRenownLoginMethods, useRenownSessionCookie, useRenownSessionSynced, useRenownWalletAdapter };
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { n as useDocumentsByIds, t as useDocumentById } from "./document-by-id-
|
|
1
|
+
import { c as getPHStore } from "./make-ph-event-functions-B5GU5xcR.js";
|
|
2
|
+
import { O as useSelectedNodeId, P as useDriveContext, R as DocumentTypeMismatchError, V as ambientRenownTokenProvider, g as useSelectedDriveSafe, t as useDocumentModelModuleById, z as NoSelectedDocumentError } from "./document-model-modules-DROQT_yu.js";
|
|
3
|
+
import { n as useDocumentsByIds, t as useDocumentById } from "./document-by-id-DqAyjr9P.js";
|
|
4
|
+
import { createContext, useContext, useMemo } from "react";
|
|
5
|
+
import { jsx } from "react/jsx-runtime";
|
|
4
6
|
import { DriveCollectionId, ModuleNotFoundError } from "@powerhousedao/reactor";
|
|
5
7
|
import { isFileNode } from "@powerhousedao/shared/document-drive";
|
|
6
8
|
import { z } from "zod";
|
|
@@ -66,28 +68,59 @@ function useDocumentOfType(documentId, documentType) {
|
|
|
66
68
|
return [document, dispatch];
|
|
67
69
|
}
|
|
68
70
|
//#endregion
|
|
71
|
+
//#region src/hooks/editor-context.tsx
|
|
72
|
+
const EditorDocumentContext = createContext(void 0);
|
|
73
|
+
/** Hosts render an editor inside this, with the same `document` and `dispatch`
|
|
74
|
+
* as its props; `useSelected*Document` hooks below read them. */
|
|
75
|
+
function EditorDocumentProvider(props) {
|
|
76
|
+
const { document, dispatch } = props;
|
|
77
|
+
const value = useMemo(() => [document, dispatch], [document, dispatch]);
|
|
78
|
+
return /* @__PURE__ */ jsx(EditorDocumentContext.Provider, {
|
|
79
|
+
value,
|
|
80
|
+
children: props.children
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/** The nearest editor's document and dispatch, or undefined outside one. */
|
|
84
|
+
function useEditorDocumentContext() {
|
|
85
|
+
return useContext(EditorDocumentContext);
|
|
86
|
+
}
|
|
87
|
+
//#endregion
|
|
69
88
|
//#region src/hooks/selected-document.ts
|
|
70
|
-
/** Returns the selected document id
|
|
89
|
+
/** Returns the selected document id: the editor's document, else the drive
|
|
90
|
+
* app's open document, else the app's selection. */
|
|
71
91
|
function useSelectedDocumentId() {
|
|
92
|
+
const editor = useEditorDocumentContext();
|
|
93
|
+
const drive = useDriveContext();
|
|
72
94
|
const selectedNode = useSelectedNode();
|
|
95
|
+
if (editor) return editor[0].header.id;
|
|
96
|
+
if (drive?.nodeId && !drive.folder) return selectedNode && !isFileNode(selectedNode) ? void 0 : drive.nodeId;
|
|
73
97
|
return selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;
|
|
74
98
|
}
|
|
75
99
|
/** Returns the selected document. */
|
|
76
100
|
function useSelectedDocument() {
|
|
77
|
-
const
|
|
78
|
-
const [document, dispatch] = useDocumentById(selectedDocumentId);
|
|
101
|
+
const [document, dispatch] = useSelectedDocumentSafe();
|
|
79
102
|
if (!document) throw new NoSelectedDocumentError();
|
|
80
103
|
return [document, dispatch];
|
|
81
104
|
}
|
|
82
|
-
/** Returns the selected document. */
|
|
105
|
+
/** Returns the selected document: the editor's, else the app's selection. */
|
|
83
106
|
function useSelectedDocumentSafe() {
|
|
107
|
+
const editor = useEditorDocumentContext();
|
|
84
108
|
const selectedDocumentId = useSelectedDocumentId();
|
|
85
|
-
|
|
109
|
+
const selected = useDocumentById(editor ? null : selectedDocumentId);
|
|
110
|
+
return editor ?? selected;
|
|
86
111
|
}
|
|
87
112
|
function useSelectedDocumentOfType(documentType) {
|
|
113
|
+
const editor = useEditorDocumentContext();
|
|
88
114
|
const documentId = useSelectedDocumentId();
|
|
89
|
-
const result = useDocumentOfType(documentType ? documentId : null, documentType);
|
|
115
|
+
const result = useDocumentOfType(documentType && !editor ? documentId : null, documentType);
|
|
116
|
+
const documentModelModule = useDocumentModelModuleById(documentType);
|
|
90
117
|
if (!documentType) return [];
|
|
118
|
+
if (editor) {
|
|
119
|
+
const [document, dispatch] = editor;
|
|
120
|
+
if (!documentModelModule) throw new ModuleNotFoundError(documentType);
|
|
121
|
+
if (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(document.header.id, documentType, document.header.documentType);
|
|
122
|
+
return [document, dispatch];
|
|
123
|
+
}
|
|
91
124
|
if (!documentId) throw new NoSelectedDocumentError();
|
|
92
125
|
return result;
|
|
93
126
|
}
|
|
@@ -320,6 +353,6 @@ function createSwitchboardSchemaTool(deps) {
|
|
|
320
353
|
};
|
|
321
354
|
}
|
|
322
355
|
//#endregion
|
|
323
|
-
export {
|
|
356
|
+
export { sortNodesByName as C, isFolderNodeKind as S, useDocumentsInSelectedDrive as _, getBrowserSyncManager as a, useNodesInSelectedDrive as b, useSelectedDocument as c, useSelectedDocumentSafe as d, EditorDocumentProvider as f, useDocumentTypesInSelectedDrive as g, useSelectedNode as h, createSwitchboardSchemaTool as i, useSelectedDocumentId as l, useDocumentOfType as m, SWITCHBOARD_INTROSPECTION_QUERY as n, resolveDriveSwitchboard as o, useEditorDocumentContext as p, SWITCHBOARD_SCHEMA_TOOL_NAME as r, summarizeIntrospectionSchema as s, GQL_CHANNEL_SUFFIX as t, useSelectedDocumentOfType as u, useFileNodesInSelectedDrive as v, isFileNodeKind as x, useFolderNodesInSelectedDrive as y };
|
|
324
357
|
|
|
325
|
-
//# sourceMappingURL=switchboard-
|
|
358
|
+
//# sourceMappingURL=switchboard-cwUp3FxP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"switchboard-cwUp3FxP.js","names":[],"sources":["../src/utils/nodes.ts","../src/hooks/items-in-selected-drive.ts","../src/hooks/selected-node.ts","../src/hooks/document-of-type.ts","../src/hooks/editor-context.tsx","../src/hooks/selected-document.ts","../src/ai/switchboard.ts"],"sourcesContent":["import type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n","import type {\n FileNode,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelDocument,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { isFileNodeKind, isFolderNodeKind } from \"../utils/nodes.js\";\nimport { useDocumentsByIds } from \"./document-by-id.js\";\nimport { useSelectedDriveSafe } from \"./selected-drive.js\";\n\n/** Returns the nodes in the selected drive. */\nexport function useNodesInSelectedDrive() {\n const [selectedDrive] = useSelectedDriveSafe();\n return selectedDrive?.state.global.nodes;\n}\n\n/** Returns the file nodes in the selected drive. */\nexport function useFileNodesInSelectedDrive(): FileNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFileNodeKind(n));\n}\n\n/** Returns the folder nodes in the selected drive. */\nexport function useFolderNodesInSelectedDrive(): FolderNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFolderNodeKind(n));\n}\n\n/** Returns the documents in the selected drive. */\nexport function useDocumentsInSelectedDrive(): PHDocument[] | undefined {\n const fileNodes = useFileNodesInSelectedDrive();\n const fileNodeIds = fileNodes?.map((node) => node.id);\n return useDocumentsByIds(fileNodeIds);\n}\n\n/** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */\nexport function useDocumentTypesInSelectedDrive() {\n const documentsInSelectedDrive = useDocumentsInSelectedDrive();\n const documentModelDocumentsInSelectedDrive =\n documentsInSelectedDrive?.filter(isDocumentModelDocument);\n const documentTypesFromDocumentModelDocuments =\n documentModelDocumentsInSelectedDrive?.map((doc) => doc.state.global.id);\n return documentTypesFromDocumentModelDocuments;\n}\n\nfunction isDocumentModelDocument(\n document: PHDocument,\n): document is DocumentModelDocument {\n return document.header.documentType === \"powerhouse/document-model\";\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedNodeId } from \"./set-selected-node.js\";\n\nexport {\n addResetSelectedNodeEventHandler,\n addSelectedNodeIdEventHandler,\n getNodeTarget,\n useNodeTarget,\n preloadNode,\n setSelectedNode,\n setSelectedNodeId,\n useOpenNode,\n usePreloadNode,\n useSetSelectedNode,\n} from \"./set-selected-node.js\";\nexport { addSetSelectedNodeOnPopStateEventHandler } from \"./sync-selection.js\";\n\n/** Returns the selected node. */\nexport function useSelectedNode(): Node | undefined {\n const selectedNodeId = useSelectedNodeId();\n const nodes = useNodesInSelectedDrive();\n return nodes?.find((n) => n.id === selectedNodeId);\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { DocumentTypeMismatchError } from \"../errors.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\n\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nexport function useDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentId: string | null | undefined,\n documentType: string | null | undefined,\n) {\n const [document, dispatch] = useDocumentById(documentId);\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentId || !documentType) return [];\n\n if (!document) {\n throw new Error(`Document not found: ${documentId}`);\n }\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n documentId,\n documentType,\n document.header.documentType,\n );\n }\n\n return [document, dispatch] as [TDocument, DocumentDispatch<TAction>];\n}\n","import type {\n DocumentDispatch,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext, useMemo } from \"react\";\n\n/** The document an editor is rendered with, and a dispatch bound to it. */\nexport type EditorDocumentContextValue = readonly [\n PHDocument,\n DocumentDispatch,\n];\n\nconst EditorDocumentContext = createContext<\n EditorDocumentContextValue | undefined\n>(undefined);\n\n/** Hosts render an editor inside this, with the same `document` and `dispatch`\n * as its props; `useSelected*Document` hooks below read them. */\nexport function EditorDocumentProvider(props: {\n document: PHDocument;\n dispatch: DocumentDispatch;\n children: ReactNode;\n}) {\n const { document, dispatch } = props;\n const value = useMemo(\n () => [document, dispatch] as const,\n [document, dispatch],\n );\n return (\n <EditorDocumentContext.Provider value={value}>\n {props.children}\n </EditorDocumentContext.Provider>\n );\n}\n\n/** The nearest editor's document and dispatch, or undefined outside one. */\nexport function useEditorDocumentContext() {\n return useContext(EditorDocumentContext);\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport {\n DocumentTypeMismatchError,\n NoSelectedDocumentError,\n} from \"../errors.js\";\nimport type { DispatchFn, UseDispatchResult } from \"./dispatch.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\nimport { useDocumentOfType } from \"./document-of-type.js\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { useEditorDocumentContext } from \"./editor-context.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected document id: the editor's document, else the drive\n * app's open document, else the app's selection. */\nexport function useSelectedDocumentId(): string | undefined {\n const editor = useEditorDocumentContext();\n const drive = useDriveContext();\n const selectedNode = useSelectedNode();\n if (editor) return editor[0].header.id;\n // The drive may not list a document the route opened yet.\n if (drive?.nodeId && !drive.folder) {\n return selectedNode && !isFileNode(selectedNode) ? undefined : drive.nodeId;\n }\n return selectedNode && isFileNode(selectedNode) ? selectedNode.id : undefined;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocument(): readonly [\n PHDocument,\n DispatchFn<Action>,\n] {\n const [document, dispatch] = useSelectedDocumentSafe();\n if (!document) {\n throw new NoSelectedDocumentError();\n }\n return [document, dispatch] as const;\n}\n\n/** Returns the selected document: the editor's, else the app's selection. */\nexport function useSelectedDocumentSafe(): UseDispatchResult<\n PHDocument,\n Action\n> {\n const editor = useEditorDocumentContext();\n const selectedDocumentId = useSelectedDocumentId();\n const selected = useDocumentById(editor ? null : selectedDocumentId);\n return editor ?? selected;\n}\n\n/** Returns the selected document of a specific type, throws an error if the found document has a different type */\nexport function useSelectedDocumentOfType(\n documentType: null | undefined,\n): never[];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(documentType: string): [TDocument, DocumentDispatch<TAction>];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentType: string | null | undefined,\n): never[] | [TDocument, DocumentDispatch<TAction>] {\n const editor = useEditorDocumentContext();\n const documentId = useSelectedDocumentId();\n // Called on every render; without a type, or in an editor, it reads no document.\n const result = useDocumentOfType<TDocument, TAction>(\n documentType && !editor ? documentId : null,\n documentType,\n );\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentType) {\n return [];\n }\n if (editor) {\n const [document, dispatch] = editor;\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n document.header.id,\n documentType,\n document.header.documentType,\n );\n }\n return [document as TDocument, dispatch];\n }\n if (!documentId) {\n throw new NoSelectedDocumentError();\n }\n return result;\n}\n","import { getPHStore } from \"../hooks/ph-store.js\";\nimport { DriveCollectionId, type ISyncManager } from \"@powerhousedao/reactor\";\nimport { z } from \"zod\";\nimport { ambientRenownTokenProvider } from \"../graphql-client/auth.js\";\nimport type { AiToolDescriptor } from \"./types.js\";\n\n/**\n * The switchboard serving a remote drive: the base URL the browser talks to\n * and its GraphQL supergraph endpoint.\n */\nexport interface DriveSwitchboard {\n /** Switchboard base URL (e.g. `http://localhost:4001`). */\n switchboardUrl: string;\n /** GraphQL supergraph endpoint (`<base>/graphql`). */\n graphqlUrl: string;\n}\n\n/**\n * Reads the tab-side sync manager from the browser global. Returns\n * `undefined` in non-browser environments or before the reactor client\n * module is initialized.\n */\nexport function getBrowserSyncManager(): ISyncManager | undefined {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n return getPHStore()?.reactorClientModule?.reactorModule?.syncModule\n ?.syncManager;\n}\n\n/** Suffix of the per-drive GraphQL channel endpoint the switchboard serves. */\nexport const GQL_CHANNEL_SUFFIX = \"/graphql/r\";\n\n/**\n * Resolves the switchboard that serves a drive, if any.\n *\n * Every remote drive stores its switchboard's exact GraphQL channel\n * endpoint in its sync remote — `channelConfig = { type: \"gql\",\n * parameters: { url: \"<origin>/graphql/r\" } }` — and the switchboard base\n * is that URL minus the `/graphql/r` suffix. Deriving it per drive (rather\n * than from a global setting) is what keeps multi-switchboard deployments\n * correct. Drives that are not synced to a remote switchboard (local\n * drives, other channel types, unexpected shapes) return `undefined`.\n */\nexport function resolveDriveSwitchboard(\n driveId: string | undefined,\n syncManager?: ISyncManager,\n): DriveSwitchboard | undefined {\n const manager = syncManager ?? getBrowserSyncManager();\n if (!driveId || !manager) {\n return undefined;\n }\n const collectionId = DriveCollectionId.forDrive(driveId);\n const remote = manager\n .list()\n .find((r) => r.meta.collectionId.equals(collectionId));\n if (!remote) {\n return undefined;\n }\n const { channelConfig } = remote.meta;\n if (channelConfig.type !== \"gql\") {\n return undefined;\n }\n const url = channelConfig.parameters.url;\n if (typeof url !== \"string\" || !url.endsWith(GQL_CHANNEL_SUFFIX)) {\n return undefined;\n }\n const switchboardUrl = url.slice(0, -GQL_CHANNEL_SUFFIX.length);\n return { switchboardUrl, graphqlUrl: `${switchboardUrl}/graphql` };\n}\n\n/** A bounded introspected GraphQL type reference (see the query below). */\ntype IntrospectedTypeRef = {\n kind: string;\n name: string | null;\n ofType?: IntrospectedTypeRef | null;\n};\n\ntype IntrospectedField = {\n name: string;\n description: string | null;\n args: Array<{ name: string; type: IntrospectedTypeRef }>;\n type: IntrospectedTypeRef;\n};\n\ntype IntrospectedRootType = {\n fields: IntrospectedField[] | null;\n} | null;\n\ntype IntrospectedSchema = {\n queryType?: IntrospectedRootType;\n mutationType?: IntrospectedRootType;\n};\n\n/**\n * Introspection over the switchboard supergraph's root query and mutation\n * fields. Types are requested with three levels of `ofType` nesting so\n * that common shapes like `[X!]!` (LIST(NON_NULL(LIST(X)))) render fully.\n */\nexport const SWITCHBOARD_INTROSPECTION_QUERY: string = /* GraphQL */ `\n query SwitchboardIntrospection {\n __schema {\n queryType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n mutationType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n`;\n\n/**\n * Renders an introspected type reference as a GraphQL type string.\n * Recursion is bounded by the `ofType` nesting of the query, so it always\n * terminates.\n */\nfunction renderTypeRef(type: IntrospectedTypeRef | null | undefined): string {\n if (!type) {\n return \"Unknown\";\n }\n switch (type.kind) {\n case \"NON_NULL\":\n return `${renderTypeRef(type.ofType)}!`;\n case \"LIST\":\n return `[${renderTypeRef(type.ofType)}]`;\n default:\n return type.name ?? \"Unknown\";\n }\n}\n\n/** One root query or mutation field, reduced to a prompt-friendly line. */\nexport type SchemaFieldSummary = {\n name: string;\n description?: string;\n args: string;\n returns: string;\n};\n\n/** Cap on the number of fields reported per root type. */\nconst MAX_FIELDS_PER_ROOT = 200;\n\nfunction summarizeFields(fields: IntrospectedField[] | null | undefined): {\n fields: SchemaFieldSummary[];\n truncated: boolean;\n} {\n const list = fields ?? [];\n return {\n fields: list.slice(0, MAX_FIELDS_PER_ROOT).map((field) => ({\n name: field.name,\n ...(field.description ? { description: field.description } : {}),\n args: field.args\n .map((arg) => `${arg.name}: ${renderTypeRef(arg.type)}`)\n .join(\", \"),\n returns: renderTypeRef(field.type),\n })),\n truncated: list.length > MAX_FIELDS_PER_ROOT,\n };\n}\n\n/**\n * Reduces a GraphQL `__schema` introspection payload (the `data.__schema`\n * object) to a compact summary of its root query and mutation fields.\n * Accepts `unknown` because the payload arrives over the wire.\n */\nexport function summarizeIntrospectionSchema(schema: unknown): {\n queries: SchemaFieldSummary[];\n mutations: SchemaFieldSummary[];\n truncated: boolean;\n} {\n const introspection = (schema ?? {}) as IntrospectedSchema;\n const queries = summarizeFields(introspection.queryType?.fields);\n const mutations = summarizeFields(introspection.mutationType?.fields);\n return {\n queries: queries.fields,\n mutations: mutations.fields,\n truncated: queries.truncated || mutations.truncated,\n };\n}\n\nexport const SWITCHBOARD_SCHEMA_TOOL_NAME = \"getSwitchboardSchema\";\n\n/** Test seams for {@link createSwitchboardSchemaTool}. */\nexport interface SwitchboardToolDeps {\n getSyncManager?: () => ISyncManager | undefined;\n getSelectedDriveId?: () => string | undefined;\n tokenProvider?: () => Promise<string | undefined>;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}\n\n/**\n * Creates the read-only `getSwitchboardSchema` tool: it introspects the\n * GraphQL supergraph of the switchboard serving a drive and returns a\n * summary of its root queries and mutations. It reads the schema only and\n * never modifies data.\n */\nexport function createSwitchboardSchemaTool(\n deps?: SwitchboardToolDeps,\n): AiToolDescriptor {\n const getSyncManager = deps?.getSyncManager ?? getBrowserSyncManager;\n const getSelectedDriveId =\n deps?.getSelectedDriveId ??\n ((): string | undefined =>\n typeof window === \"undefined\"\n ? undefined\n : getPHStore()?.selectedDriveId);\n const tokenProvider = deps?.tokenProvider ?? ambientRenownTokenProvider;\n const fetchImpl = deps?.fetchImpl ?? fetch;\n const timeoutMs = deps?.timeoutMs ?? 10_000;\n\n return {\n name: SWITCHBOARD_SCHEMA_TOOL_NAME,\n description:\n \"Introspect the GraphQL endpoint of the switchboard serving a drive and list the queries and mutations it exposes (reactor operations, document-model read models, package subgraphs). Read-only: it reads the schema only and never modifies data. Omit driveId to introspect the currently selected drive.\",\n inputSchema: {\n driveId: z\n .string()\n .describe(\n \"Drive to introspect. Omit to use the currently selected drive.\",\n )\n .optional(),\n },\n annotations: { readOnlyHint: true },\n callback: async (input: { driveId?: string } | undefined) => {\n const driveId = input?.driveId ?? getSelectedDriveId();\n const sb = resolveDriveSwitchboard(driveId, getSyncManager());\n if (!sb) {\n throw new Error(\n driveId\n ? `Drive \"${driveId}\" has no switchboard: it is not synced to a remote switchboard.`\n : \"No drive is currently selected and no driveId was given.\",\n );\n }\n\n const token = await tokenProvider();\n let response: Response;\n try {\n response = await fetchImpl(sb.graphqlUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({ query: SWITCHBOARD_INTROSPECTION_QUERY }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} is not reachable: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} refused the request (HTTP ${response.status}). Sign in to the switchboard (Renown) and try again.`,\n );\n }\n if (!response.ok) {\n throw new Error(\n `Switchboard introspection failed: HTTP ${response.status} ${response.statusText} from ${sb.graphqlUrl}`,\n );\n }\n\n const body = (await response.json()) as {\n errors?: Array<{ message?: string }>;\n data?: { __schema?: unknown } | null;\n } | null;\n const schemaErrors = body?.errors;\n if (schemaErrors && schemaErrors.length > 0) {\n throw new Error(\n schemaErrors.map((e) => e.message ?? \"unknown error\").join(\"; \"),\n );\n }\n const schema = body?.data?.__schema as\n | IntrospectedSchema\n | null\n | undefined;\n if (!schema?.queryType) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} did not return a GraphQL schema.`,\n );\n }\n\n const summary = summarizeIntrospectionSchema(schema);\n return {\n switchboardUrl: sb.switchboardUrl,\n graphqlUrl: sb.graphqlUrl,\n ...summary,\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,gBAAgC,OAAY;CAC1D,OAAO,MAAM,UAAU,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAC9D;;AAGA,SAAgB,eACd,MACkB;CAClB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;;AAGA,SAAgB,iBACd,MACoB;CACpB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;;;;ACZA,SAAgB,0BAA0B;CACxC,MAAM,CAAC,iBAAiB,qBAAqB;CAC7C,OAAO,eAAe,MAAM,OAAO;AACrC;;AAGA,SAAgB,8BAAsD;CAEpE,OADc,wBACH,CAAC,EAAE,QAAQ,MAAM,eAAe,CAAC,CAAC;AAC/C;;AAGA,SAAgB,gCAA0D;CAExE,OADc,wBACH,CAAC,EAAE,QAAQ,MAAM,iBAAiB,CAAC,CAAC;AACjD;;AAGA,SAAgB,8BAAwD;CAEtE,MAAM,cADY,4BACU,CAAC,EAAE,KAAK,SAAS,KAAK,EAAE;CACpD,OAAO,kBAAkB,WA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G,WAAW,6BAA6B,SAAS,OAAO,sDAC/E;GAEF,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MACR,0CAA0C,SAAS,OAAO,GAAG,SAAS,WAAW,QAAQ,GAAG,YAC9F;GAGF,MAAM,OAAQ,MAAM,SAAS,KAAK;GAIlC,MAAM,eAAe,MAAM;GAC3B,IAAI,gBAAgB,aAAa,SAAS,GACxC,MAAM,IAAI,MACR,aAAa,KAAK,MAAM,EAAE,WAAW,eAAe,CAAC,CAAC,KAAK,IAAI,CACjE;GAEF,MAAM,SAAS,MAAM,MAAM;GAI3B,IAAI,CAAC,QAAQ,WACX,MAAM,IAAI,MACR,kBAAkB,GAAG,WAAW,kCAClC;GAGF,MAAM,UAAU,6BAA6B,MAAM;GACnD,OAAO;IACL,gBAAgB,GAAG;IACnB,YAAY,GAAG;IACf,GAAG;GACL;EACF;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/reactor-browser",
|
|
3
|
-
"version": "6.2.3-dev.
|
|
3
|
+
"version": "6.2.3-dev.70",
|
|
4
4
|
"license": "AGPL-3.0-only",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -64,17 +64,17 @@
|
|
|
64
64
|
"sideEffects": false,
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@ai-sdk/openai-compatible": "3.0.37",
|
|
67
|
-
"@powerhousedao/analytics-engine-browser": "6.2.3-dev.
|
|
68
|
-
"@powerhousedao/analytics-engine-core": "6.2.3-dev.
|
|
69
|
-
"@powerhousedao/reactor": "6.2.3-dev.
|
|
70
|
-
"@powerhousedao/reactor-attachments": "6.2.3-dev.
|
|
71
|
-
"@powerhousedao/reactor-drive": "6.2.3-dev.
|
|
72
|
-
"@powerhousedao/shared": "6.2.3-dev.
|
|
73
|
-
"@renown/sdk": "6.2.3-dev.
|
|
67
|
+
"@powerhousedao/analytics-engine-browser": "6.2.3-dev.70",
|
|
68
|
+
"@powerhousedao/analytics-engine-core": "6.2.3-dev.70",
|
|
69
|
+
"@powerhousedao/reactor": "6.2.3-dev.70",
|
|
70
|
+
"@powerhousedao/reactor-attachments": "6.2.3-dev.70",
|
|
71
|
+
"@powerhousedao/reactor-drive": "6.2.3-dev.70",
|
|
72
|
+
"@powerhousedao/shared": "6.2.3-dev.70",
|
|
73
|
+
"@renown/sdk": "6.2.3-dev.70",
|
|
74
74
|
"@tanstack/react-query": "^5.49.2",
|
|
75
75
|
"ai": "7.0.83",
|
|
76
76
|
"change-case": "5.4.4",
|
|
77
|
-
"document-model": "6.2.3-dev.
|
|
77
|
+
"document-model": "6.2.3-dev.70",
|
|
78
78
|
"graphql-request": "7.4.0",
|
|
79
79
|
"graphql-ws": "6.0.7",
|
|
80
80
|
"kysely": "0.28.16",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"document-model-modules-BwnWiVeC.js","names":[],"sources":["../src/graphql-client/auth.ts","../src/errors.ts","../src/routing/initial-sync.ts","../src/hooks/drives.ts","../src/hooks/set-selected-node.ts","../src/hooks/selected-drive.ts","../src/hooks/vetra-packages.ts","../src/hooks/document-model-modules.ts"],"sourcesContent":["import { getPHStore } from \"../hooks/ph-store.js\";\nimport type { SdkFunctionWrapper } from \"../graphql/gen/schema.js\";\n\n/**\n * Resolves the bearer token to send with a request.\n *\n * Returning `undefined` (or an empty string) means \"send this request\n * anonymously\": open Switchboards must keep serving reads to logged-out users.\n */\nexport type BearerTokenProvider = () => Promise<string | undefined>;\n\n/** Lifetime requested for an ambient Renown token, in seconds. */\nconst ambientTokenExpiresInSeconds = 600;\n\n/**\n * The default token provider: the token of the currently logged-in Renown user.\n *\n * It is deliberately resolved from `window.ph` on every call rather than\n * captured at construction time, so a client built before login starts sending\n * the token as soon as there is one.\n *\n * The token is requested WITHOUT an `aud` claim - the Switchboard verifier\n * rejects tokens that carry an audience.\n */\nexport async function ambientRenownTokenProvider(): Promise<\n string | undefined\n> {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n\n const renown = getPHStore()?.renown;\n if (!renown?.user) {\n return undefined;\n }\n\n return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });\n}\n\n/**\n * Builds the SDK middleware that authenticates every request.\n *\n * The token is resolved per request and never cached, so a login, a logout or\n * an expiry between two calls is picked up by the next one. When no token is\n * available the request goes out unauthenticated.\n */\nexport function makeAuthMiddleware(\n tokenProvider: BearerTokenProvider,\n): SdkFunctionWrapper {\n return async (action) => {\n const token = await tokenProvider();\n if (!token) {\n return action();\n }\n\n return action({ authorization: `Bearer ${token}` });\n };\n}\n","export class UnsupportedDocumentTypeError extends Error {\n constructor(documentType: string) {\n super(`Document type ${documentType} is not supported`);\n this.name = \"UnsupportedDocumentTypeError\";\n }\n\n static isError(error: unknown): error is UnsupportedDocumentTypeError {\n return (\n Error.isError(error) && error.name === \"UnsupportedDocumentTypeError\"\n );\n }\n}\n\nexport class DocumentModelNotFoundError extends Error {\n readonly documentType: string;\n readonly name = \"DocumentModelNotFoundError\";\n\n constructor(documentType: string) {\n super(`Document model module for type ${documentType} not found`);\n this.documentType = documentType;\n }\n\n static isError(error: unknown): error is DocumentModelNotFoundError {\n return Error.isError(error) && error.name === \"DocumentModelNotFoundError\";\n }\n}\n\nexport class DocumentTypeMismatchError extends Error {\n constructor(documentId: string, expectedType: string, actualType: string) {\n super(\n `Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`,\n );\n }\n}\n\nexport class NoSelectedDocumentError extends Error {\n constructor() {\n super(\n \"There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?\",\n );\n }\n}\n","import type { Remote } from \"@powerhousedao/reactor\";\nimport type { PHStore } from \"../hooks/ph-store.js\";\n\n/** The store's sync remotes; none before the reactor is ready. */\nexport function listSyncRemotes(store: PHStore | undefined): Remote[] {\n try {\n return (\n store?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list() ??\n []\n );\n } catch {\n return [];\n }\n}\n\n// Only a first pull in flight may still bring drives. A connected remote that\n// never polled is paused or answer-only; one failed or failing to reconnect won't soon.\nfunction isFirstPullInFlight(remote: Remote) {\n try {\n const { state, receivingPages, lastSuccessUtcMs, failureCount } =\n remote.channel.getConnectionState();\n if (state === \"connected\") return receivingPages;\n if (state === \"reconnecting\") return !lastSuccessUtcMs && !failureCount;\n return state === \"connecting\" && (receivingPages || !lastSuccessUtcMs);\n } catch {\n return false;\n }\n}\n\n/** Whether a remote, or one syncing `driveId` when given, is in its first pull. */\nexport function isInitialSyncInFlight(\n store: PHStore | undefined,\n driveId?: string,\n) {\n return listSyncRemotes(store).some(\n (remote) =>\n (driveId === undefined || remote.meta.collectionId.driveId === driveId) &&\n isFirstPullInFlight(remote),\n );\n}\n","import type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { SetPHGlobalValue, UsePHGlobalValue } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst drivesEventFunctions = makePHEventFunctions(\"drives\");\n\n/** Returns all of the drives in the reactor */\nexport const useDrives: UsePHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.useValue;\n\n/** Sets the drives in the reactor */\nexport const setDrives: SetPHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.setValue;\n\n/** Adds an event handler for the drives */\nexport const addDrivesEventHandler = drivesEventFunctions.addEventHandler;\n","import type {\n PHNavigateOptions,\n PHNavigationTarget,\n} from \"@powerhousedao/reactor-browser\";\nimport type { Node } from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n makeDriveSlug,\n makeNodeSlug,\n} from \"../utils/url.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport { useCallback } from \"react\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n openTargetWith,\n preloadTarget,\n} from \"./navigation.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport {\n getPHStore,\n isScopedPHStore,\n usePHStore,\n warnGlobalSetterInScope,\n} from \"./ph-store.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nexport const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;\n/** Sets the selected node id without touching the URL. */\nexport const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\n/** @deprecated `ph:setSelectedNodeId` bypasses the URL; use `setSelectedNode`. */\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\n\nfunction decodeSlug(slug: string) {\n try {\n return decodeURIComponent(slug);\n } catch {\n return slug;\n }\n}\n\n// The selected drive's slug, else the path's: a pending navigation's path\n// already names its destination, not the drive still shown.\nfunction openDriveSlug(store: PHStore | undefined, pathname: string) {\n const selected = store?.drives?.find(\n (d) => d.header.id === store.selectedDriveId,\n );\n if (selected) return makeDriveSlug(selected);\n const driveSlug = extractDriveSlugFromPath(pathname);\n return driveSlug ? decodeSlug(driveSlug) : undefined;\n}\n\n// The node in the app's open drive.\nfunction nodeTarget(nodeSlug: string): PHNavigationTarget | undefined {\n const driveSlug = openDriveSlug(getPHStore(), getCurrentPathname());\n if (!driveSlug) return undefined;\n return { driveSlug, nodeSlug: nodeSlug || undefined };\n}\n\ntype NodeRef = Node | string | undefined;\n\nconst toSlug = (node: NodeRef) =>\n typeof node === \"string\" ? node : makeNodeSlug(node);\n\n// The node in a scope's open drive.\nfunction scopedNodeTarget(store: PHStore, nodeSlug: string) {\n const pathname = store.navigation?.location().pathname ?? \"\";\n const driveSlug = openDriveSlug(store, pathname);\n if (!driveSlug) return undefined;\n return { driveSlug, nodeSlug: nodeSlug || undefined };\n}\n\n/** Selects a node in the app's store, without the scope warning. */\nexport function selectNode(node: NodeRef, options?: PHNavigateOptions) {\n const nodeSlug = toSlug(node);\n // A host router resolves the node and writes the selection itself.\n if (!hasHostNavigation()) {\n setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));\n }\n const target = nodeTarget(nodeSlug);\n if (target) openTarget(target, options);\n}\n\n/** Selects a node in `store`: a scope's own selection, else the app's. */\nexport function selectNodeIn(\n store: PHStore | undefined,\n node: NodeRef,\n options?: PHNavigateOptions,\n) {\n if (!store || !isScopedPHStore(store)) {\n selectNode(node, options);\n return;\n }\n const nodeSlug = toSlug(node);\n const navigation = store.navigation;\n if (!navigation) {\n store.selectedNodeId =\n typeof node === \"object\" ? node.id : extractNodeIdFromSlug(nodeSlug);\n return;\n }\n const target = scopedNodeTarget(store, nodeSlug);\n if (target) openTargetWith(navigation, target, options);\n}\n\n/** Sets the selected node (file or folder) of the app's store; `search` sets\n * the params it opens with. Inside a scoped store, use `useSetSelectedNode`. */\nexport function setSelectedNode(node: NodeRef, options?: PHNavigateOptions) {\n warnGlobalSetterInScope(\"setSelectedNode\", \"useSetSelectedNode\");\n selectNode(node, options);\n}\n\n/** `setSelectedNode` for the store in context, e.g. a scoped editor's. */\nexport function useSetSelectedNode() {\n const store = usePHStore();\n return useCallback(\n (node: NodeRef, options?: PHNavigateOptions) =>\n selectNodeIn(store, node, options),\n [store],\n );\n}\n\n/** Opens a node, or with `undefined` its drive, in the store in context. */\nexport const useOpenNode: () => (\n node: Node | undefined,\n options?: PHNavigateOptions,\n) => void = useSetSelectedNode;\n\n/** Where a node of `store`'s open drive navigates to. */\nexport function getNodeTargetIn(store: PHStore | undefined, node: Node) {\n const nodeSlug = makeNodeSlug(node);\n return store && isScopedPHStore(store)\n ? scopedNodeTarget(store, nodeSlug)\n : nodeTarget(nodeSlug);\n}\n\n/** Where a node of the open drive navigates to. */\nexport function getNodeTarget(node: Node | undefined) {\n return nodeTarget(makeNodeSlug(node));\n}\n\nfunction preloadNodeIn(store: PHStore | undefined, node: Node | undefined) {\n if (!node) return;\n if (!store || !isScopedPHStore(store)) {\n const target = nodeTarget(makeNodeSlug(node));\n if (target) preloadTarget(target);\n return;\n }\n const target = scopedNodeTarget(store, makeNodeSlug(node));\n if (target) store.navigation?.preload?.(target);\n}\n\n/** Warms a node's view before it is opened, e.g. on hover. */\nexport function preloadNode(node: Node | undefined) {\n warnGlobalSetterInScope(\"preloadNode\", \"usePreloadNode\");\n preloadNodeIn(undefined, node);\n}\n\n/** `preloadNode` for the store in context. */\nexport function usePreloadNode() {\n const store = usePHStore();\n return useCallback(\n (node: Node | undefined) => preloadNodeIn(store, node),\n [store],\n );\n}\n\nexport function addResetSelectedNodeEventHandler() {\n subscribeToPHValue(\"selectedDriveId\", () => {\n setSelectedNodeId(undefined);\n });\n}\n","import type { PHStore } from \"./ph-store.js\";\nimport {\n getPHStore,\n isScopedPHStore,\n usePHStore,\n warnGlobalSetterInScope,\n} from \"./ph-store.js\";\nimport { useCallback } from \"react\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeSlugFromPath,\n findDriveBySlug,\n makeDriveSlug,\n} from \"../utils/url.js\";\nimport { isInitialSyncInFlight } from \"../routing/initial-sync.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDrives } from \"./drives.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n openTargetWith,\n preloadTarget,\n} from \"./navigation.js\";\nimport { selectNode } from \"./set-selected-node.js\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\n\n/** Returns the selected drive id */\nexport const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Sets the selected drive id */\nexport const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n\n/** Adds an event handler for the selected drive id\n * @deprecated `ph:setSelectedDriveId` bypasses the URL; use `setSelectedDrive`. */\nexport const addSelectedDriveIdEventHandler =\n selectedDriveIdEventFunctions.addEventHandler;\n\n/** Returns the selected drive */\nexport function useSelectedDrive() {\n const drive = useSelectedDriveSafe();\n if (!drive[0]) {\n throw new Error(\n \"There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?\",\n );\n }\n\n return drive;\n}\n\n/** Returns the selected drive, or undefined if no drive is selected */\nexport function useSelectedDriveSafe() {\n const selectedDriveId = useSelectedDriveId();\n const drives = useDrives();\n const selectedDrive = drives?.find(\n (drive) => drive.header.id === selectedDriveId,\n );\n\n const [drive, dispatch] = useDispatch(selectedDrive);\n if (!selectedDrive) {\n return [undefined, undefined] as const;\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n\ntype DriveRef = string | DocumentDriveDocument | undefined;\n\n/** Selects a drive in the app's store; inside a scoped store, use\n * `useSetSelectedDrive`. */\nexport function setSelectedDrive(driveOrDriveSlug: DriveRef) {\n warnGlobalSetterInScope(\"setSelectedDrive\", \"useSetSelectedDrive\");\n selectDrive(driveOrDriveSlug);\n}\n\n/** Selects a drive in `store`: a scope's own selection, else the app's. */\nexport function selectDriveIn(\n store: PHStore | undefined,\n driveOrDriveSlug: DriveRef,\n) {\n if (!store || !isScopedPHStore(store)) {\n selectDrive(driveOrDriveSlug);\n return;\n }\n const driveSlug =\n typeof driveOrDriveSlug === \"string\"\n ? driveOrDriveSlug\n : driveOrDriveSlug && makeDriveSlug(driveOrDriveSlug);\n if (store.navigation) {\n openTargetWith(store.navigation, driveSlug ? { driveSlug } : undefined);\n return;\n }\n const drive =\n typeof driveOrDriveSlug === \"object\"\n ? driveOrDriveSlug\n : findDriveBySlug(store.drives, driveSlug);\n store.selectedDriveId = drive?.header.id;\n store.selectedNodeId = undefined;\n}\n\n/** `setSelectedDrive` for the store in context, e.g. a scoped editor's. */\nexport function useSetSelectedDrive() {\n const store = usePHStore();\n return useCallback((drive: DriveRef) => selectDriveIn(store, drive), [store]);\n}\n\n/** Selects a drive in the app's store, without the scope warning. */\nexport function selectDrive(driveOrDriveSlug: DriveRef) {\n const driveSlug =\n typeof driveOrDriveSlug === \"string\"\n ? driveOrDriveSlug\n : driveOrDriveSlug && makeDriveSlug(driveOrDriveSlug);\n\n // A host router resolves the drive and writes the selection itself.\n if (hasHostNavigation()) {\n cancelPendingDriveSelection();\n openTarget(driveSlug ? { driveSlug } : undefined);\n return;\n }\n\n // A full drive document is selected directly — a just-created drive\n // navigates before the collection refresh. Slugs go through the lookup.\n const drives = getPHStore()?.drives;\n const drive =\n typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null\n ? driveOrDriveSlug\n : findDriveBySlug(drives, driveSlug);\n const driveId = drive?.header.id;\n\n // Deprecated: hosts without a navigation only; route loaders wait for drives.\n // A deep link may predate remote drive registration, so defer the lookup.\n if (\n !driveId &&\n driveSlug &&\n extractDriveSlugFromPath(getCurrentPathname()) === driveSlug\n ) {\n // Clear the previous selection so a stale drive doesn't render against\n // the new URL; the selected node resets with it, the URL is untouched.\n if (getPHStore()?.selectedDriveId) {\n setSelectedDriveId(undefined);\n }\n deferDriveSelection(driveSlug);\n return;\n }\n\n // Any resolved selection supersedes a pending deferred lookup.\n cancelPendingDriveSelection();\n\n setSelectedDriveId(driveId);\n openTarget(driveId && driveSlug ? { driveSlug } : undefined);\n}\n\n/** Warms a drive's view before it is opened, e.g. on hover. */\nexport function preloadDrive(drive: DocumentDriveDocument | undefined) {\n warnGlobalSetterInScope(\"preloadDrive\", \"usePreloadDrive\");\n if (drive) preloadTarget({ driveSlug: makeDriveSlug(drive) });\n}\n\n/** `preloadDrive` for the store in context. */\nexport function usePreloadDrive() {\n const store = usePHStore();\n return useCallback(\n (drive: DocumentDriveDocument | undefined) => {\n if (!drive) return;\n if (!isScopedPHStore(store)) {\n preloadTarget({ driveSlug: makeDriveSlug(drive) });\n return;\n }\n store?.navigation?.preload?.({ driveSlug: makeDriveSlug(drive) });\n },\n [store],\n );\n}\n\n// Tick between unresolved-slug checks; re-armed while a sync is in flight.\nconst DEFERRED_DRIVE_TICK_MS = 2_000;\n// Hard cap so a wedged remote can't pin the deep link forever.\nconst DEFERRED_DRIVE_MAX_WAIT_MS = 15_000;\n\nlet unsubscribePending: (() => void) | undefined;\nlet pendingTimeout: ReturnType<typeof setTimeout> | undefined;\n\nfunction cancelPendingDriveSelection() {\n if (unsubscribePending) {\n unsubscribePending();\n unsubscribePending = undefined;\n }\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n pendingTimeout = undefined;\n }\n}\n\n// Deprecated with the no-navigation path: re-runs the slug lookup on drives\n// updates, restores the pinned node, and redirects home once syncs settle.\nfunction deferDriveSelection(driveSlug: string) {\n cancelPendingDriveSelection();\n\n // Capture the node pinned in the deep link before setSelectedDrive\n // rewrites the URL to /d/<driveSlug>, dropping the node segment.\n const nodeSlug = extractNodeSlugFromPath(getCurrentPathname());\n const handler = () => {\n const drive = findDriveBySlug(getPHStore()?.drives, driveSlug);\n if (!drive) {\n return;\n }\n cancelPendingDriveSelection();\n selectDrive(driveSlug);\n selectNode(nodeSlug);\n };\n unsubscribePending = subscribeToPHValue(\"drives\", handler);\n\n const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n const scheduleTick = () => {\n pendingTimeout = setTimeout(() => {\n if (Date.now() < deadline && isInitialSyncInFlight(getPHStore())) {\n scheduleTick();\n return;\n }\n cancelPendingDriveSelection();\n openTarget(undefined);\n }, DEFERRED_DRIVE_TICK_MS);\n };\n scheduleTick();\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport type { DocumentModelLib } from \"document-model\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n isDuplicateManifestError,\n isDuplicateModuleError,\n} from \"../reactor-interop.js\";\nimport type { IPackageManager } from \"../types/vetra.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst vetraPackageManagerFunctions = makePHEventFunctions(\n \"vetraPackageManager\",\n);\n\nexport const useVetraPackageManager = vetraPackageManagerFunctions.useValue;\n\nconst EMPTY_VETRA_PACKAGES: DocumentModelLib[] = [];\nconst noPackageManagerUnsubscribe = () => {};\n\n/**\n * Returns all of the Vetra packages loaded by the Connect instance.\n *\n * The snapshot and subscription must keep stable identity while no package\n * manager is registered: `useSyncExternalStore` loops when the snapshot\n * changes on every read, which a fresh `[]` does.\n */\nexport const useVetraPackages = () => {\n const packageManager = useVetraPackageManager();\n const getPackages = () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES;\n\n return useSyncExternalStore(\n (cb) =>\n packageManager\n ? packageManager.subscribe(cb)\n : noPackageManagerUnsubscribe,\n getPackages,\n getPackages,\n );\n};\n\n/** Adds the Vetra package manager event handler */\nexport const addVetraPackageManagerEventHandler =\n vetraPackageManagerFunctions.addEventHandler;\n\n/**\n * Non-react access to the Vetra package manager: calls `callback` once a\n * manager is available - immediately when already set, otherwise when\n * `setVetraPackageManager` publishes one. Returns an unsubscribe. The worker\n * wiring uses this to forward package updates from plain boot code.\n */\nexport function onVetraPackageManager(\n callback: (packageManager: IPackageManager) => void,\n): () => void {\n let delivered: IPackageManager | undefined;\n const deliver = () => {\n const packageManager = vetraPackageManagerFunctions.getSnapshot();\n if (!packageManager || packageManager === delivered) return;\n delivered = packageManager;\n callback(packageManager);\n };\n const unsubscribe = vetraPackageManagerFunctions.subscribeToValue(deliver);\n deliver();\n return unsubscribe;\n}\n\n/** Sets the Vetra package manager and registers its packages */\nexport function setVetraPackageManager(packageManager: IPackageManager) {\n vetraPackageManagerFunctions.setValue(packageManager);\n updateReactorClientDocumentModels(packageManager.packages);\n updateReactorClientUpgradeManifests(packageManager.packages);\n packageManager.subscribe(({ packages }) => {\n updateReactorClientDocumentModels(packages);\n updateReactorClientUpgradeManifests(packages);\n });\n}\n\nfunction updateReactorClientDocumentModels(packages: DocumentModelLib[]) {\n const documentModelModules = packages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // dedupe by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n (m.version ?? 1) === (module.version ?? 1),\n ) === index,\n );\n\n const registry =\n getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || documentModelModules.length === 0) return;\n\n const results = registry.registerModules(...documentModelModules);\n const duplicateTypes = new Set<string>();\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateModuleError(result.error)) {\n duplicateTypes.add(result.item.documentModel.global.id);\n } else {\n console.error(\n \"Failed to register document model module:\",\n result.error,\n );\n }\n }\n }\n if (duplicateTypes.size > 0) {\n // unregisterModules is type-scoped, so replace the whole version family\n // with the incoming package's modules: re-registering only the duplicated\n // items would purge any new version that registered successfully above.\n registry.unregisterModules(...duplicateTypes);\n registry.registerModules(\n ...documentModelModules.filter((module) =>\n duplicateTypes.has(module.documentModel.global.id),\n ),\n );\n }\n}\n\nfunction updateReactorClientUpgradeManifests(packages: DocumentModelLib[]) {\n const upgradeManifests = packages\n .flatMap((pkg) => pkg.upgradeManifests)\n .filter((u) => u !== undefined);\n\n const registry =\n getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || upgradeManifests.length === 0) return;\n\n const results = registry.registerUpgradeManifests(...upgradeManifests);\n const duplicates = [];\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateManifestError(result.error)) {\n duplicates.push(result);\n } else {\n console.error(\"Failed to register upgrade manifest:\", result.error);\n }\n }\n }\n if (duplicates.length > 0) {\n const duplicateTypes = duplicates\n .map((r) => r.item.documentType)\n .filter((t): t is string => !!t);\n registry.unregisterUpgradeManifests(...duplicateTypes);\n registry.registerUpgradeManifests(...duplicates.map((r) => r.item));\n }\n}\n","import type { DocumentModelModule } from \"document-model\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useDocumentModelModules(): DocumentModelModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // deduplicate by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n m.version === module.version,\n ) === index,\n );\n}\n\n/**\n * Resolves a document model module by document type, mirroring the registry's\n * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the\n * LATEST version of the type wins (`version ?? 1` as each module's default),\n * with `version` given only an exact match is returned. The reactor resolves\n * modules the same way when a document is created, so metadata read through\n * this hook and the version a creation actually uses cannot disagree.\n */\nexport function useDocumentModelModuleById(\n id: string | null | undefined,\n version?: number,\n): DocumentModelModule | undefined {\n const documentModelModules = useDocumentModelModules();\n if (!id || !documentModelModules) return undefined;\n\n let latestModule: DocumentModelModule | undefined;\n let latestVersion = -1;\n for (const module of documentModelModules) {\n if (module.documentModel.global.id !== id) continue;\n const moduleVersion = module.version ?? 1;\n if (version !== undefined) {\n if (moduleVersion === version) return module;\n continue;\n }\n if (moduleVersion > latestVersion) {\n latestVersion = moduleVersion;\n latestModule = module;\n }\n }\n return latestModule;\n}\n"],"mappings":";;;;;;AAYA,MAAM,+BAA+B;;;;;;;;;;;AAYrC,eAAsB,6BAEpB;CACA,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,SAAS,WAAW,CAAC,EAAE;CAC7B,IAAI,CAAC,QAAQ,MACX;CAGF,OAAO,OAAO,eAAe,EAAE,WAAW,6BAA6B,CAAC;AAC1E;;;;;;;;AASA,SAAgB,mBACd,eACoB;CACpB,OAAO,OAAO,WAAW;EACvB,MAAM,QAAQ,MAAM,cAAc;EAClC,IAAI,CAAC,OACH,OAAO,OAAO;EAGhB,OAAO,OAAO,EAAE,eAAe,UAAU,QAAQ,CAAC;CACpD;AACF;;;ACzDA,IAAa,+BAAb,cAAkD,MAAM;CACtD,YAAY,cAAsB;EAChC,MAAM,iBAAiB,aAAa,kBAAkB;EACtD,KAAK,OAAO;CACd;CAEA,OAAO,QAAQ,OAAuD;EACpE,OACE,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS;CAE3C;AACF;AAEA,IAAa,6BAAb,cAAgD,MAAM;CACpD;CACA,OAAgB;CAEhB,YAAY,cAAsB;EAChC,MAAM,kCAA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ChJA,SAAgB,0BAA6D;CAE3E,OADsB,iBACH,CAAC,CACjB,SAAS,QAAQ,IAAI,cAAc,CAAC,CACpC,QACE,QAAQ,OAAO,YAEd,QAAQ,WACL,MACC,EAAE,cAAc,OAAO,OAAO,OAAO,cAAc,OAAO,MAC1D,EAAE,YAAY,OAAO,OACzB,MAAM,KACV;AACJ;;;;;;;;;AAUA,SAAgB,2BACd,IACA,SACiC;CACjC,MAAM,uBAAuB,wBAAwB;CACrD,IAAI,CAAC,MAAM,CAAC,sBAAsB,OAAO,KAAA;CAEzC,IAAI;CACJ,IAAI,gBAAgB;CACpB,KAAK,MAAM,UAAU,sBAAsB;EACzC,IAAI,OAAO,cAAc,OAAO,OAAO,IAAI;EAC3C,MAAM,gBAAgB,OAAO,WAAW;EACxC,IAAI,YAAY,KAAA,GAAW;GACzB,IAAI,kBAAkB,SAAS,OAAO;GACtC;EACF;EACA,IAAI,gBAAgB,eAAe;GACjC,gBAAgB;GAChB,eAAe;EACjB;CACF;CACA,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"global-Cgi-GJpN.d.ts","names":[],"sources":["../src/types/documents.ts","../src/types/reactor-browser-client.ts","../src/types/config.ts","../src/types/modals.ts","../src/types/package-discovery.ts","../src/types/timeline.ts","../src/types/toast.ts","../src/types/vetra.ts","../src/hooks/node-drag-and-drop.ts","../src/types/global.ts"],"mappings":";;;;;;;;;;;;;KAOY,iBAAiB,gBAAgB,WAC3C,iBACI,UACA,YACA,iBACA,8BAEJ,YAAY,QAAQ,kBACpB,aAAa,QAAQ;KAGX,iBAAiB,KAAK,QAAQ,KAAK,aAAa;KAEhD,iBAAiB,KAAK,QAAQ;EACxC;EACA,OAAO;;KAGG,gBAAgB,KAAK,QAAQ;EACvC;EACA;;KAGU,aAAa;EAEnB;;EAEA;EAAqB,OAAO;;EAC5B;EAAoB;;;KAGd;EACV;EACA;;UAGe;EACf,IAAI,YAAY,oBAAoB,QAAQ;EAC5C,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AmB,SAAS,0BAA0B;;KAG5C;;KAGA;EAAkB;EAAmB;;;KAGrC;EAAqB;;;KAGrB,qBAAqB,gBAAgB;;KAGrC,iBAAiB;KAEjB;EACV;;EAEA,SAAS;;;KAIC,qBACR,mBACE,MAAM,2BAA2B;KAE3B,mBACV,QAAQ,oBACR;EAAY;;;;KAKF;EACV;IAAc;IAAkB;;EAChC,KACE,QAAQ,gCACR,UAAU;;EAGZ,SAAS,QAAQ;;EAEjB,cAAc,QAAQ;;EAEtB,SAAS,QAAQ;;EAEjB,UACE,SAAS,MAAM,2BAA2B,gBAC1C;IAAY;;;EAGd,mBAAmB;;EAEnB,sBAAsB;;;EAGtB;;KAGU,WAAW;EACrB,aAAa;EACb;EACA,sBAAsB,6BAA6B;EACnD,gBAAgB;;EAEhB,oBAAoB;EACpB,oBAAoB;EACpB,uBAAuB;EACvB,SAAS,UAAU;EACnB,sBAAsB;EACtB,SAAS;EACT,gBAAgB;EAChB;EACA;EACA,eAAe;EACf,QAAQ;EACR;EACA,uBAAuB;EACvB,0BAA0B;EAC1B,WAAW;EACX,QAAQ;;KAGE,oBAAoB;KACpB,gBAAgB,SAAS;KAEzB,iBAAiB,eAAe,uBACxC;KAGQ,iBAAiB,eAAe,kBAC1C,OAAO;KAGG;KAEA,6BAA6B,OACvC,aACA;KAGU,SAAS,aAAa,eAAe,eAC9C,OAAO,OAAO,SAAS;QAGlB;YACI;IACR,KAAK;;YAEG,uBAAuB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"make-ph-event-functions-C1JTfEw1.js","names":[],"sources":["../src/hooks/ph-store.tsx","../src/hooks/make-ph-event-functions.ts"],"sourcesContent":["import type { PHGlobal, PHGlobalKey } from \"@powerhousedao/reactor-browser\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext, useEffect } from \"react\";\n\n/** PH state of one app (or one server request); assigning a key notifies. */\nexport type PHStore = PHGlobal;\n\ntype Listeners = Map<PropertyKey, Set<() => void>>;\n\n// Listeners per key; ALL_KEYS hears every change.\nconst ALL_KEYS = Symbol(\"all keys\");\nconst listenersByStore = new WeakMap<PHStore, Listeners>();\n// Stores bound to window.ph; their changes also fire `ph:<key>Updated`.\nconst windowBound = new WeakSet<Listeners>();\nconst subscribeCache = new WeakMap<\n PHStore,\n Map<PropertyKey, (listener: () => void) => () => void>\n>();\n\nfunction notifyKey(listeners: Listeners, key: PropertyKey) {\n for (const set of [listeners.get(key), listeners.get(ALL_KEYS)]) {\n for (const listener of set ?? []) listener();\n }\n // Another bundled copy of reactor-browser subscribes through window events.\n if (windowBound.has(listeners) && typeof key === \"string\") {\n window.dispatchEvent(new CustomEvent(`ph:${key}Updated`));\n }\n}\n\nexport function createPHStore(initial: PHGlobal = {}): PHStore {\n const listeners: Listeners = new Map();\n const store = new Proxy<PHGlobal>(\n { ...initial },\n {\n set: (target, key, value) => {\n if (Reflect.get(target, key) === value) return true;\n Reflect.set(target, key, value);\n notifyKey(listeners, key);\n return true;\n },\n deleteProperty: (target, key) => {\n Reflect.deleteProperty(target, key);\n notifyKey(listeners, key);\n return true;\n },\n },\n );\n listenersByStore.set(store, listeners);\n return store;\n}\n\n/** The keys a scoped store owns; every other key reads and writes its parent. */\nexport const SCOPED_PH_KEYS = [\n \"selectedDriveId\",\n \"selectedNodeId\",\n \"navigation\",\n] as const satisfies readonly PHGlobalKey[];\n\nexport type ScopedPHKey = (typeof SCOPED_PH_KEYS)[number];\nexport type ScopedPHStoreOverrides = Pick<PHGlobal, ScopedPHKey>;\n\nconst scopedKeys = new Set<PropertyKey>(SCOPED_PH_KEYS);\nconst parentOfScope = new WeakMap<PHStore, PHStore>();\n\n/** A store with its own selection and navigation over `parent`, e.g. for an\n * editor shown beside others; provide it with {@link PHStoreProvider}. */\nexport function createScopedPHStore(\n parent: PHStore,\n overrides: ScopedPHStoreOverrides = {},\n): PHStore {\n const listeners: Listeners = new Map();\n const own: PHGlobal = {};\n for (const key of SCOPED_PH_KEYS) {\n if (overrides[key] !== undefined) Reflect.set(own, key, overrides[key]);\n }\n const store = new Proxy<PHGlobal>(own, {\n get: (target, key): unknown =>\n scopedKeys.has(key) ? Reflect.get(target, key) : Reflect.get(parent, key),\n has: (target, key) =>\n scopedKeys.has(key) ? Reflect.has(target, key) : Reflect.has(parent, key),\n set: (target, key, value) => {\n if (!scopedKeys.has(key)) return Reflect.set(parent, key, value);\n if (Reflect.get(target, key) === value) return true;\n Reflect.set(target, key, value);\n notifyKey(listeners, key);\n return true;\n },\n deleteProperty: (target, key) => {\n if (!scopedKeys.has(key)) return Reflect.deleteProperty(parent, key);\n Reflect.deleteProperty(target, key);\n notifyKey(listeners, key);\n return true;\n },\n });\n listenersByStore.set(store, listeners);\n parentOfScope.set(store, parent);\n return store;\n}\n\n/** Whether `store` was made by {@link createScopedPHStore}. */\nexport function isScopedPHStore(store: PHStore | undefined) {\n return !!store && parentOfScope.has(store);\n}\n\nfunction listenersOf(store: PHStore) {\n const listeners = listenersByStore.get(store);\n if (!listeners) throw new Error(\"Not a store made by createPHStore\");\n return listeners;\n}\n\n/** Subscribes to changes of `key`, or of every key when omitted. */\nexport function subscribePHStore(\n store: PHStore,\n listener: () => void,\n key: PHGlobalKey | typeof ALL_KEYS = ALL_KEYS,\n): () => void {\n const parent = parentOfScope.get(store);\n // A scope hears its parent for the keys it reads through.\n if (parent && !scopedKeys.has(key)) {\n const fromParent = subscribePHStore(parent, listener, key);\n if (key !== ALL_KEYS) return fromParent;\n const fromScope = subscribeOwn(store, listener, key);\n return () => {\n fromParent();\n fromScope();\n };\n }\n return subscribeOwn(store, listener, key);\n}\n\nfunction subscribeOwn(store: PHStore, listener: () => void, key: PropertyKey) {\n const listeners = listenersOf(store);\n const set = listeners.get(key) ?? new Set();\n listeners.set(key, set);\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n}\n\n/** Notifies `key`'s listeners without a change, as re-setting a value does. */\nexport function notifyPHStore(store: PHStore, key: PHGlobalKey) {\n const parent = parentOfScope.get(store);\n if (parent && !scopedKeys.has(key)) notifyPHStore(parent, key);\n else notifyKey(listenersOf(store), key);\n}\n\n/** A subscribe for `key`, stable per store as useSyncExternalStore expects. */\nexport function getPHStoreSubscribe(store: PHStore, key?: PHGlobalKey) {\n const cacheKey = key ?? ALL_KEYS;\n const cache =\n subscribeCache.get(store) ??\n new Map<PropertyKey, (listener: () => void) => () => void>();\n subscribeCache.set(store, cache);\n let subscribe = cache.get(cacheKey);\n if (!subscribe) {\n subscribe = (listener: () => void) =>\n subscribePHStore(store, listener, cacheKey);\n cache.set(cacheKey, subscribe);\n }\n return subscribe;\n}\n\nlet activeStore: PHStore | undefined;\n\n/** The store bound with {@link bindPHStoreToWindow}, if any. */\nexport function getActivePHStore() {\n return activeStore;\n}\n\n/** The app's state outside React: the bound store, else `window.ph`. */\nexport function getPHStore(): PHStore | undefined {\n if (activeStore) return activeStore;\n return typeof window === \"undefined\" ? undefined : window.ph;\n}\n\n/** The bound store; otherwise binds `window.ph` if it is a store, else a new\n * store that takes over a plain `window.ph`'s values. */\nexport function ensurePHStore(): PHStore {\n if (activeStore) return activeStore;\n const current = typeof window === \"undefined\" ? undefined : window.ph;\n const store =\n current && listenersByStore.has(current) ? current : createPHStore();\n bindPHStoreToWindow(store);\n return store;\n}\n\n/** Makes `store` the app's state and `window.ph`; values set on a plain\n * `window.ph` carry over where `store` has none. */\nexport function bindPHStoreToWindow(store: PHStore) {\n activeStore = store;\n if (typeof window === \"undefined\") return;\n const previous = window.ph;\n const previousListeners = previous && listenersByStore.get(previous);\n // A previously bound store is replaced, not merged.\n if (previousListeners) windowBound.delete(previousListeners);\n else if (previous) {\n for (const [key, value] of Object.entries(previous)) {\n if (!(key in store)) Reflect.set(store, key, value);\n }\n }\n windowBound.add(listenersOf(store));\n window.ph = store;\n}\n\nconst PHStoreContext = createContext<PHStore | undefined>(undefined);\n\n// Scoped stores provided right now; plain setters warn while any is.\nlet mountedScopes = 0;\nconst warned = new Set<string>();\n\nfunction isProduction() {\n // `process` need not exist in a browser bundle.\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\"\n );\n}\n\n/** Warns once in development when a global setter runs while a scoped store\n * is mounted, since it acts on the app's store and not the scope's. */\nexport function warnGlobalSetterInScope(setter: string, hook: string) {\n if (mountedScopes === 0 || warned.has(setter) || isProduction()) return;\n warned.add(setter);\n console.warn(\n `${setter} acts on the app's PH store while a scoped store is mounted; inside a scope, use ${hook}.`,\n );\n}\n\n/** Hooks below read from `store`; without a provider they read `window.ph`. */\nexport function PHStoreProvider(props: {\n store: PHStore;\n children: ReactNode;\n}) {\n const scoped = isScopedPHStore(props.store);\n useEffect(() => {\n if (!scoped) return;\n mountedScopes++;\n return () => {\n mountedScopes--;\n };\n }, [scoped]);\n return (\n <PHStoreContext.Provider value={props.store}>\n {props.children}\n </PHStoreContext.Provider>\n );\n}\n\nexport function usePHStore() {\n return useContext(PHStoreContext);\n}\n","import type {\n PHGlobal,\n PHGlobalKey,\n SetEvent,\n} from \"@powerhousedao/reactor-browser\";\nimport { capitalCase } from \"change-case\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n getActivePHStore,\n getPHStore,\n getPHStoreSubscribe,\n notifyPHStore,\n subscribePHStore,\n usePHStore,\n} from \"./ph-store.js\";\n\n// guard condition for server side rendering\nconst isServer = typeof window === \"undefined\";\n\nconst updatedEventName = (key: PHGlobalKey) => `ph:${key}Updated`;\n\n/** Calls `onChange` whenever `key` is set: through the bound store, or the\n * `ph:<key>Updated` event on pages that bound none. */\nexport function subscribeToPHValue(key: PHGlobalKey, onChange: () => void) {\n if (isServer) return () => {};\n const store = getActivePHStore();\n if (store) return subscribePHStore(store, onChange, key);\n const eventName = updatedEventName(key);\n window.addEventListener(eventName, onChange);\n return () => window.removeEventListener(eventName, onChange);\n}\n\nexport function makePHEventFunctions<TKey extends PHGlobalKey>(key: TKey) {\n const setEventName = `ph:set${capitalCase(key)}` as const;\n const updateEventName = updatedEventName(key);\n\n function setValue(value: PHGlobal[TKey] | undefined) {\n if (isServer) {\n return;\n }\n const store = getActivePHStore();\n if (store) {\n const unchanged = store[key] === value;\n store[key] = value;\n // Re-setting a value still notifies, as the event path always has.\n if (unchanged) notifyPHStore(store, key);\n return;\n }\n const event = new CustomEvent(setEventName, {\n detail: { [key]: value },\n });\n window.dispatchEvent(event);\n }\n\n function dispatchUpdatedEvent() {\n if (isServer) {\n return;\n }\n const event = new CustomEvent(updateEventName);\n window.dispatchEvent(event);\n }\n\n function handleSetValueEvent(event: SetEvent<TKey>) {\n if (isServer) {\n return;\n }\n if (getActivePHStore()) {\n setValue(event.detail[key]);\n return;\n }\n // No bound store: the page keeps a plain `window.ph`.\n (window.ph ??= {})[key] = event.detail[key];\n dispatchUpdatedEvent();\n }\n\n // Only pages without a bound store need it; `ph:set*` events still apply.\n function addEventHandler() {\n if (isServer) {\n return;\n }\n window.addEventListener(setEventName, handleSetValueEvent as EventListener);\n }\n\n function subscribeToValue(onStoreChange: () => void) {\n return subscribeToPHValue(key, onStoreChange);\n }\n\n function getSnapshot() {\n if (isServer) {\n return undefined;\n }\n // Read before the first setValue is expected: subscribers mount before init.\n return getPHStore()?.[key];\n }\n\n function getServerSnapshot() {\n return undefined;\n }\n\n function useValue() {\n const store = usePHStore();\n const readStore = () => store?.[key];\n return useSyncExternalStore(\n store ? getPHStoreSubscribe(store, key) : subscribeToValue,\n store ? readStore : getSnapshot,\n store ? readStore : getServerSnapshot,\n );\n }\n\n return {\n useValue,\n setValue,\n addEventHandler,\n // Non-React access, e.g. Connect's boot wiring of the reactor worker.\n subscribeToValue,\n getSnapshot,\n };\n}\n"],"mappings":";;;;AAUA,MAAM,WAAW,OAAO,UAAU;AAClC,MAAM,mCAAmB,IAAI,QAA4B;AAEzD,MAAM,8BAAc,IAAI,QAAmB;AAC3C,MAAM,iCAAiB,IAAI,QAGzB;AAEF,SAAS,UAAU,WAAsB,KAAkB;CACzD,KAAK,MAAM,OAAO,CAAC,UAAU,IAAI,GAAG,GAAG,UAAU,IAAI,QAAQ,CAAC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OAAO;GAEb,IAAI,WAAW,cAAc,OAAO,GAAG;GACvC;EACF;EACA,MAAM,QAAQ,IAAI,YAAY,cAAc,EAC1C,QAAQ,GAAG,MAAM,MAAM,EACzB,CAAC;EACD,OAAO,cAAc,KAAK;CAC5B;CAEA,SAAS,uBAAuB;EAC9B,IAAI,UACF;EAEF,MAAM,QAAQ,IAAI,YAAY,eAAe;EAC7C,OAAO,cAAc,KAAK;CAC5B;CAEA,SAAS,oBAAoB,OAAuB;EAClD,IAAI,UACF;EAEF,IAAI,iBAAiB,GAAG;GACtB,SAAS,MAAM,OAAO,IAAI;GAC1B;EACF;EAEA,CAAC,OAAO,OAAO,CAAC,EAAA,CAAG,OAAO,MAAM,OAAO;EACvC,qBAAqB;CACvB;CAGA,SAAS,kBAAkB;EACzB,IAAI,UACF;EAEF,OAAO,iBAAiB,cAAc,mBAAoC;CAC5E;CAEA,SAAS,iBAAiB,eAA2B;EACnD,OAAO,mBAAmB,KAAK,aAAa;CAC9C;CAEA,SAAS,cAAc;EACrB,IAAI,UACF;EAGF,OAAO,WAAW,CAAC,GAAG;CACxB;CAEA,SAAS,oBAAoB,CAE7B;CAEA,SAAS,WAAW;EAClB,MAAM,QAAQ,WAAW;EACzB,MAAM,kBAAkB,QAAQ;EAChC,OAAO,qBACL,QAAQ,oBAAoB,OAAO,GAAG,IAAI,kBAC1C,QAAQ,YAAY,aACpB,QAAQ,YAAY,iBACtB;CACF;CAEA,OAAO;EACL;EACA;EACA;EAEA;EACA;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"navigation-BUPIObES.js","names":[],"sources":["../src/utils/url.ts","../src/hooks/navigation.ts"],"sourcesContent":["import { getPHStore } from \"../hooks/ph-store.js\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport { isDerivedDocumentId } from \"@powerhousedao/shared/document-model\";\nimport slug from \"slug\";\n\n// Length of the base64url id a v2-required document gets.\nconst DERIVED_ID_LENGTH = 43;\n\n// Returns url with base path plus provided path\nexport function resolveUrlPathname(path: string) {\n return new URL(\n path.replace(/^\\/+/, \"\"),\n window.location.origin + (getPHStore()?.basePath ?? \"/\"),\n ).pathname;\n}\n\n/** Returns the path without a leading base path */\nexport function getPathWithoutBase(path: string) {\n const basePath = getPHStore()?.basePath ?? \"/\";\n if (!path.startsWith(basePath)) return path;\n const rest = path.slice(basePath.length);\n if (basePath.endsWith(\"/\")) return `/${rest}`;\n return rest === \"\" || rest.startsWith(\"/\") ? rest : path;\n}\n\n/** Makes a URL component for a drive.\n * @deprecated Open drives through the store's `navigation`; it builds the path. */\nexport function makeDriveUrlComponent(\n drive: DocumentDriveDocument | undefined,\n) {\n if (!drive) return \"\";\n return `/d/${slug(drive.header.slug)}`;\n}\n\n/** A drive's URL component: its slug, else its id, prefixed with the slugged\n * name as `<name>-<id>` when the id is opaque (a UUID or derived id). */\nexport function makeDriveSlug(drive: DocumentDriveDocument) {\n const { id, slug: driveSlug } = drive.header;\n if (driveSlug && driveSlug !== id) return driveSlug;\n return isOpaqueId(id) ? namedDriveSlug(drive) : id;\n}\n\nfunction isOpaqueId(id: string) {\n return findUuid(id) !== undefined || isDerivedDocumentId(id);\n}\n\nfunction namedDriveSlug(drive: DocumentDriveDocument) {\n const name = drive.state.global.name || drive.header.name;\n return namedSlug(drive, name, drive.header.id);\n}\n\nconst namedSlugs = new WeakMap<\n object,\n { name: string; id: string; value: string }\n>();\n\n// `<slugged name>-<id>`, cached per drive or node; inputs are rechecked.\nfunction namedSlug(owner: object, name: string, id: string) {\n const cached = namedSlugs.get(owner);\n if (cached?.name === name && cached.id === id) return cached.value;\n const nameSlug = name ? slug(name) : \"\";\n const value = nameSlug ? `${nameSlug}-${id}` : id;\n namedSlugs.set(owner, { name, id, value });\n return value;\n}\n\n/** The drive a URL slug names: its own slug, its id, or `<name>-<id>`. */\nexport function findDriveBySlug(\n drives: readonly DocumentDriveDocument[] | undefined,\n ref: string | undefined,\n) {\n if (!drives || !ref) return undefined;\n const exact = drives.find(\n (d) => d.header.slug === ref || d.header.id === ref,\n );\n if (exact) return exact;\n const id = extractDriveIdFromSlug(ref);\n if (id !== undefined) {\n const byId = drives.find((d) => d.header.id === id);\n if (byId) return byId;\n }\n // `<name>-<id>` also for a readable id, as older links wrote it.\n return drives.find(\n (d) =>\n (!d.header.slug || d.header.slug === d.header.id) &&\n ref.endsWith(d.header.id) &&\n namedDriveSlug(d) === ref,\n );\n}\n\n/**\n * Makes a URL component for a node: `<slugged name>-<id>`. The id is kept\n * verbatim, since a v2-required id is case-sensitive base64url.\n */\nexport function makeNodeSlug(node: Node | undefined) {\n if (!node) return \"\";\n return namedSlug(node, node.name, node.id);\n}\n\n/** Extracts the node slug from a path.\n *\n * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.\n */\nexport function extractNodeSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/[^/]+\\/([^/]+)$/.exec(currentPath);\n return match?.[1];\n}\n\n/** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */\nexport function findUuid(input: string | undefined) {\n if (!input) return undefined;\n const uuidRegex =\n /\\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/;\n const match = uuidRegex.exec(input);\n return match?.[0];\n}\n\n/** The v2-required document id a slug ends with, if any. */\nexport function findDerivedId(input: string | undefined) {\n if (!input || input.length < DERIVED_ID_LENGTH) return undefined;\n const start = input.length - DERIVED_ID_LENGTH;\n if (start > 0 && input[start - 1] !== \"-\") return undefined;\n const candidate = input.slice(start);\n return isDerivedDocumentId(candidate) ? candidate : undefined;\n}\n\nexport function extractNodeIdFromSlug(nodeSlug: string | undefined) {\n return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);\n}\n\n/** @deprecated Route loaders resolve the node; use `extractNodeIdFromSlug`. */\nexport function extractNodeIdFromPath(path: string) {\n const nodeSlug = extractNodeSlugFromPath(path);\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n return nodeId;\n}\n\n/** Extracts the drive slug from a path.\n * Used for extracting drive ids from drive slugs in the URL.\n * Expects the path to be in the format `/d/<drive-slug>`.\n */\nexport function extractDriveSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/([^/]+)/.exec(currentPath);\n return match?.[1] ?? \"\";\n}\n\nexport function extractDriveIdFromSlug(driveSlug: string | undefined) {\n return findUuid(driveSlug) ?? findDerivedId(driveSlug);\n}\n\n/** @deprecated Route loaders resolve the drive; use `extractDriveIdFromSlug`. */\nexport function extractDriveIdFromPath(path: string) {\n const driveSlug = extractDriveSlugFromPath(path);\n const driveId = extractDriveIdFromSlug(driveSlug);\n return driveId;\n}\n\n/** Creates a URL string with the given pathname, keeping the query string.\n * @deprecated The store's `navigation` keeps global params across navigations. */\nexport function createUrlWithPreservedParams(pathname: string): string {\n const search = window.location.search;\n return search ? `${pathname}${search}` : pathname;\n}\n","import type {\n PHNavigateOptions,\n PHNavigation,\n PHNavigationTarget,\n PHSearchUpdate,\n PHSettingsTarget,\n SearchParamsUpdate,\n} from \"@powerhousedao/reactor-browser\";\nimport { useMemo, useSyncExternalStore } from \"react\";\nimport { resolveUrlPathname } from \"../utils/url.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getPHStore, isScopedPHStore } from \"./ph-store.js\";\n\nconst isServer = typeof window === \"undefined\";\n\n/** Fired on `window` when the fallback navigator rewrites the URL. */\nexport const PH_LOCATION_CHANGE_EVENT = \"ph:locationchange\";\n\n/** Params read at boot or app-wide; they survive every navigation. Others,\n * e.g. a document's own, are dropped when the target changes. */\nexport const GLOBAL_SEARCH_PARAMS = [\n // A remote drive to add on boot.\n \"driveUrl\",\n // The theme override read by the inline theme boot script.\n \"theme\",\n // Embedded mode, which hides Connect's chrome.\n \"embed\",\n // Log level override for the feature-flag provider.\n \"LOG_LEVEL\",\n // The reactor worker runtime flag override.\n \"reactorWorker\",\n] as const;\n\n/** Feature flags are any `FEATURE_*` param, so they are retained by prefix. */\nexport const FEATURE_FLAG_PARAM_PREFIX = \"FEATURE_\";\n\n/** Whether `key` is a param every navigation keeps. */\nexport function isGlobalSearchParam(key: string) {\n return (\n (GLOBAL_SEARCH_PARAMS as readonly string[]).includes(key) ||\n key.startsWith(FEATURE_FLAG_PARAM_PREFIX)\n );\n}\n\nfunction globalSearch(search: string) {\n return Object.fromEntries(\n Object.entries(searchToRecord(search)).filter(([key]) =>\n isGlobalSearchParam(key),\n ),\n );\n}\n\n/** A query string's params; repeated keys keep their last value. */\nexport function searchToRecord(search: string): Record<string, string> {\n return Object.fromEntries(new URLSearchParams(search));\n}\n\n/** `prev` with `update` applied; an `undefined` value removes the key. */\nexport function applySearchUpdate(\n prev: Record<string, string>,\n update: PHSearchUpdate,\n): Record<string, string> {\n const next = { ...prev };\n for (const [key, value] of Object.entries(update)) {\n if (value === undefined) delete next[key];\n else next[key] = value;\n }\n return next;\n}\n\n/** `params` as a query string, with an empty value as a bare key: `history`, not `history=`. */\nexport function searchParamsToString(params: URLSearchParams) {\n return params.toString().replace(/=(?=&|$)/g, \"\");\n}\n\n/** `?a=1&b=2`, or an empty string for no params. */\nexport function recordToSearch(record: Record<string, string>) {\n const search = searchParamsToString(new URLSearchParams(record));\n return search ? `?${search}` : \"\";\n}\n\n/** The settings page's path; its tabs are below it. */\nexport const SETTINGS_PATH = \"/settings\";\n\nexport function isSettingsTarget(\n target: PHNavigationTarget | undefined,\n): target is PHSettingsTarget {\n return !!target && \"settings\" in target;\n}\n\n/** The pathname a target opens at, base path included. */\nexport function targetPathname(target: PHNavigationTarget | undefined) {\n if (!target) return resolveUrlPathname(\"/\");\n if (isSettingsTarget(target)) {\n const { settings } = target;\n return resolveUrlPathname(\n settings === true ? SETTINGS_PATH : `${SETTINGS_PATH}/${settings}`,\n );\n }\n const { driveSlug, nodeSlug } = target;\n return resolveUrlPathname(\n nodeSlug ? `/d/${driveSlug}/${nodeSlug}` : `/d/${driveSlug}`,\n );\n}\n\n/** History state key: the index of the entry a document was opened from. */\nexport const OPENED_FROM_STATE_KEY = \"phOpenedFrom\";\n\n// The fallback numbers its own entries; a router's history has its own index.\ntype BrowserEntryState = { phIndex?: number; phOpenedFrom?: number };\n\nfunction browserEntryState(): BrowserEntryState {\n const state: unknown = window.history.state;\n return state && typeof state === \"object\" ? (state as BrowserEntryState) : {};\n}\n\n/** The index to go back to from `index`, when it lies before it. */\nexport function openedFromIndex(\n state: object | undefined,\n index: number,\n): number | undefined {\n const from = (state as Record<string, unknown> | undefined)?.[\n OPENED_FROM_STATE_KEY\n ];\n return typeof from === \"number\" && from >= 0 && from < index\n ? from\n : undefined;\n}\n\n// `openedFrom` \"keep\" carries the current entry's, as an in-document write does.\nfunction writeBrowserUrl(\n href: string,\n replace: boolean | undefined,\n openedFrom: number | \"keep\" | undefined,\n) {\n const prev = browserEntryState();\n const index = prev.phIndex ?? 0;\n const from = openedFrom === \"keep\" ? prev.phOpenedFrom : openedFrom;\n // Keeps the entry's state, e.g. a router's history key, on a replace.\n if (replace) {\n window.history.replaceState(\n { ...prev, phIndex: index, phOpenedFrom: from },\n \"\",\n href,\n );\n } else {\n window.history.pushState(\n { phIndex: index + 1, phOpenedFrom: from },\n \"\",\n href,\n );\n }\n window.dispatchEvent(new Event(PH_LOCATION_CHANGE_EVENT));\n}\n\nfunction subscribeToLocation(onChange: () => void) {\n window.addEventListener(\"popstate\", onChange);\n window.addEventListener(PH_LOCATION_CHANGE_EVENT, onChange);\n return () => {\n window.removeEventListener(\"popstate\", onChange);\n window.removeEventListener(PH_LOCATION_CHANGE_EVENT, onChange);\n };\n}\n\nconst readSearch = () => window.location.search;\nconst readPathname = () => window.location.pathname;\nconst readServerPathname = () => \"\";\nconst readServerSearch = () => \"\";\n\nfunction setBrowserSearch(\n update: (prev: Record<string, string>) => PHSearchUpdate,\n options?: { replace?: boolean },\n) {\n const prev = searchToRecord(window.location.search);\n const next = recordToSearch(applySearchUpdate({}, update(prev)));\n if (next === recordToSearch(prev)) return;\n // Like a router's search update, this drops the hash.\n writeBrowserUrl(\n `${window.location.pathname}${next}`,\n options?.replace,\n \"keep\",\n );\n}\n\nfunction setBrowserSearchParams(\n update: SearchParamsUpdate,\n options?: { replace?: boolean },\n) {\n setBrowserSearch((prev) => resolveSearchUpdate(prev, update), options);\n}\n\n/** The fallback without a host: `window.location` and `window.history`. Only\n * the global params carry over to another target, as with a router. */\n// Set by sync-selection.ts, which imports this module: importing it here would be a cycle.\nlet syncSelectionAfterOpen = () => {};\n\n/** @internal Selects what the browser fallback opens; sync-selection.ts sets it. */\nexport function setBrowserOpenSync(sync: () => void) {\n syncSelectionAfterOpen = sync;\n}\n\nexport const browserNavigation: PHNavigation = {\n location: () => window.location,\n hrefFor: (target) =>\n `${targetPathname(target)}${recordToSearch(globalSearch(window.location.search))}`,\n useIsCurrent(target) {\n const pathname = useSyncExternalStore(\n subscribeToLocation,\n readPathname,\n readServerPathname,\n );\n return pathname === targetPathname(target);\n },\n open: (target, options) => {\n const prev = globalSearch(window.location.search);\n const search = options?.search\n ? applySearchUpdate(prev, options.search)\n : prev;\n const entry = browserEntryState();\n writeBrowserUrl(\n `${targetPathname(target)}${recordToSearch(search)}`,\n options?.replace,\n options?.replace ? entry.phOpenedFrom : (entry.phIndex ?? 0),\n );\n // No router selects for it, and pushState fires no popstate.\n syncSelectionAfterOpen();\n },\n closeOpened: () => {\n const entry = browserEntryState();\n const index = entry.phIndex ?? 0;\n const from = openedFromIndex(entry, index);\n if (from === undefined) return false;\n window.history.go(from - index);\n return true;\n },\n setSearch: setBrowserSearch,\n useSearchParams() {\n const search = useSyncExternalStore(\n subscribeToLocation,\n readSearch,\n readServerSearch,\n );\n return useMemo(() => searchToRecord(search), [search]);\n },\n useSetSearchParams: () => setBrowserSearchParams,\n};\n\nconst NO_PARAMS: Record<string, string> = {};\nconst noop = () => {};\n\n// A scope without a navigation of its own: no URL, so opening only selects.\nconst detachedNavigation: PHNavigation = {\n location: () => ({ pathname: \"\", search: \"\" }),\n open: noop,\n setSearch: noop,\n useSearchParams: () => NO_PARAMS,\n useSetSearchParams: () => noop,\n};\n\n/** The navigation `store` acts through: a scope's own, else the app's. */\nexport function getNavigationOf(store: PHStore | undefined): PHNavigation {\n if (store && isScopedPHStore(store)) {\n return store.navigation ?? detachedNavigation;\n }\n return store?.navigation ?? getPHNavigation();\n}\n\n/** True when the store has a host navigation, not the browser fallback. */\nexport function hasHostNavigation() {\n return !isServer && getPHStore()?.navigation !== undefined;\n}\n\n/** The app store's navigation, else the browser fallback. */\nexport function getPHNavigation(): PHNavigation {\n return getPHStore()?.navigation ?? browserNavigation;\n}\n\n/** The current pathname as the navigation sees it, base path included. */\nexport function getCurrentPathname() {\n return getPHNavigation().location().pathname;\n}\n\n/** Opens `target`; without `search`, a target already open is left alone. */\nexport function openTarget(\n target: PHNavigationTarget | undefined,\n options?: PHNavigateOptions,\n) {\n openTargetWith(getPHNavigation(), target, options);\n}\n\n/** Opens `target` through `navigation`, unless it is open already. */\nexport function openTargetWith(\n navigation: PHNavigation,\n target: PHNavigationTarget | undefined,\n options?: PHNavigateOptions,\n) {\n const pathname = navigation.location().pathname;\n const targetPath = targetPathname(target);\n // On any tab, the settings page is open.\n const open =\n targetPath === pathname ||\n (isSettingsTarget(target) &&\n target.settings === true &&\n pathname.startsWith(`${targetPath}/`));\n if (!options?.search && open) return;\n navigation.open(target, options);\n}\n\n/** Asks the host navigation to warm `target`; a no-op without one. */\nexport function preloadTarget(target: PHNavigationTarget | undefined) {\n if (!hasHostNavigation()) return;\n getPHNavigation().preload?.(target);\n}\n\n/** The href `target` opens at through `navigation`, base path included. */\nexport function getTargetHref(\n target: PHNavigationTarget | undefined,\n navigation: PHNavigation = getPHNavigation(),\n) {\n return navigation.hrefFor?.(target) ?? targetPathname(target);\n}\n\nexport function resolveSearchUpdate(\n prev: Record<string, string>,\n update: SearchParamsUpdate,\n): Record<string, string> {\n return typeof update === \"function\"\n ? applySearchUpdate({}, update(prev))\n : applySearchUpdate(prev, update);\n}\n\n/** Rewrites the current query params through the app store's navigation. */\nexport function setSearchParams(\n update: SearchParamsUpdate,\n options?: { replace?: boolean },\n) {\n getPHNavigation().setSearch(\n (prev) => resolveSearchUpdate(prev, update),\n options,\n );\n}\n"],"mappings":";;;;;AASA,MAAM,oBAAoB;AAG1B,SAAgB,mBAAmB,MAAc;CAC/C,OAAO,IAAI,IACT,KAAK,QAAQ,QAAQ,EAAE,GACvB,OAAO,SAAS,UAAU,WAAW,CAAC,EAAE,YAAY,IACtD,CAAC,CAAC;AACJ;;AAGA,SAAgB,mBAAmB,MAAc;CAC/C,MAAM,WAAW,WAAW,CAAC,EAAE,YAAY;CAC3C,IAAI,CAAC,KAAK,WAAW,QAAQ,GAAG,OAAO;CACvC,MAAM,OAAO,KAAK,MAAM,SAAS,MAAM;CACvC,IAAI,SAAS,SAAS,GAAG,GAAG,OAAO,IAAI;CACvC,OAAO,SAAS,MAAM,KAAK,WAAW,GAAG,IAAI,OAAO;AACtD;;;AAIA,SAAgB,sBACd,OACA;CACA,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,MAAM,KAAK,MAAM,OAAO,IAAI;AACrC;;;AAIA,SAAgB,cAAc,OAA8B;CAC1D,MAAM,EAAE,IAAI,MAAM,cAAc,MAAM;CACtC,IAAI,aAAa,cAAc,IAAI,OAAO;CAC1C,OAAO,WAAW,EAAE,IAAI,eAAe,KAAK,IAAI;AAClD;AAEA,SAAS,WAAW,IAAY;CAC9B,OAAO,SAAS,EAAE,MAAM,KAAA,KAAa,oBAAoB,EAAE;AAC7D;AAEA,SAAS,eAAe,OAA8B;CAEpD,OAAO,UAAU,OADJ,MAAM,MAAM,OAAO,QAAQ,MAAM,OAAO,MACvB,MAAM,OAAO,EAAE;AAC/C;AAEA,MAAM,6BAAa,IAAI,QAGrB;AAGF,SAAS,UAAU,OAAe,MAAc,IAAY;CAC1D,MAAM,SAAS,WAAW,IAAI,KAAK;CAC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AACjC;;AAGA,SAAgB,cAAc,QAAwC;CACpE,IAAI,CAAC,kBAAkB,GAAG;CAC1B,gBAAgB,CAAC,CAAC,UAAU,MAAM;AACpC;;AAGA,SAAgB,cACd,QACA,aAA2B,gBAAgB,GAC3C;CACA,OAAO,WAAW,UAAU,MAAM,KAAK,eAAe,MAAM;AAC9D;AAEA,SAAgB,oBACd,MACA,QACwB;CACxB,OAAO,OAAO,WAAW,aACrB,kBAAkB,CAAC,GAAG,OAAO,IAAI,CAAC,IAClC,kBAAkB,MAAM,MAAM;AACpC;;AAGA,SAAgB,gBACd,QACA,SACA;CACA,gBAAgB,CAAC,CAAC,WACf,SAAS,oBAAoB,MAAM,MAAM,GAC1C,OACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard-CiYrfAcM.js","names":[],"sources":["../src/utils/nodes.ts","../src/hooks/items-in-selected-drive.ts","../src/hooks/selected-node.ts","../src/hooks/document-of-type.ts","../src/hooks/selected-document.ts","../src/ai/switchboard.ts"],"sourcesContent":["import type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n","import type {\n FileNode,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelDocument,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { isFileNodeKind, isFolderNodeKind } from \"../utils/nodes.js\";\nimport { useDocumentsByIds } from \"./document-by-id.js\";\nimport { useSelectedDriveSafe } from \"./selected-drive.js\";\n\n/** Returns the nodes in the selected drive. */\nexport function useNodesInSelectedDrive() {\n const [selectedDrive] = useSelectedDriveSafe();\n return selectedDrive?.state.global.nodes;\n}\n\n/** Returns the file nodes in the selected drive. */\nexport function useFileNodesInSelectedDrive(): FileNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFileNodeKind(n));\n}\n\n/** Returns the folder nodes in the selected drive. */\nexport function useFolderNodesInSelectedDrive(): FolderNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFolderNodeKind(n));\n}\n\n/** Returns the documents in the selected drive. */\nexport function useDocumentsInSelectedDrive(): PHDocument[] | undefined {\n const fileNodes = useFileNodesInSelectedDrive();\n const fileNodeIds = fileNodes?.map((node) => node.id);\n return useDocumentsByIds(fileNodeIds);\n}\n\n/** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */\nexport function useDocumentTypesInSelectedDrive() {\n const documentsInSelectedDrive = useDocumentsInSelectedDrive();\n const documentModelDocumentsInSelectedDrive =\n documentsInSelectedDrive?.filter(isDocumentModelDocument);\n const documentTypesFromDocumentModelDocuments =\n documentModelDocumentsInSelectedDrive?.map((doc) => doc.state.global.id);\n return documentTypesFromDocumentModelDocuments;\n}\n\nfunction isDocumentModelDocument(\n document: PHDocument,\n): document is DocumentModelDocument {\n return document.header.documentType === \"powerhouse/document-model\";\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedNodeId } from \"./set-selected-node.js\";\n\nexport {\n addResetSelectedNodeEventHandler,\n addSelectedNodeIdEventHandler,\n getNodeTarget,\n getNodeTargetIn,\n preloadNode,\n setSelectedNode,\n setSelectedNodeId,\n useOpenNode,\n usePreloadNode,\n useSetSelectedNode,\n} from \"./set-selected-node.js\";\nexport { addSetSelectedNodeOnPopStateEventHandler } from \"./sync-selection.js\";\n\n/** Returns the selected node. */\nexport function useSelectedNode(): Node | undefined {\n const selectedNodeId = useSelectedNodeId();\n const nodes = useNodesInSelectedDrive();\n return nodes?.find((n) => n.id === selectedNodeId);\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { DocumentTypeMismatchError } from \"../errors.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\n\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nexport function useDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentId: string | null | undefined,\n documentType: string | null | undefined,\n) {\n const [document, dispatch] = useDocumentById(documentId);\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentId || !documentType) return [];\n\n if (!document) {\n throw new Error(`Document not found: ${documentId}`);\n }\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n documentId,\n documentType,\n document.header.documentType,\n );\n }\n\n return [document, dispatch] as [TDocument, DocumentDispatch<TAction>];\n}\n","import type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { NoSelectedDocumentError } from \"../errors.js\";\nimport type { DispatchFn, UseDispatchResult } from \"./dispatch.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentOfType } from \"./document-of-type.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected document id */\nexport function useSelectedDocumentId(): string | undefined {\n const selectedNode = useSelectedNode();\n return selectedNode && isFileNode(selectedNode) ? selectedNode.id : undefined;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocument(): readonly [\n PHDocument,\n DispatchFn<Action>,\n] {\n const selectedDocumentId = useSelectedDocumentId();\n const [document, dispatch] = useDocumentById(selectedDocumentId);\n if (!document) {\n throw new NoSelectedDocumentError();\n }\n return [document, dispatch] as const;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocumentSafe(): UseDispatchResult<\n PHDocument,\n Action\n> {\n const selectedDocumentId = useSelectedDocumentId();\n return useDocumentById(selectedDocumentId);\n}\n\n/** Returns the selected document of a specific type, throws an error if the found document has a different type */\nexport function useSelectedDocumentOfType(\n documentType: null | undefined,\n): never[];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(documentType: string): [TDocument, DocumentDispatch<TAction>];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentType: string | null | undefined,\n): never[] | [TDocument, DocumentDispatch<TAction>] {\n const documentId = useSelectedDocumentId();\n // Called on every render; without a type it reads no document.\n const result = useDocumentOfType<TDocument, TAction>(\n documentType ? documentId : null,\n documentType,\n );\n\n if (!documentType) {\n return [];\n }\n if (!documentId) {\n throw new NoSelectedDocumentError();\n }\n return result;\n}\n","import { getPHStore } from \"../hooks/ph-store.js\";\nimport { DriveCollectionId, type ISyncManager } from \"@powerhousedao/reactor\";\nimport { z } from \"zod\";\nimport { ambientRenownTokenProvider } from \"../graphql-client/auth.js\";\nimport type { AiToolDescriptor } from \"./types.js\";\n\n/**\n * The switchboard serving a remote drive: the base URL the browser talks to\n * and its GraphQL supergraph endpoint.\n */\nexport interface DriveSwitchboard {\n /** Switchboard base URL (e.g. `http://localhost:4001`). */\n switchboardUrl: string;\n /** GraphQL supergraph endpoint (`<base>/graphql`). */\n graphqlUrl: string;\n}\n\n/**\n * Reads the tab-side sync manager from the browser global. Returns\n * `undefined` in non-browser environments or before the reactor client\n * module is initialized.\n */\nexport function getBrowserSyncManager(): ISyncManager | undefined {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n return getPHStore()?.reactorClientModule?.reactorModule?.syncModule\n ?.syncManager;\n}\n\n/** Suffix of the per-drive GraphQL channel endpoint the switchboard serves. */\nexport const GQL_CHANNEL_SUFFIX = \"/graphql/r\";\n\n/**\n * Resolves the switchboard that serves a drive, if any.\n *\n * Every remote drive stores its switchboard's exact GraphQL channel\n * endpoint in its sync remote — `channelConfig = { type: \"gql\",\n * parameters: { url: \"<origin>/graphql/r\" } }` — and the switchboard base\n * is that URL minus the `/graphql/r` suffix. Deriving it per drive (rather\n * than from a global setting) is what keeps multi-switchboard deployments\n * correct. Drives that are not synced to a remote switchboard (local\n * drives, other channel types, unexpected shapes) return `undefined`.\n */\nexport function resolveDriveSwitchboard(\n driveId: string | undefined,\n syncManager?: ISyncManager,\n): DriveSwitchboard | undefined {\n const manager = syncManager ?? getBrowserSyncManager();\n if (!driveId || !manager) {\n return undefined;\n }\n const collectionId = DriveCollectionId.forDrive(driveId);\n const remote = manager\n .list()\n .find((r) => r.meta.collectionId.equals(collectionId));\n if (!remote) {\n return undefined;\n }\n const { channelConfig } = remote.meta;\n if (channelConfig.type !== \"gql\") {\n return undefined;\n }\n const url = channelConfig.parameters.url;\n if (typeof url !== \"string\" || !url.endsWith(GQL_CHANNEL_SUFFIX)) {\n return undefined;\n }\n const switchboardUrl = url.slice(0, -GQL_CHANNEL_SUFFIX.length);\n return { switchboardUrl, graphqlUrl: `${switchboardUrl}/graphql` };\n}\n\n/** A bounded introspected GraphQL type reference (see the query below). */\ntype IntrospectedTypeRef = {\n kind: string;\n name: string | null;\n ofType?: IntrospectedTypeRef | null;\n};\n\ntype IntrospectedField = {\n name: string;\n description: string | null;\n args: Array<{ name: string; type: IntrospectedTypeRef }>;\n type: IntrospectedTypeRef;\n};\n\ntype IntrospectedRootType = {\n fields: IntrospectedField[] | null;\n} | null;\n\ntype IntrospectedSchema = {\n queryType?: IntrospectedRootType;\n mutationType?: IntrospectedRootType;\n};\n\n/**\n * Introspection over the switchboard supergraph's root query and mutation\n * fields. Types are requested with three levels of `ofType` nesting so\n * that common shapes like `[X!]!` (LIST(NON_NULL(LIST(X)))) render fully.\n */\nexport const SWITCHBOARD_INTROSPECTION_QUERY: string = /* GraphQL */ `\n query SwitchboardIntrospection {\n __schema {\n queryType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n mutationType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n`;\n\n/**\n * Renders an introspected type reference as a GraphQL type string.\n * Recursion is bounded by the `ofType` nesting of the query, so it always\n * terminates.\n */\nfunction renderTypeRef(type: IntrospectedTypeRef | null | undefined): string {\n if (!type) {\n return \"Unknown\";\n }\n switch (type.kind) {\n case \"NON_NULL\":\n return `${renderTypeRef(type.ofType)}!`;\n case \"LIST\":\n return `[${renderTypeRef(type.ofType)}]`;\n default:\n return type.name ?? \"Unknown\";\n }\n}\n\n/** One root query or mutation field, reduced to a prompt-friendly line. */\nexport type SchemaFieldSummary = {\n name: string;\n description?: string;\n args: string;\n returns: string;\n};\n\n/** Cap on the number of fields reported per root type. */\nconst MAX_FIELDS_PER_ROOT = 200;\n\nfunction summarizeFields(fields: IntrospectedField[] | null | undefined): {\n fields: SchemaFieldSummary[];\n truncated: boolean;\n} {\n const list = fields ?? [];\n return {\n fields: list.slice(0, MAX_FIELDS_PER_ROOT).map((field) => ({\n name: field.name,\n ...(field.description ? { description: field.description } : {}),\n args: field.args\n .map((arg) => `${arg.name}: ${renderTypeRef(arg.type)}`)\n .join(\", \"),\n returns: renderTypeRef(field.type),\n })),\n truncated: list.length > MAX_FIELDS_PER_ROOT,\n };\n}\n\n/**\n * Reduces a GraphQL `__schema` introspection payload (the `data.__schema`\n * object) to a compact summary of its root query and mutation fields.\n * Accepts `unknown` because the payload arrives over the wire.\n */\nexport function summarizeIntrospectionSchema(schema: unknown): {\n queries: SchemaFieldSummary[];\n mutations: SchemaFieldSummary[];\n truncated: boolean;\n} {\n const introspection = (schema ?? {}) as IntrospectedSchema;\n const queries = summarizeFields(introspection.queryType?.fields);\n const mutations = summarizeFields(introspection.mutationType?.fields);\n return {\n queries: queries.fields,\n mutations: mutations.fields,\n truncated: queries.truncated || mutations.truncated,\n };\n}\n\nexport const SWITCHBOARD_SCHEMA_TOOL_NAME = \"getSwitchboardSchema\";\n\n/** Test seams for {@link createSwitchboardSchemaTool}. */\nexport interface SwitchboardToolDeps {\n getSyncManager?: () => ISyncManager | undefined;\n getSelectedDriveId?: () => string | undefined;\n tokenProvider?: () => Promise<string | undefined>;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}\n\n/**\n * Creates the read-only `getSwitchboardSchema` tool: it introspects the\n * GraphQL supergraph of the switchboard serving a drive and returns a\n * summary of its root queries and mutations. It reads the schema only and\n * never modifies data.\n */\nexport function createSwitchboardSchemaTool(\n deps?: SwitchboardToolDeps,\n): AiToolDescriptor {\n const getSyncManager = deps?.getSyncManager ?? getBrowserSyncManager;\n const getSelectedDriveId =\n deps?.getSelectedDriveId ??\n ((): string | undefined =>\n typeof window === \"undefined\"\n ? undefined\n : getPHStore()?.selectedDriveId);\n const tokenProvider = deps?.tokenProvider ?? ambientRenownTokenProvider;\n const fetchImpl = deps?.fetchImpl ?? fetch;\n const timeoutMs = deps?.timeoutMs ?? 10_000;\n\n return {\n name: SWITCHBOARD_SCHEMA_TOOL_NAME,\n description:\n \"Introspect the GraphQL endpoint of the switchboard serving a drive and list the queries and mutations it exposes (reactor operations, document-model read models, package subgraphs). Read-only: it reads the schema only and never modifies data. Omit driveId to introspect the currently selected drive.\",\n inputSchema: {\n driveId: z\n .string()\n .describe(\n \"Drive to introspect. Omit to use the currently selected drive.\",\n )\n .optional(),\n },\n annotations: { readOnlyHint: true },\n callback: async (input: { driveId?: string } | undefined) => {\n const driveId = input?.driveId ?? getSelectedDriveId();\n const sb = resolveDriveSwitchboard(driveId, getSyncManager());\n if (!sb) {\n throw new Error(\n driveId\n ? `Drive \"${driveId}\" has no switchboard: it is not synced to a remote switchboard.`\n : \"No drive is currently selected and no driveId was given.\",\n );\n }\n\n const token = await tokenProvider();\n let response: Response;\n try {\n response = await fetchImpl(sb.graphqlUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({ query: SWITCHBOARD_INTROSPECTION_QUERY }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} is not reachable: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} refused the request (HTTP ${response.status}). Sign in to the switchboard (Renown) and try again.`,\n );\n }\n if (!response.ok) {\n throw new Error(\n `Switchboard introspection failed: HTTP ${response.status} ${response.statusText} from ${sb.graphqlUrl}`,\n );\n }\n\n const body = (await response.json()) as {\n errors?: Array<{ message?: string }>;\n data?: { __schema?: unknown } | null;\n } | null;\n const schemaErrors = body?.errors;\n if (schemaErrors && schemaErrors.length > 0) {\n throw new Error(\n schemaErrors.map((e) => e.message ?? \"unknown error\").join(\"; \"),\n );\n }\n const schema = body?.data?.__schema as\n | IntrospectedSchema\n | null\n | undefined;\n if (!schema?.queryType) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} did not return a GraphQL schema.`,\n );\n }\n\n const summary = summarizeIntrospectionSchema(schema);\n return {\n switchboardUrl: sb.switchboardUrl,\n graphqlUrl: sb.graphqlUrl,\n ...summary,\n };\n },\n };\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,gBAAgC,OAAY;CAC1D,OAAO,MAAM,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