All files / kernel-browser-runtime/src/utils relay-query-string.ts

100% Statements 13/13
83.33% Branches 5/6
100% Functions 3/3
100% Lines 13/13

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 47 48 49 50 51            4x                 3x                   7x 7x 7x 2x   5x   1x 1x                     2x 1x 1x   1x    
import { Logger } from '@metamask/logger';
 
/**
 * Utilities for handling relay query strings in kernel workers.
 */
 
const logger = new Logger('relay-query-string');
 
/**
 * Creates a query string parameter for relay addresses.
 *
 * @param relays - Array of relay addresses (e.g., libp2p multiaddrs)
 * @returns Encoded query string parameter for relays
 */
export function createRelayQueryString(relays: string[]): string {
  return `relays=${encodeURIComponent(JSON.stringify(relays))}`;
}
 
/**
 * Parses relay addresses from a query string.
 *
 * @param queryString - The query string (e.g., from window.location.search)
 * @returns Array of relay addresses, or empty array if parsing fails
 */
export function parseRelayQueryString(queryString: string): string[] {
  try {
    const relaysParam = queryString.split('relays=')[1];
    if (!relaysParam) {
      return [];
    }
    return JSON.parse(decodeURIComponent(relaysParam.split('&')[0] ?? '[]'));
  } catch (error) {
    logger.error('Error parsing relays from query string:', error);
    return [];
  }
}
 
/**
 * Gets relay addresses from the current global location's query string.
 * This is intended to be used within a worker context.
 *
 * @returns Array of relay addresses from the current location
 */
export function getRelaysFromCurrentLocation(): string[] {
  if (typeof globalThis.location === 'undefined') {
    logger.warn('No location object available in current context');
    return [];
  }
  return parseRelayQueryString(globalThis.location.search);
}