| 1 | import type { ProjectNode } from "./types"; |
| 2 | import { sessionIdentityBaseKey } from "./sessionIdentity"; |
| 3 | |
| 4 | /** Stable row identity; topicId is only the last resort for an empty draft. */ |
| 5 | export function projectSessionIdentity(node: ProjectNode): string { |
| 6 | if (node.session?.sessionId) return sessionIdentityBaseKey(node); |
| 7 | if (node.remoteSession) { |
| 8 | const remote = node.remoteSession; |
| 9 | if (remote.sessionId) return sessionIdentityBaseKey({ session: { hostId: remote.hostId, sessionId: remote.sessionId } }); |
| 10 | return `source\u0000${remote.hostId}\u0000${remote.workspace}\u0000${remote.path || remote.name}`; |
| 11 | } |
| 12 | if (node.source) return `source\u0000${node.source.hostId || "local"}\u0000${node.source.sourceKey || `${node.source.path}\u0000${node.source.headId || ""}`}`; |
| 13 | if (node.sessionPath) return `path\u0000${node.sessionPath.trim()}`; |
| 14 | if (node.tabId) return `tab\u0000local\u0000${node.tabId}`; |
| 15 | return `topic\u0000${node.topicId || node.key}`; |
| 16 | } |
| 17 | |
| 18 | /** Only owner-verified aliases may join a source to its adopted session. */ |
| 19 | export function projectSessionKeys(node: ProjectNode): string[] { |
| 20 | return [projectSessionIdentity(node), ...(node.identityAliases ?? [])]; |
| 21 | } |
| 22 | |
| 23 | export function projectSessionExcluded(node: ProjectNode, excluded: ReadonlySet<string>): boolean { |
| 24 | return projectSessionKeys(node).some(key => excluded.has(key)) || Boolean(node.topicId && excluded.has(node.topicId)); |
| 25 | } |
| 26 | |
| 27 | /** A source keeps its mounted row key when its owner publishes canonical aliases. */ |
| 28 | const mountedRowKeys = new Map<string, string>(); |
| 29 | export function projectSessionRowKey(node: ProjectNode): string { |
| 30 | const keys = projectSessionKeys(node); |
| 31 | const existing = keys.map(key => mountedRowKeys.get(key)).find(Boolean); |
| 32 | const rowKey = existing ?? projectSessionIdentity(node); |
| 33 | for (const key of keys) mountedRowKeys.set(key, rowKey); |
| 34 | return rowKey; |
| 35 | } |
| 36 | |
| 37 | export function sameProjectSession(a: ProjectNode, b: ProjectNode): boolean { |
| 38 | const keys = new Set(projectSessionKeys(a)); |
| 39 | return projectSessionKeys(b).some(key => keys.has(key)); |
| 40 | } |
| 41 |