/**
 * Navigate the current document to a same- or cross-origin HTTP(S) URL.
 *
 * Invalid paths fall back to the application root so callers do not diverge on
 * error handling.
 */
export function navigateDocumentTo(path: string): void {
  try {
    const url = new URL(path, window.location.origin)
    if (url.protocol === 'http:' || url.protocol === 'https:') {
      assignDocumentLocation(url.href)
      return
    }
  } catch {
    // Fall through to the root fallback below.
  }

  assignDocumentLocation('/')
}

function assignDocumentLocation(href: string): void {
  try {
    window.location.assign(href)
  } catch {
    window.location.href = href
  }
}
