All files / src/core/routing socket-parser.ts

100% Statements 8/8
100% Branches 2/2
100% Functions 1/1
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                                                      11x 11x 11x 3x     8x 8x 8x   8x                
/**
 * Socket file parser
 * Core logic - no Vite dependencies
 */
 
import * as path from 'path';
import { SOCKET_FILE_PATTERN } from '../../shared/constants.js';
import { normalizeRoutePath, extractParamsFromPattern, patternToRegex } from '../normalize/normalize-path.js';
 
/**
 * Result of parsing a socket file
 */
export interface ParsedSocket {
  pattern: string;
  params: string[];
  file: string;
}
 
/**
 * Extracts socket information from a file path
 *
 * Examples:
 * - src/api/chat.socket.ts -> { pattern: 'chat', params: [], file }
 * - src/api/index.socket.ts -> { pattern: '', params: [], file }
 * - src/api/rooms/[id].socket.ts -> { pattern: 'rooms/:id', params: ['id'], file }
 */
export function parseSocketFile(filePath: string, baseDir: string): ParsedSocket | null {
  const relativePath = path.relative(baseDir, filePath).replace(/\\/g, '/');
  const match = relativePath.match(SOCKET_FILE_PATTERN);
  if (!match) {
    return null;
  }
 
  const [, pathPart] = match;
  const pattern = normalizeRoutePath(pathPart);
  const params = extractParamsFromPattern(pattern);
 
  return {
    pattern,
    params,
    file: filePath,
  };
}
 
export { patternToRegex };