/ utils / sessionUrl.ts
sessionUrl.ts
 1  import { randomUUID, type UUID } from 'crypto'
 2  import { validateUuid } from './uuid.js'
 3  
 4  export type ParsedSessionUrl = {
 5    sessionId: UUID
 6    ingressUrl: string | null
 7    isUrl: boolean
 8    jsonlFile: string | null
 9    isJsonlFile: boolean
10  }
11  
12  /**
13   * Parses a session resume identifier which can be either:
14   * - A URL containing session ID (e.g., https://api.example.com/v1/session_ingress/session/550e8400-e29b-41d4-a716-446655440000)
15   * - A plain session ID (UUID)
16   *
17   * @param resumeIdentifier - The URL or session ID to parse
18   * @returns Parsed session information or null if invalid
19   */
20  export function parseSessionIdentifier(
21    resumeIdentifier: string,
22  ): ParsedSessionUrl | null {
23    // Check for JSONL file path before URL parsing, since Windows absolute
24    // paths (e.g., C:\path\file.jsonl) are parsed as valid URLs with C: as protocol
25    if (resumeIdentifier.toLowerCase().endsWith('.jsonl')) {
26      return {
27        sessionId: randomUUID() as UUID,
28        ingressUrl: null,
29        isUrl: false,
30        jsonlFile: resumeIdentifier,
31        isJsonlFile: true,
32      }
33    }
34  
35    // Check if it's a plain UUID
36    if (validateUuid(resumeIdentifier)) {
37      return {
38        sessionId: resumeIdentifier as UUID,
39        ingressUrl: null,
40        isUrl: false,
41        jsonlFile: null,
42        isJsonlFile: false,
43      }
44    }
45  
46    // Check if it's a URL
47    try {
48      const url = new URL(resumeIdentifier)
49  
50      // Use the entire URL as the ingress URL
51      // Always generate a random session ID
52      return {
53        sessionId: randomUUID() as UUID,
54        ingressUrl: url.href,
55        isUrl: true,
56        jsonlFile: null,
57        isJsonlFile: false,
58      }
59    } catch {
60      // Not a valid URL
61    }
62  
63    return null
64  }