Source: http/url.js

/**
 * This file is part of SesaJsTools.
 *   Copyright 2014-2015, Association Sésamath
 *
 * SesaJsTools is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License version 3
 * as published by the Free Software Foundation.
 *
 * SesaJsTools is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with SesaJsTools (LICENCE.txt).
 * @see http://www.gnu.org/licenses/agpl.txt
 *
 *
 * Ce fichier fait partie de l'application Sésathèque, créée par l'association Sésamath.
 *
 * Sésathèque est un logiciel libre ; vous pouvez le redistribuer ou le modifier suivant
 * les termes de la GNU Affero General Public License version 3 telle que publiée par la
 * Free Software Foundation.
 * Sésathèque est distribué dans l'espoir qu'il sera utile, mais SANS AUCUNE GARANTIE,
 * sans même la garantie tacite de QUALITÉ MARCHANDE ou d'ADÉQUATION à UN BUT PARTICULIER.
 * Consultez la GNU Affero General Public License pour plus de détails.
 * Vous devez avoir reçu une copie de la GNU General Public License en même temps que Sésathèque
 * (cf LICENCE.txt et http://vvlibri.org/fr/Analyse/gnu-affero-general-public-license-v3-analyse
 * pour une explication en français)
 */

'use strict'

var tools = require('../index')

/**
 * Retourne l'url (absolue ou relative) avec slash de fin
 * @param {string} url
 * @returns {string}
 */
function addSlash (url) {
  if (typeof url === 'string') {
    if (url.length === 0 || url.substr(-1) !== '/') url += '/'
  } else {
    console.error('urlAddSlashAdd veut une string, reçu ' + typeof url)
    url = '/'
  }

  return url
}

/**
 * Ajoute des arguments à une url (avec encodeURIComponent)
 * @param {string} url
 * @param {object} params liste key:value
 * @returns {string} l'url complète
 */
function complete (url, params) {
  if (!params) return url
  if (tools.isObjectPlain(params)) {
    var args = []
    for (var key in params) {
      args.push(key + '=' + encodeURIComponent(params[key]))
    }
    if (args.length) url += (url.indexOf('?') === -1 ? '?' : '&') + args.join('&')
  }
  return url
}

/**
 * Retourne le domaine de l'url absolue passée en argument
 * @param {string} url
 * @param {boolean} [withoutPort=false]
 * @returns {Array|{index: number, input: string}|*}
 */
function getDomain (url, withoutPort) {
  if (tools.isUrlAbsolute(url)) {
    var match = withoutPort ? /^https?:\/\/([a-z0-9\-._]+)/.exec(url) : /^https?:\/\/([a-z0-9\-._]+(:[0-9]+)?)(\/|$)/.exec(url)
    return match && match[1]
  }
}

/**
 * Récupère un paramètre de l'url courante
 * Inspiré de http://stackoverflow.com/a/11582513
 * Attention, les + sont transformés en espace (RFC 1738), les %20 aussi (RFC 3986),
 * pour récupérer des + faut qu'ils soient correctement encodés en %2B
 * @param {string}  name              Le nom du paramètre
 * @param {boolean} [noPlusTransform] Passer true pour conserver les '+' dans le retour,
 *                                      sinon ils seront transformés en espace (un + devrait être encodé %2B)
 * @returns {*} Sa valeur (ou null s'il n'existait pas)
 */
function getParameter (name, noPlusTransform) {
  var regexp = new RegExp('[?|&]' + name + '=([^&#]+?)(&|#|$)')
  var param = regexp.exec(window.location.search)
  if (param) {
    var component = noPlusTransform ? param[1] : param[1].replace(/\+/g, '%20')
    param = decodeURIComponent(component)
  }
  return param
}

/**
 * Retourne l'url sans slash de fin
 * @param {string} url
 * @returns {string}
 */
function trimSlash (url) {
  if (typeof url === 'string') {
    if (url.length > 0 && url.substr(-1) === '/') url = url.substr(0, url.length - 1)
  } else {
    console.error('urlTrimSlash veut une string, reçu ' + typeof url)
    url = ''
  }

  return url
}

/**
 * Collection de fonctions pour manipuler des urls
 * @service sesajstools/utils/url
 */
module.exports = {
  addSlash: addSlash,
  complete: complete,
  getDomain: getDomain,
  getParameter: getParameter,
  trimSlash: trimSlash
}