@powerhousedao/reactor-browser 6.3.0-dev.9 → 6.4.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +0 -12
  2. package/dist/{attachment-service-B-AmTrs2.d.ts → attachment-service-0E5S0hZ6.d.ts} +53 -24
  3. package/dist/attachment-service-0E5S0hZ6.d.ts.map +1 -0
  4. package/dist/{document-model-modules-BG-61uke.js → document-model-modules-DCC6DjOP.js} +2 -2
  5. package/dist/{document-model-modules-BG-61uke.js.map → document-model-modules-DCC6DjOP.js.map} +1 -1
  6. package/dist/{document-operations-DRMMwmGZ.js → document-operations-BUbpyfSf.js} +143 -251
  7. package/dist/document-operations-BUbpyfSf.js.map +1 -0
  8. package/dist/{global-iARBhxNI.d.ts → global-DfeQC3Fg.d.ts} +3 -53
  9. package/dist/global-DfeQC3Fg.d.ts.map +1 -0
  10. package/dist/{index-CNS_9THu.d.ts → index-BlCYgfht.d.ts} +3 -10
  11. package/dist/{index-CNS_9THu.d.ts.map → index-BlCYgfht.d.ts.map} +1 -1
  12. package/dist/index.d.ts +6 -129
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +7 -9
  15. package/dist/index.js.map +1 -1
  16. package/dist/{renown-CBoTdGrg.js → renown-BXiV_I-t.js} +2 -22
  17. package/dist/renown-BXiV_I-t.js.map +1 -0
  18. package/dist/{renown-B3MUaiq7.js → renown-BlvHEYjM.js} +3 -12
  19. package/dist/{renown-B3MUaiq7.js.map → renown-BlvHEYjM.js.map} +1 -1
  20. package/dist/src/ai/index.js +3 -3
  21. package/dist/src/graphql-client/entry.d.ts +3 -3
  22. package/dist/src/graphql-client/entry.js +2 -2
  23. package/dist/src/renown/index.d.ts +2 -2
  24. package/dist/src/renown/index.js +3 -3
  25. package/dist/{switchboard-directory-vH6qtkh-.js → switchboard-directory-CwT34q4g.js} +2 -2
  26. package/dist/switchboard-directory-CwT34q4g.js.map +1 -0
  27. package/package.json +10 -10
  28. package/dist/attachment-service-B-AmTrs2.d.ts.map +0 -1
  29. package/dist/document-operations-DRMMwmGZ.js.map +0 -1
  30. package/dist/global-iARBhxNI.d.ts.map +0 -1
  31. package/dist/renown-CBoTdGrg.js.map +0 -1
  32. package/dist/switchboard-directory-vH6qtkh-.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"global-iARBhxNI.d.ts","names":[],"sources":["../src/types/documents.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/hooks/ph-store.tsx","../src/hooks/drive-nodes.ts","../src/types/global.ts"],"mappings":";;;;;;;;;;;;;;;KAOY,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,SAAS,eAAe,oBAAoB,QAAQ;EACpD,UAAU,uBAAuB;;EAEjC,iBAAiB,aAAa;;;KAIpB;;EAEV;;EAEA,qBAAqB;;EAErB;;EAEA;;;KAIU;;EAEV;;EAEA;;EAEA;;EAEA;;;;UAKe;;EAEf,wBAAwB,cAAc,gBAAgB;;EAEtD,oBAAoB,cAAc,gBAAgB;;EAElD,wBAAwB,cAAc;;EAEtC,yBACE,cACA,eACA;;;;;;;UASa;;EAEf,mBAAmB,oBAAoB,gBAAgB;;EAEvD,eAAe,oBAAoB,eAAe;;EAElD,mBAAmB,oBAAoB;;EAEvC,qBAAqB;;EAErB,oBAAoB,oBAAoB;;;;KC9F9B,mBAAiB,uBAC3B,gBACA,2BACA,uBACA,0BACA,qCACA,2BACA,uBACA;KAEU,4BAA0B;KAC1B,0BACV,4BA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e,uBACxC;KAGQ,mBAAiB,eAAe,kBAC1C,OAAO;KAGG;KAEA,6BAA6B,OACvC,eACA;KAGU,SAAS,aAAa,iBAAe,eAC9C,OAAO,OAAO,WAAS;QAGlB;YACI;IACR,KAAK;;YAEG,uBAAuB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"renown-CBoTdGrg.js","names":[],"sources":["../src/utils/url.ts","../src/hooks/navigation.ts","../src/hooks/loading.ts","../src/renown/initial-user.tsx","../src/hooks/renown.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): string {\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): string {\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): 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): DocumentDriveDocument | undefined {\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): string {\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 { getPHStore } 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\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","import type { LOADING } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nexport const {\n useValue: useLoading,\n setValue: setLoading,\n addEventHandler: addLoadingEventHandler,\n} = makePHEventFunctions(\"loading\");\n\nexport const loading: LOADING = null;\n","\"use client\";\n\nimport type { User } from \"@renown/sdk\";\nimport { createContext, useContext, type ReactNode } from \"react\";\n\n/** Whether the first render already knows who (if anyone) is signed in. */\n// \"anonymous\" is load-bearing: it separates a signed-out visitor from an\n// unresolved one, which otherwise both have to render a spinner.\nexport type RenownInitialAuth =\n | { state: \"authenticated\"; user: User }\n | { state: \"anonymous\" }\n | { state: \"unknown\" };\n\nexport const RENOWN_INITIAL_UNKNOWN: RenownInitialAuth = { state: \"unknown\" };\nexport const RENOWN_INITIAL_ANONYMOUS: RenownInitialAuth = {\n state: \"anonymous\",\n};\n\n// Seeds the auth store's first render (server + hydration) from a session\n// cookie or localStorage, enabling authenticated SSR without a flash.\nconst RenownInitialUserContext = createContext<RenownInitialAuth>(\n RENOWN_INITIAL_UNKNOWN,\n);\n\nexport interface RenownInitialUserProviderProps {\n /** Resolved first-render auth (see `RenownProvider`). Takes precedence over `initialUser`. */\n initialAuth?: RenownInitialAuth;\n /** User resolved from a verified session cookie (see `verifyRenownSession`). */\n initialUser?: User;\n children: ReactNode;\n}\n\nexport function RenownInitialUserProvider({\n initialAuth,\n initialUser,\n children,\n}: RenownInitialUserProviderProps) {\n // `initialUser` alone cannot express \"anonymous\" — absence stays \"unknown\".\n const value =\n initialAuth ??\n (initialUser\n ? { state: \"authenticated\" as const, user: initialUser }\n : RENOWN_INITIAL_UNKNOWN);\n return (\n <RenownInitialUserContext.Provider value={value}>\n {children}\n </RenownInitialUserContext.Provider>\n );\n}\n\n/** First-render auth as a three-state value; use this to skip a spinner when anonymous. */\nexport function useRenownInitialAuth(): RenownInitialAuth {\n return useContext(RenownInitialUserContext);\n}\n\nexport function useRenownInitialUser(): User | undefined {\n const initial = useRenownInitialAuth();\n return initial.state === \"authenticated\" ? initial.user : undefined;\n}\n","import type { IRenown, LoginStatus, User } from \"@renown/sdk\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport { useRenownInitialUser } from \"../renown/initial-user.js\";\nimport type { LOADING } from \"../types/global.js\";\nimport { loading } from \"./loading.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst renownEventFunctions = makePHEventFunctions(\"renown\");\n\n/** Adds an event handler for the renown instance */\nexport const addRenownEventHandler: () => void =\n renownEventFunctions.addEventHandler;\n\n/** Returns the renown instance */\nexport const useRenown: () => IRenown | LOADING | undefined =\n renownEventFunctions.useValue;\n\n/** Sets the renown instance */\nexport const setRenown: (value: IRenown | LOADING | undefined) => void =\n renownEventFunctions.setValue;\n\n/** Returns the DID from the renown instance */\nexport function useDid() {\n const renown = useRenown();\n return renown?.did;\n}\n\n// Order-insensitive structural equality for plain JSON (what a persisted user\n// is): the cookie and localStorage paths build the same user with different key\n// order, and both must keep one object identity for did-keyed consumers.\nfunction jsonEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || !a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const ra = a as Record<string, unknown>;\n const rb = b as Record<string, unknown>;\n const keys = Object.keys(ra).filter((k) => ra[k] !== undefined);\n if (keys.length !== Object.keys(rb).filter((k) => rb[k] !== undefined).length)\n return false;\n return keys.every((k) => jsonEqual(ra[k], rb[k]));\n}\n\nfunction sameUser(a: User | undefined, b: User | undefined): boolean {\n return jsonEqual(a, b);\n}\n\n// What the SDK says once it exists. Its `user` is a synchronous storage read,\n// so undefined with status \"initial\" means nothing was restored and a stale seed\n// (e.g. a cookie outliving localStorage) must go; during \"checking\"/\"authorized\"\n// the SDK owns a session it has not published yet, so the seed stands.\nfunction resolveInstanceUser(\n instance: IRenown,\n seed: User | undefined,\n): User | undefined {\n const restored = instance.user;\n if (restored) return sameUser(seed, restored) ? seed : restored;\n return instance.status === \"initial\" ? undefined : seed;\n}\n\ninterface TrackedUser {\n instance: IRenown | undefined;\n user: User | undefined;\n}\n\n/** Returns the current user from the renown instance, subscribing to user events */\nexport function useUser(): User | undefined {\n const renown = useRenown();\n // Seed (cookie on the server, localStorage once mounted) covers the first\n // paint; the SDK is authoritative after, so a logout/revoke clears it.\n const initialUser = useRenownInitialUser();\n const instance = renown ? renown : undefined;\n // Tagged with the instance it came from. On a swap the value for this render\n // is derived here (state alone would be one frame stale) and persisted after\n // commit; the derivation is pure, so re-renders before that agree.\n const [tracked, setTracked] = useState<TrackedUser>(() => ({\n instance,\n user: instance ? resolveInstanceUser(instance, initialUser) : initialUser,\n }));\n const current: TrackedUser =\n tracked.instance === instance\n ? tracked\n : {\n instance,\n user: instance\n ? resolveInstanceUser(instance, tracked.user ?? initialUser)\n : tracked.user,\n };\n\n useEffect(() => {\n if (current !== tracked) setTracked(current);\n }, [current, tracked]);\n\n useEffect(() => {\n if (!instance) return;\n return instance.on(\"user\", (user) =>\n setTracked((prev) => ({\n instance,\n user: sameUser(prev.user, user) ? prev.user : user,\n })),\n );\n }, [instance]);\n\n // Until the SDK exists the seed wins, which is what lands the post-mount\n // localStorage read.\n return instance ? current.user : (initialUser ?? current.user);\n}\n\n/** Returns the login status, subscribing to renown status events */\nexport function useLoginStatus(): LoginStatus | \"loading\" | undefined {\n const renown = useRenown();\n return useSyncExternalStore(\n (cb) => {\n if (!renown) {\n return () => {};\n }\n return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AG,IAAI,GAAG,EAAE,CAAC;AAClD;AAEA,SAAS,SAAS,GAAqB,GAA8B;CACnE,OAAO,UAAU,GAAG,CAAC;AACvB;AAMA,SAAS,oBACP,UACA,MACkB;CAClB,MAAM,WAAW,SAAS;CAC1B,IAAI,UAAU,OAAO,SAAS,MAAM,QAAQ,IAAI,OAAO;CACvD,OAAO,SAAS,WAAW,YAAY,KAAA,IAAY;AACrD;;AAQA,SAAgB,UAA4B;CAC1C,MAAM,SAAS,UAAU;CAGzB,MAAM,cAAc,qBAAqB;CACzC,MAAM,WAAW,SAAS,SAAS,KAAA;CAInC,MAAM,CAAC,SAAS,cAAc,gBAA6B;EACzD;EACA,MAAM,WAAW,oBAAoB,UAAU,WAAW,IAAI;CAChE,EAAE;CACF,MAAM,UACJ,QAAQ,aAAa,WACjB,UACA;EACE;EACA,MAAM,WACF,oBAAoB,UAAU,QAAQ,QAAQ,WAAW,IACzD,QAAQ;CACd;CAEN,gBAAgB;EACd,IAAI,YAAY,SAAS,WAAW,OAAO;CAC7C,GAAG,CAAC,SAAS,OAAO,CAAC;CAErB,gBAAgB;EACd,IAAI,CAAC,UAAU;EACf,OAAO,SAAS,GAAG,SAAS,SAC1B,YAAY,UAAU;GACpB;GACA,MAAM,SAAS,KAAK,MAAM,IAAI,IAAI,KAAK,OAAO;EAChD,EAAE,CACJ;CACF,GAAG,CAAC,QAAQ,CAAC;CAIb,OAAO,WAAW,QAAQ,OAAQ,eAAe,QAAQ;AAC3D;;AAGA,SAAgB,iBAAsD;CACpE,MAAM,SAAS,UAAU;CACzB,OAAO,sBACJ,OAAO;EACN,IAAI,CAAC,QACH,aAAa,CAAC;EAEhB,OAAO,OAAO,GAAG,UAAU,EAAE;CAC/B,SACO,WAAA,OAAqB,YAAY,QAAQ,cAC1C,KAAA,CACR;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"switchboard-directory-vH6qtkh-.js","names":[],"sources":["../src/hooks/node-by-id.ts","../src/hooks/selected-node.ts","../src/hooks/document-of-type.ts","../src/hooks/editor-context.tsx","../src/hooks/selected-document.ts","../src/utils/gql-channel.ts","../src/utils/switchboard.ts","../src/utils/switchboard-directory.ts"],"sourcesContent":["import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useDriveNode } from \"./drive-nodes.js\";\nimport { useSelectedDriveId } from \"./selected-drive.js\";\n\n/** Returns a node in the selected drive by id. */\nexport function useNodeById(id: string | null | undefined): Node | undefined {\n return useDriveNode(useSelectedDriveId(), id);\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodeById } from \"./node-by-id.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 return useNodeById(useSelectedNodeId());\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","/** Suffix of the per-drive GraphQL channel endpoint the switchboard serves. */\nexport const GQL_CHANNEL_SUFFIX = \"/graphql/r\";\n","import { pascalCase } from \"change-case\";\nimport type { DocumentModelModule } from \"document-model\";\nimport {\n Kind,\n parse,\n type DefinitionNode,\n type InterfaceTypeDefinitionNode,\n type ObjectTypeDefinitionNode,\n type TypeNode,\n type UnionTypeDefinitionNode,\n} from \"graphql\";\nimport lzString from \"lz-string\";\nimport { GQL_CHANNEL_SUFFIX } from \"./gql-channel.js\";\nimport { GetDocumentWithOperationsDocument } from \"../graphql/gen/schema.js\";\n\nexport async function getDriveIdBySlug(driveUrl: string, slug: string) {\n if (!driveUrl) {\n return;\n }\n\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"drives\"); // add /drives\n const drivesUrl = urlParts.join(\"/\");\n const result = await fetch(drivesUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n query: `\n query getDriveIdBySlug($slug: String!) {\n driveIdBySlug(slug: $slug)\n }\n `,\n variables: {\n slug,\n },\n }),\n });\n\n const data = (await result.json()) as {\n data: { driveIdBySlug: string };\n };\n\n return data.data.driveIdBySlug;\n}\n\nexport function getSlugFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n return urlParts.pop();\n}\n\nexport function getSwitchboardGatewayUrlFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"graphql\"); // add /graphql\n return urlParts.join(\"/\");\n}\n\nexport function getDocumentGraphqlQuery() {\n const loc = GetDocumentWithOperationsDocument.loc;\n if (!loc) {\n throw new Error(\n \"GetDocumentWithOperationsDocument is misconfigured, loc is missing.\",\n );\n }\n return loc.source.body;\n}\n\n/**\n * The base URL of the switchboard that serves a drive's GraphQL channel.\n *\n * The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the\n * suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does\n * not end with the suffix is unexpected — fall back to its origin.\n */\nexport function getSwitchboardBaseFromChannelUrl(channelUrl: string): string {\n if (channelUrl.endsWith(GQL_CHANNEL_SUFFIX)) {\n return channelUrl.slice(0, -GQL_CHANNEL_SUFFIX.length);\n }\n return new URL(channelUrl).origin;\n}\n\n/**\n * The GraphQL name the switchboard exposes a document model under. Mirrors\n * `getDocumentModelSchemaName` on the server (`model-schema-templates.ts`): the root\n * query field and the state type names are all derived from the model's\n * `global.name`.\n */\nfunction getDocumentModelSchemaName(model: DocumentModelModule): string {\n return pascalCase(model.documentModel.global.name.replaceAll(\"/\", \" \"));\n}\n\ntype StateType =\n | ObjectTypeDefinitionNode\n | InterfaceTypeDefinitionNode\n | UnionTypeDefinitionNode;\n\nfunction buildStateTypeMap(definitions: ReadonlyArray<DefinitionNode>) {\n const typeMap = new Map<string, StateType>();\n for (const def of definitions) {\n if (\n def.kind === Kind.OBJECT_TYPE_DEFINITION ||\n def.kind === Kind.INTERFACE_TYPE_DEFINITION ||\n def.kind === Kind.UNION_TYPE_DEFINITION\n ) {\n typeMap.set(def.name.value, def);\n }\n }\n return typeMap;\n}\n\n/**\n * Recursively expands the fields of a state object type into a GraphQL\n * selection. Objects expand their sub-selection (lists expand their item\n * type); enums, scalars, and built-ins are leaves.\n */\nfunction expandStateFields(\n typeDef: StateType,\n typeMap: Map<string, StateType>,\n): string {\n if (typeDef.kind !== Kind.OBJECT_TYPE_DEFINITION) {\n throw new Error(\n `Abstract state type requires the generic document query: ${typeDef.name.value}`,\n );\n }\n return (typeDef.fields ?? [])\n .map((field) => {\n const fieldName = field.name.value;\n let typeNode: TypeNode = field.type;\n if (typeNode.kind === Kind.NON_NULL_TYPE) {\n typeNode = typeNode.type;\n }\n\n if (typeNode.kind === Kind.LIST_TYPE) {\n let itemType: TypeNode = typeNode.type;\n if (itemType.kind === Kind.NON_NULL_TYPE) {\n itemType = itemType.type;\n }\n if (itemType.kind === Kind.LIST_TYPE) {\n throw new Error(\n `Nested lists are not supported in state selections: ${fieldName}`,\n );\n }\n if (itemType.kind !== Kind.NAMED_TYPE) {\n return fieldName;\n }\n const itemTypeDef = typeMap.get(itemType.name.value);\n if (!itemTypeDef) {\n // Scalar, enum, or built-in item — a leaf.\n return fieldName;\n }\n return `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;\n }\n\n if (typeNode.kind !== Kind.NAMED_TYPE) {\n return fieldName;\n }\n const typeDef = typeMap.get(typeNode.name.value);\n if (!typeDef) {\n // Scalar, enum, or a type from another schema — a leaf.\n return fieldName;\n }\n return `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;\n })\n .join(\" \");\n}\n\n/**\n * Finds the root state object type in a state SDL. Root state types follow\n * the `<Name>State` / `<Name>GlobalState` conventions, and are defined last\n * by convention — the same resolution order the server uses\n * (`extractRootTypeName` in `create-schema.ts`).\n */\nfunction findRootStateType(\n definitions: ReadonlyArray<DefinitionNode>,\n candidates: string[],\n): ObjectTypeDefinitionNode {\n let lastObjectType: ObjectTypeDefinitionNode | null = null;\n for (const def of definitions) {\n if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) {\n continue;\n }\n if (candidates.includes(def.name.value)) {\n return def;\n }\n lastObjectType = def;\n }\n if (!lastObjectType) {\n throw new Error(\"No root state type found in the document model schema\");\n }\n return lastObjectType;\n}\n\n/**\n * Derives the subselection for the document's `global` state scope from the\n * model's state SDL (e.g. `name total`), expanding object fields\n * recursively. Throws when the schema is missing, unparseable, or has no\n * root object type — the caller falls back to the generic document query.\n */\nexport function getDocumentStateSelection(model: DocumentModelModule): string {\n const spec = model.documentModel.global.specifications.at(-1);\n const schema = spec?.state.global.schema;\n if (!schema || !schema.trim()) {\n throw new Error(\"Document model has no global state schema\");\n }\n const ast = parse(schema);\n const typeMap = buildStateTypeMap(ast.definitions);\n const documentName = getDocumentModelSchemaName(model);\n const rootType = findRootStateType(ast.definitions, [\n `${documentName}State`,\n `${documentName}GlobalState`,\n ]);\n return expandStateFields(rootType, typeMap);\n}\n\nfunction getLocalStateSelection(\n localSchema: string,\n documentName: string,\n): string {\n const ast = parse(localSchema);\n const typeMap = buildStateTypeMap(ast.definitions);\n const rootType = findRootStateType(ast.definitions, [\n `${documentName}LocalState`,\n ]);\n return expandStateFields(rootType, typeMap);\n}\n\n/**\n * Builds a query scoped to a document type's own subgraph root field,\n * selecting the document and its full typed state. The shape mirrors what\n * the switchboard generates per model (`generateNewApiSchema` in\n * `model-schema-templates.ts`): `<Name> { document(idOrSlug:) { document { ...\n * state { auth document global local } } } childIds }`.\n */\nfunction buildModelScopedQuery(model: DocumentModelModule): string {\n const globalState = model.documentModel.global;\n const documentName = getDocumentModelSchemaName(model);\n const globalSelection = getDocumentStateSelection(model);\n\n const spec = globalState.specifications.at(-1);\n const localSchema = spec?.state.local.schema ?? \"\";\n const hasLocalStateType = localSchema.includes(\n `type ${documentName}LocalState`,\n );\n const localSelection = hasLocalStateType\n ? getLocalStateSelection(localSchema, documentName)\n : null;\n\n return [\n \"query GetDocument($idOrSlug: String!) {\",\n ` ${documentName} {`,\n \" document(idOrSlug: $idOrSlug) {\",\n \" document {\",\n \" id\",\n \" name\",\n \" documentType\",\n \" state {\",\n \" auth\",\n \" document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }\",\n ` global { ${globalSelection} }`,\n ` ${localSelection ? `local { ${localSelection} }` : \"local\"}`,\n \" }\",\n \" }\",\n \" childIds\",\n \" }\",\n \" }\",\n \"}\",\n ].join(\"\\n\");\n}\n\nexport function buildDocumentSubgraphQuery(\n documentType: string,\n identifier: string,\n model?: DocumentModelModule,\n authToken?: string,\n): string {\n let query: string;\n // Only trust a model that actually matches the document's type; a model\n // with a different root field would produce a query the supergraph cannot\n // resolve.\n if (model && model.documentModel.global.id === documentType) {\n try {\n query = buildModelScopedQuery(model);\n } catch (error) {\n console.warn(\n \"Could not derive a document-scoped query from the document model, \" +\n \"falling back to the generic document query:\",\n error,\n );\n query = getDocumentGraphqlQuery();\n }\n } else {\n query = getDocumentGraphqlQuery();\n }\n const variables = { idOrSlug: identifier };\n const headers = authToken\n ? {\n Authorization: `Bearer ${authToken}`,\n }\n : undefined;\n\n const payload: Record<string, string> = {\n document: query.trim(),\n variables: JSON.stringify(variables, null, 2),\n };\n if (headers) {\n payload.headers = JSON.stringify(headers);\n }\n return lzString.compressToEncodedURIComponent(JSON.stringify(payload));\n}\n\nexport function buildDocumentSubgraphUrl(\n channelUrl: string,\n documentType: string,\n identifier: string,\n model?: DocumentModelModule,\n authToken?: string,\n): string {\n const encodedQuery = buildDocumentSubgraphQuery(\n documentType,\n identifier,\n model,\n authToken,\n );\n const base = getSwitchboardBaseFromChannelUrl(channelUrl);\n return `${base}/explorer?explorerURLState=${encodedQuery}`;\n}\n","// The switchboards an app reaches, and the one a call should go to. Hosts\n// build the directory once at boot (createSwitchboardDirectory) and set it on\n// their store; callers ask resolveSwitchboard, which never guesses a URL.\nimport { DriveCollectionId, type ISyncManager } from \"@powerhousedao/reactor\";\nimport { ORIGIN_PLACEHOLDER } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport type {\n SwitchboardDirectory,\n SwitchboardEntry,\n SwitchboardWorkflows,\n} from \"../types/switchboards.js\";\nimport { getSwitchboardBaseFromChannelUrl } from \"./switchboard.js\";\n\n/** What a router says about its backends; structural, so hosts pass their own. */\nexport interface SwitchboardRouter {\n readonly backends: readonly {\n readonly name: string;\n readonly facts: {\n readonly known: boolean;\n readonly reactor: { readonly workflows: boolean };\n };\n }[];\n /** The name of the backend that serves `identifier`. */\n locate(identifier: string, signal?: AbortSignal): Promise<string>;\n}\n\nexport interface SwitchboardDirectoryOptions {\n /**\n * The host's remote backends, as the served config lists them\n * (`instance.remoteBackends`): a name and one of the switchboard's drive\n * addresses, `<base>/d/<slug>`.\n */\n remoteBackends?: readonly { readonly name: string; readonly url: string }[];\n /** The router over those backends, for their facts and for `locate`. */\n router?: SwitchboardRouter;\n /** The tab's sync manager, read on each call: every gql remote's switchboard. */\n syncManager?: () => Pick<ISyncManager, \"list\"> | undefined;\n /** What `${origin}` stands for; defaults to the page's origin. */\n origin?: string;\n}\n\n/** `${origin}` resolved against the page; a base stays as it is otherwise. */\nfunction resolveOrigin(base: string, origin: string | undefined): string {\n if (!base.startsWith(ORIGIN_PLACEHOLDER)) return base;\n const page =\n origin ?? (typeof location === \"undefined\" ? undefined : location.origin);\n return page ? page + base.slice(ORIGIN_PLACEHOLDER.length) : base;\n}\n\nfunction trimSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\n/** A synced drive's switchboard, named by its host and path. */\nfunction syncName(base: string): string {\n return base.replace(/^[a-z]+:\\/\\//i, \"\");\n}\n\n/**\n * Builds the directory from the host's remote backends and the tab's synced\n * drives. A backend's facts are read on each `list`, so a refresh shows.\n */\nexport function createSwitchboardDirectory(\n options: SwitchboardDirectoryOptions,\n): SwitchboardDirectory {\n const backends = (options.remoteBackends ?? []).flatMap(({ name, url }) => {\n const drive = switchboardOfDrive(url);\n if (!drive) return [];\n const base = trimSlash(resolveOrigin(drive.base, options.origin));\n return [{ name, base }];\n });\n\n const workflowsOf = (name: string): SwitchboardWorkflows => {\n const backend = options.router?.backends.find((b) => b.name === name);\n if (!backend?.facts.known) return \"unknown\";\n return backend.facts.reactor.workflows;\n };\n\n const remotes = () => {\n try {\n return options.syncManager?.()?.list() ?? [];\n } catch {\n return [];\n }\n };\n\n const syncBase = (remote: ReturnType<typeof remotes>[number]) => {\n const { channelConfig } = remote.meta;\n const url =\n channelConfig.type === \"gql\" ? channelConfig.parameters.url : \"\";\n if (typeof url !== \"string\" || !url) return undefined;\n try {\n return trimSlash(getSwitchboardBaseFromChannelUrl(url));\n } catch {\n return undefined;\n }\n };\n\n const list = (): SwitchboardEntry[] => {\n const entries: SwitchboardEntry[] = backends.map(({ name, base }) => ({\n name,\n base,\n graphqlUrl: `${base}/graphql`,\n via: \"backend\",\n workflows: workflowsOf(name),\n }));\n const seen = new Set(entries.map((entry) => entry.base));\n for (const remote of remotes()) {\n const base = syncBase(remote);\n if (!base || seen.has(base)) continue;\n seen.add(base);\n entries.push({\n name: syncName(base),\n base,\n graphqlUrl: `${base}/graphql`,\n via: \"sync\",\n workflows: \"unknown\",\n });\n }\n return entries;\n };\n\n const locate = async (\n documentId: string,\n signal?: AbortSignal,\n ): Promise<SwitchboardEntry | undefined> => {\n const entries = list();\n const collectionId = DriveCollectionId.forDrive(documentId);\n const remote = remotes().find((r) =>\n r.meta.collectionId.equals(collectionId),\n );\n const synced = remote && syncBase(remote);\n if (synced) return entries.find((entry) => entry.base === synced);\n if (!options.router || backends.length === 0) return undefined;\n let name: string;\n try {\n name = await options.router.locate(documentId, signal);\n } catch (error) {\n if (signal?.aborted) throw error;\n return undefined;\n }\n return entries.find(\n (entry) => entry.via === \"backend\" && entry.name === name,\n );\n };\n\n return { list, locate };\n}\n\nexport type SwitchboardLookupErrorCode =\n | \"NO_DIRECTORY\"\n | \"NO_SWITCHBOARD\"\n | \"UNKNOWN_SWITCHBOARD\"\n | \"AMBIGUOUS_SWITCHBOARD\"\n | \"NO_WORKFLOW_RUNTIME\";\n\n/** Why no switchboard could be picked, with the ones there are. */\nexport class SwitchboardLookupError extends Error {\n constructor(\n message: string,\n readonly code: SwitchboardLookupErrorCode,\n readonly switchboards: readonly SwitchboardEntry[] = [],\n ) {\n super(message);\n this.name = \"SwitchboardLookupError\";\n }\n}\n\nexport interface SwitchboardRequest {\n /** A name from the directory, or a URL on the switchboard (its base, GraphQL or any path under it). */\n switchboard?: string;\n /** The document or drive the call is about: its switchboard, when the directory can place it. */\n documentId?: string;\n /** What the switchboard must run. */\n need?: \"workflows\";\n signal?: AbortSignal;\n}\n\nfunction describe(entry: SwitchboardEntry): string {\n const workflows =\n entry.workflows === \"unknown\"\n ? \"workflows unknown\"\n : entry.workflows\n ? \"runs workflows\"\n : \"no workflows\";\n return `${entry.name} (${entry.base}, ${workflows})`;\n}\n\nfunction describeAll(entries: readonly SwitchboardEntry[]): string {\n return entries.map(describe).join(\"; \");\n}\n\n/** The entry `switchboard` names: by name, then by the longest base it lies under. */\nfunction byNameOrUrl(\n entries: readonly SwitchboardEntry[],\n switchboard: string,\n): SwitchboardEntry | undefined {\n const named = entries.find((entry) => entry.name === switchboard);\n if (named) return named;\n const url = trimSlash(switchboard);\n return entries\n .filter((entry) => url === entry.base || url.startsWith(`${entry.base}/`))\n .sort((a, b) => b.base.length - a.base.length)[0];\n}\n\nfunction checkNeed(\n entry: SwitchboardEntry,\n need: SwitchboardRequest[\"need\"],\n entries: readonly SwitchboardEntry[],\n): SwitchboardEntry {\n if (need === \"workflows\" && entry.workflows === false) {\n throw new SwitchboardLookupError(\n `Switchboard ${entry.name} (${entry.base}) runs no workflow runtime.`,\n \"NO_WORKFLOW_RUNTIME\",\n entries,\n );\n }\n return entry;\n}\n\n/**\n * The switchboard a call goes to: the one named, else the one serving the\n * document, else the only one there is (or the only one running what `need`\n * asks for). Throws a {@link SwitchboardLookupError} that lists the\n * switchboards whenever it can't pick one; there is no default URL.\n */\nexport async function resolveSwitchboard(\n directory: SwitchboardDirectory | undefined,\n request: SwitchboardRequest = {},\n): Promise<SwitchboardEntry> {\n if (!directory) {\n throw new SwitchboardLookupError(\n \"This app provides no switchboard directory, so no switchboard can be picked.\",\n \"NO_DIRECTORY\",\n );\n }\n const entries = directory.list();\n const { need } = request;\n\n if (request.switchboard) {\n const named = byNameOrUrl(entries, request.switchboard);\n if (!named) {\n throw new SwitchboardLookupError(\n entries.length > 0\n ? `No switchboard \"${request.switchboard}\". This app reaches: ${describeAll(entries)}.`\n : `No switchboard \"${request.switchboard}\": this app reaches no switchboard.`,\n \"UNKNOWN_SWITCHBOARD\",\n entries,\n );\n }\n return checkNeed(named, need, entries);\n }\n\n // With one switchboard, placing the document could only name that one.\n if (request.documentId && entries.length > 1) {\n const located = await directory.locate(request.documentId, request.signal);\n if (located) return checkNeed(located, need, entries);\n }\n\n if (entries.length === 0) {\n throw new SwitchboardLookupError(\n \"This app reaches no switchboard; it is connected to none.\",\n \"NO_SWITCHBOARD\",\n );\n }\n if (entries.length === 1) return checkNeed(entries[0], need, entries);\n\n if (need === \"workflows\") {\n const running = entries.filter((entry) => entry.workflows === true);\n if (running.length === 1) return running[0];\n if (running.length === 0) {\n const maybe = entries.filter((entry) => entry.workflows === \"unknown\");\n if (maybe.length === 1) return maybe[0];\n if (maybe.length === 0) {\n throw new SwitchboardLookupError(\n `None of the switchboards runs a workflow runtime: ${describeAll(entries)}.`,\n \"NO_WORKFLOW_RUNTIME\",\n entries,\n );\n }\n }\n }\n throw new SwitchboardLookupError(\n `This app reaches several switchboards (${describeAll(entries)}); name one with \"switchboard\".`,\n \"AMBIGUOUS_SWITCHBOARD\",\n entries,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,SAAgB,YAAY,IAAiD;CAC3E,OAAO,aAAa,mBAAmB,GAAG,EAAE;AAC9C;;;;ACYA,SAAgB,kBAAoC;CAClD,OAAO,YAAY,kBAAkB,CAAC;AACxC;;;;ACbA,SAAgB,kBAId,YACA,cACA;CACA,MAAM,CAAC,UAAU,YAAY,gBAAgB,UAAU;CACvD,MAAM,sBAAsB,2BAA2B,YAAY;CAEnE,IAAI,CAAC,cAAc,CAAC,cAAc,OAAO,CAAC;CAE1C,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,uBAAuB,YAAY;CAErD,IAAI,CAAC,qBACH,MAAM,IAAI,oBAAoB,YAAY;CAG5C,IAAI,SAAS,OAAO,iBAAiB,cACnC,MAAM,IAAI,0BACR,YACA,cACA,SAAS,OAAO,YAClB;CAGF,OAAO,CAAC,UAAU,QAAQ;AAC5B;;;ACvBA,MAAM,wBAAwB,cAE5B,KAAA,CAAS;;;AAIX,SAAgB,uBAAuB,OAIpC;CACD,MAAM,EAAE,UAAU,aAAa;CAC/B,MAAM,QAAQ,cACN,CAAC,UAAU,QAAQ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