/** * @module cosmology/workspace/cosmos-url-helper * * Helpers for parsing and resolving remote Cosmos URLs and endpoints. * Supports friendly (@owner/cosmosName) and direct WebSocket API URLs. */ import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { DEFAULT_VCS_REMOTE_URL } from '../branching/branching-constants.mjs'; export interface ResolvedRemoteCosmos { /** HTTP base URL of the remote server (e.g. 'http://localhost:8080' or 'https://space-gib.com') */ baseUrl: string; /** WebSocket base URL of the remote server (e.g. 'ws://localhost:8080' or 'wss://space-gib.com') */ wsBaseUrl: string; /** Primary Keystone TJP address of the remote domain owner */ domainAddr: string; /** Owner display handle if present (e.g. '@alice') */ ownerHandle?: string; /** Name of the remote Cosmos */ cosmosName: string; /** Full WebSocket endpoint for Cosmos-level sync */ cosmosWsUrl: string; /** Dedicated read-only clone WebSocket endpoint (if senderDomainAddr is provided) */ cloneWsUrl?: string; /** Full HTTP evolve endpoint for upfront session authentication */ httpEvolveUrl: string; } export interface ResolveRemoteCosmosUrlOpts { /** * Remote URL or shorthand identifier: * - `@alice/project-x` * - `http://localhost:8080/@alice/project-x` * - `https://space-gib.com/api/sync/ws/:domainAddr/:cosmosName` */ remoteUrl: string; /** * Fallback base URL if remoteUrl is a shorthand like `@alice/project-x`. * Defaults to DEFAULT_VCS_REMOTE_URL. */ defaultBaseUrl?: string; /** * Optional custom fetch implementation (useful for testing). */ fnFetch?: typeof fetch; /** * Optional caller identity domain TJP address (Bob's domain address) for constructing clone WebSocket endpoint. */ senderDomainAddr?: string; } /** * Builds a dedicated read-only clone WebSocket endpoint URL. */ export function buildCloneWsUrl({ wsBaseUrl, senderDomainAddr, targetDomainAddr, cosmosName, galaxyName, branchName, }: { wsBaseUrl: string; senderDomainAddr: string; targetDomainAddr: string; cosmosName: string; galaxyName?: string; branchName?: string; }): string { const sender = encodeURIComponent(senderDomainAddr); const target = encodeURIComponent(targetDomainAddr); const cosmos = encodeURIComponent(cosmosName); let url = `${wsBaseUrl}/api/clone/ws/${sender}/${target}/${cosmos}`; if (galaxyName && branchName) { url += `/${encodeURIComponent(galaxyName)}/${encodeURIComponent(branchName)}`; } return url; } /** * Parses and resolves a remote Cosmos URL into structured endpoints and domain coordinates. * If an `@owner` handle is provided, queries `POST /api/keystone/lookup` on the remote server * to resolve the authoritative primary Keystone TJP address. */ export async function resolveRemoteCosmosUrl({ remoteUrl, defaultBaseUrl = DEFAULT_VCS_REMOTE_URL, fnFetch = globalThis.fetch, senderDomainAddr, }: ResolveRemoteCosmosUrlOpts): Promise { const lc = `[resolveRemoteCosmosUrl]`; const trimmed = (remoteUrl || '').trim(); if (!trimmed) { throw new Error(`${lc} remoteUrl is required (E: 81ba72c90df1428a9b1c7209384bc126)`); } let urlString = trimmed; let ownerHandle: string | undefined; let cosmosName: string | undefined; let directDomainAddr: string | undefined; let baseServerUrl: string; // 1. Shorthand handle: @owner/cosmosName if (trimmed.startsWith('@')) { const parts = trimmed.split('/'); if (parts.length !== 2 || !parts[0] || !parts[1]) { throw new Error(`Invalid shorthand remote URL '${trimmed}'. Expected format: '@owner/cosmosName' (E: d2010fea3522f6bd51b1c7146e13b1e5)`); } ownerHandle = parts[0]; cosmosName = parts[1]; baseServerUrl = defaultBaseUrl; } else { // Full URL with protocol or host let parsed: URL; try { parsed = new URL(trimmed.startsWith('http') || trimmed.startsWith('ws') ? trimmed : `https://${trimmed}`); } catch { parsed = new URL(`https://${trimmed}`); } const isSecure = parsed.protocol === 'https:' || parsed.protocol === 'wss:'; const httpScheme = isSecure ? 'https:' : 'http:'; baseServerUrl = `${httpScheme}//${parsed.host}`; // Check if path is /api/sync/ws/:domainAddr/:cosmosName const wsMatch = parsed.pathname.match(/^\/api\/sync\/ws\/([^\/]+?)(?:%5E|\^)([^\/]+)\/([^\/]+)\/?$/); if (wsMatch) { const domainIb = decodeURIComponent(wsMatch[1]); const domainGib = decodeURIComponent(wsMatch[2]); directDomainAddr = `${domainIb}^${domainGib}`; cosmosName = decodeURIComponent(wsMatch[3]); } else { // Path is /@owner/:cosmosName const handleMatch = parsed.pathname.match(/^\/(@[^\/]+)\/([^\/]+)\/?$/); if (handleMatch) { ownerHandle = decodeURIComponent(handleMatch[1]); cosmosName = decodeURIComponent(handleMatch[2]); } else { throw new Error(`Unsupported remote Cosmos URL format: '${trimmed}'. Expected 'https://host/@owner/cosmosName' or 'https://host/api/sync/ws/:domainAddr/:cosmosName' (E: 15342b2044d6543073f6f903c07866e1)`); } } } if (!cosmosName) { throw new Error(`Could not determine cosmosName from remote URL: '${trimmed}' (E: 67fe918f87486e1e35fcb28aa456d676)`); } // Resolve domainAddr: either direct from URL or via /api/keystone/lookup let domainAddr = directDomainAddr; if (!domainAddr && ownerHandle) { const username = ownerHandle.replace(/^@/, ''); const lookupUrl = `${baseServerUrl}/api/keystone/lookup`; try { const res = await fnFetch(lookupUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ identifier: username }), }); if (!res.ok) { const text = await res.text().catch(() => ''); throw new Error(`Lookup failed (${res.status}): ${text || res.statusText}`); } const data: any = await res.json(); if (!data?.tjpAddr) { throw new Error(`Lookup response missing tjpAddr for owner '${ownerHandle}'`); } domainAddr = data.tjpAddr; } catch (err) { throw new Error(`Failed to resolve owner handle '${ownerHandle}' on remote server '${baseServerUrl}': ${extractErrorMsg(err)} (E: 98c1afcd57df6b5799732f89a236ed7a)`); } } if (!domainAddr) { throw new Error(`Could not resolve primary domainAddr for remote Cosmos '${cosmosName}' (E: 2e5f224f042c72016c2bd246bb282e74)`); } // Build WS and HTTP endpoints const parsedBase = new URL(baseServerUrl); const isBaseSecure = parsedBase.protocol === 'https:'; const wsScheme = isBaseSecure ? 'wss:' : 'ws:'; const httpScheme = isBaseSecure ? 'https:' : 'http:'; const host = parsedBase.host; const wsBaseUrl = `${wsScheme}//${host}`; const domainAddrEncoded = encodeURIComponent(domainAddr); const cosmosNameEncoded = encodeURIComponent(cosmosName); const cosmosWsUrl = `${wsBaseUrl}/api/sync/ws/${domainAddrEncoded}/${cosmosNameEncoded}`; const cloneWsUrl = senderDomainAddr ? buildCloneWsUrl({ wsBaseUrl, senderDomainAddr, targetDomainAddr: domainAddr, cosmosName, }) : undefined; const httpEvolveUrl = `${httpScheme}//${host}/api/keystone/evolve/${domainAddrEncoded}`; return { baseUrl: `${httpScheme}//${host}`, wsBaseUrl, domainAddr, ownerHandle, cosmosName, cosmosWsUrl, cloneWsUrl, httpEvolveUrl, }; }