const addressbar = require('addressbar') const urlMapper = require('url-mapper') TODO: inyeccion de datos con router, esto seria genial: estado -> router -> app , elimina los globales!!!
487311
function route({path, module, props, childRoutes}) {
  let urlPath = ''
  let childs = {}

  for (let i = 0, childRoute, moduleTemp; childRoute = childRoutes[i]; i++) {
    childs[childRoute.path] = childRoute.module
  }

  let routerDef = F.def({
    init: ({key}) => ({
      childName: '/',
      childStates:  R.mapObjIndexed((child, name) => child.init({key: name}), childs),
      ...module.init({key}),
    }),
    inputs: {
      changeChild: (ctx, Action, name) => Action.ChangeChild(name),
      childAction: (ctx, Action, name, a) => Action.ChildAction(name, a),
      ...module.inputs,
    },
    load: (ctx, i, Action) => {
      return {
        childModules: R.mapObjIndexed((child, name) => F.createContext(child, {action$: i.childAction(name)}), childs),
        ...module.load(ctx, i, Action),
      }
    },
    actions: {
      ChangeChild: [[String], (name, m) => R.evolve({childName: R.always(name)}, m)],
      ChildAction: [[String, Array], (name, a, m) => R.evolve({childStates: R.evolve({[name]: childs[name].update(a)})}, m)],
      ...module.actions,
    },
    interfaces: {
      view: (ctx, i, m) => module.interfaces.view(ctx, i, m),
      router: (ctx, i, m) => ({
        routeChange: function(path) {
          i.changeChild(path)
        }
      }),
    },
  })
  return routerDef
}
880012
function koifyRouter(Router) {
	// router factory function is the prototype
	let routerPrototype = Router;

	// original router methods
	let routerPrototype_ = {};

	// router duck testing
	let routerMethods = Object.keys(routerPrototype).sort();

	function isRouter(someRouter) {
		let someRouterPrototype = Object.getPrototypeOf(someRouter);
		let someRouterMethods = Object.keys(someRouterPrototype).sort();

		return arrayEqual(someRouterMethods, routerMethods) && (typeof someRouterPrototype === 'function');
	}

	routerPrototype_.use = routerPrototype.use;
	routerPrototype.use = function () {
		let args = slice.call(arguments);

		for (let i = 0; i < args.length; i++) {
			let handler = args[i];

			// don't wrap router instances
			if (isFunction(handler) && !isRouter(handler)) {
				args[i] = ko.ko(handler);
			}
		}

		return routerPrototype_.use.apply(this, args);
	};

	routerPrototype_.param = routerPrototype.param;
	routerPrototype.param = function () {
		let args = slice.call(arguments);

		let handler = args[1];

		if (isFunction(handler)) {
			// additional argument to indicate param handler
			args[1] = ko.ko(handler, true);
		}

		return routerPrototype_.param.apply(this, args);
	};

	// safeguard
	Object.defineProperty(routerPrototype, '$$koified', {
		configurable: true,
		writable: true,
		value: false
	});

	return Router;
}
1057366
function createConnect() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$connectHOC = _ref.connectHOC,
      connectHOC = _ref$connectHOC === undefined ? __WEBPACK_IMPORTED_MODULE_0__components_connectAdvanced__["a" /* default */] : _ref$connectHOC,
      _ref$mapStateToPropsF = _ref.mapStateToPropsFactories,
      mapStateToPropsFactories = _ref$mapStateToPropsF === undefined ? __WEBPACK_IMPORTED_MODULE_3__mapStateToProps__["a" /* default */] : _ref$mapStateToPropsF,
      _ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories,
      mapDispatchToPropsFactories = _ref$mapDispatchToPro === undefined ? __WEBPACK_IMPORTED_MODULE_2__mapDispatchToProps__["a" /* default */] : _ref$mapDispatchToPro,
      _ref$mergePropsFactor = _ref.mergePropsFactories,
      mergePropsFactories = _ref$mergePropsFactor === undefined ? __WEBPACK_IMPORTED_MODULE_4__mergeProps__["a" /* default */] : _ref$mergePropsFactor,
      _ref$selectorFactory = _ref.selectorFactory,
      selectorFactory = _ref$selectorFactory === undefined ? __WEBPACK_IMPORTED_MODULE_5__selectorFactory__["a" /* default */] : _ref$selectorFactory;

  return function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
    var _ref2 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
        _ref2$pure = _ref2.pure,
        pure = _ref2$pure === undefined ? true : _ref2$pure,
        _ref2$areStatesEqual = _ref2.areStatesEqual,
        areStatesEqual = _ref2$areStatesEqual === undefined ? strictEqual : _ref2$areStatesEqual,
        _ref2$areOwnPropsEqua = _ref2.areOwnPropsEqual,
        areOwnPropsEqual = _ref2$areOwnPropsEqua === undefined ? __WEBPACK_IMPORTED_MODULE_1__utils_shallowEqual__["a" /* default */] : _ref2$areOwnPropsEqua,
        _ref2$areStatePropsEq = _ref2.areStatePropsEqual,
        areStatePropsEqual = _ref2$areStatePropsEq === undefined ? __WEBPACK_IMPORTED_MODULE_1__utils_shallowEqual__["a" /* default */] : _ref2$areStatePropsEq,
        _ref2$areMergedPropsE = _ref2.areMergedPropsEqual,
        areMergedPropsEqual = _ref2$areMergedPropsE === undefined ? __WEBPACK_IMPORTED_MODULE_1__utils_shallowEqual__["a" /* default */] : _ref2$areMergedPropsE,
        extraOptions = _objectWithoutProperties(_ref2, ['pure', 'areStatesEqual', 'areOwnPropsEqual', 'areStatePropsEqual', 'areMergedPropsEqual']);

    var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps');
    var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps');
    var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps');

    return connectHOC(selectorFactory, _extends({
      // used in error messages
      methodName: 'connect',

      // used to compute Connect's displayName from the wrapped component's displayName.
      getDisplayName: function getDisplayName(name) {
        return 'Connect(' + name + ')';
      },

      // if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes
      shouldHandleStateChanges: Boolean(mapStateToProps),

      // passed through to selectorFactory
      initMapStateToProps: initMapStateToProps,
      initMapDispatchToProps: initMapDispatchToProps,
      initMergeProps: initMergeProps,
      pure: pure,
      areStatesEqual: areStatesEqual,
      areOwnPropsEqual: areOwnPropsEqual,
      areStatePropsEqual: areStatePropsEqual,
      areMergedPropsEqual: areMergedPropsEqual

    }, extraOptions));
  };
}
291550
function createRouter() {
  var rtr = express.Router.apply(express, arguments);
  router.patch(rtr);
  return rtr;
}
1055181
function createDitcherInstance(mongoUrl, callback) {
  // Default config used by ditcher if no connection string
  // is provided
  var config = {
    database: {
      host: process.env.MONGODB_HOST || '127.0.0.1',
      port: process.env.FH_LOCAL_DB_PORT || 27017,
      name: 'FH_LOCAL'
    }
  };

  if (mongoUrl) {
    try {
      config = utils.parseMongoConnectionURL(mongoUrl);
    } catch(e) {
      return callback(e);
    }
  }

  var versString = (mongoUrl) ? "db per app" : "shared db";
  var ditcher = new fhditcher.Ditcher(config, logger, versString, function () {
    return callback(null, ditcher);
  });
}
1016017
function Router(options) {
  options = options || {};
  var self = this;
  this.map = {};
  this.params = {};
  this._params = [];
  this.caseSensitive = options.caseSensitive;
  this.strict = options.strict;
  this.middleware = function router(req, res, next){
    self._dispatch(req, res, next);
  };
}
417119
function Router(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config) {
        var _this = this;
        this.rootComponentType = rootComponentType;
        this.urlSerializer = urlSerializer;
        this.rootContexts = rootContexts;
        this.location = location;
        this.config = config;
        this.navigations = new rxjs__WEBPACK_IMPORTED_MODULE_2__["BehaviorSubject"](null);
        this.navigationId = 0;
        this.isNgZoneEnabled = false;
        this.events = new rxjs__WEBPACK_IMPORTED_MODULE_2__["Subject"]();
        /**
         * Error handler that is invoked when a navigation errors.
         *
         * See `ErrorHandler` for more information.
         */
        this.errorHandler = defaultErrorHandler;
        /**
         * Malformed uri error handler is invoked when `Router.parseUrl(url)` throws an
         * error due to containing an invalid character. The most common case would be a `%` sign
         * that's not encoded and is not part of a percent encoded sequence.
         */
        this.malformedUriErrorHandler = defaultMalformedUriErrorHandler;
        /**
         * Indicates if at least one navigation happened.
         */
        this.navigated = false;
        this.lastSuccessfulId = -1;
        /**
         * Used by RouterModule. This allows us to
         * pause the navigation either before preactivation or after it.
         * @internal
         */
        this.hooks = {
            beforePreactivation: defaultRouterHook,
            afterPreactivation: defaultRouterHook
        };
        /**
         * Extracts and merges URLs. Used for AngularJS to Angular migrations.
         */
        this.urlHandlingStrategy = new DefaultUrlHandlingStrategy();
        this.routeReuseStrategy = new DefaultRouteReuseStrategy();
        /**
         * Define what the router should do if it receives a navigation request to the current URL.
         * By default, the router will ignore this navigation. However, this prevents features such
         * as a "refresh" button. Use this option to configure the behavior when navigating to the
         * current URL. Default is 'ignore'.
         */
        this.onSameUrlNavigation = 'ignore';
        /**
         * Defines how the router merges params, data and resolved data from parent to child
         * routes. Available options are:
         *
         * - `'emptyOnly'`, the default, only inherits parent params for path-less or component-less
         *   routes.
         * - `'always'`, enables unconditional inheritance of parent params.
         */
        this.paramsInheritanceStrategy = 'emptyOnly';
        /**
         * Defines when the router updates the browser URL. The default behavior is to update after
         * successful navigation. However, some applications may prefer a mode where the URL gets
         * updated at the beginning of navigation. The most common use case would be updating the
         * URL early so if navigation fails, you can show an error message with the URL that failed.
         * Available options are:
         *
         * - `'deferred'`, the default, updates the browser URL after navigation has finished.
         * - `'eager'`, updates browser URL at the beginning of navigation.
         */
        this.urlUpdateStrategy = 'deferred';
        /**
         * See {@link RouterModule} for more information.
         */
        this.relativeLinkResolution = 'legacy';
        var onLoadStart = function (r) { return _this.triggerEvent(new RouteConfigLoadStart(r)); };
        var onLoadEnd = function (r) { return _this.triggerEvent(new RouteConfigLoadEnd(r)); };
        this.ngModule = injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModuleRef"]);
        this.console = injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵConsole"]);
        var ngZone = injector.get(_angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"]);
        this.isNgZoneEnabled = ngZone instanceof _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgZone"];
        this.resetConfig(config);
        this.currentUrlTree = createEmptyUrlTree();
        this.rawUrlTree = this.currentUrlTree;
        this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd);
        this.routerState = createEmptyState(this.currentUrlTree, this.rootComponentType);
        this.processNavigations();
    }
1185119
function routeMatch(route, url) {
  const matcher = `^${route.replace(/(:\w+)/g, '([\\w-]+)')}$`
  return url.match(matcher)
}
720827
function buildRequest(args) {
  const { browser, method } = args;
  const params  = args.params || new Map();
  const site    = /^(https?:|file:)/i.test(browser.site) ? browser.site : `http://${browser.site || 'locahost'}`;
  const url     = URL.resolve(site, URL.format(args.url));

  const headers = new Fetch.Headers(args.headers);

  // HTTP header Referer, but Document property referrer
  const referrer = args.referrer || browser.referrer || browser.referer || args.history.url;
  if (referrer && !headers.has('Referer'))
    headers.set('Referer', referrer);
  if (!headers.has('Accept'))
    headers.set('Accept', 'text/html,*/*');

  if (/^GET|HEAD|DELETE$/i.test(method)) {
    const uri = URL.parse(url, true);
    // These methods use query string parameters instead
    for (let [name, values] of params)
      uri.query[name] = values;
    return new Fetch.Request(URL.format(uri), { method, headers });
  }

  const mimeType = (args.encoding || '').split(';')[0].toLowerCase();
  // Default mime type, but can also be specified in form encoding
  if (mimeType === '' || mimeType === 'application/x-www-form-urlencoded') {
    const urlEncoded = [...params]
      .map(function([name, values]) {
        return values.map(value => `${QS.escape(name)}=${QS.escape(value)}`).join('&');
      })
      .join('&');

    headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
    return new Fetch.Request(url, { method, headers, body: urlEncoded });
  }

  if (mimeType === 'multipart/form-data') {
    const form = new Fetch.FormData();
    for (let [name, values] of params)
      for (let value of values)
        form.append(name, value);
    return new Fetch.Request(url, { method, headers, body: form });
  }

  throw new TypeError(`Unsupported content type ${mimeType}`);
}
1197997
function callee(method, href, params, opt, cb, userData){
		cb = cb || ((err)=>{
			if (err) console.error(method, href, params, opt, userData, err)
		})
		if (!href) return cb('url not defined')
		opt=opt||{}

		const urlobj = url.parse(href)
		let protocol

		switch(urlobj.protocol){
		case 'http:': protocol=http; break
		case 'https:': protocol=https; break
		default:
			if (opt.socketPath){
				protocol=http
				urlobj.protocol = 'http:'
				urlobj.socketPath = opt.socketPath
				break
			}
			fs.readFile(href, 'utf8', (err, data)=>{
				cb(err, 4, data, userData)
			}); return
		}

		const isGet = 'GET' === (urlobj.method = method.toUpperCase())
		let body = Array.isArray(params) ? pObj.extends({}, params, {tidy:1, mergeArr:1}) : params || ''

		if (isGet){
			urlobj.path += body ? '?' + qs.stringify(body) : body
			urlobj.headers = opt.headers||{}
		}else{
			urlobj.headers = Object.assign({
				'Content-Type': 'application/x-www-form-urlencoded'
			},opt.headers||{})
			switch(urlobj.headers['Content-Type']){
			case 'application/json': body = JSON.stringify(body); break
			case 'plain/text': body = body.toString(); break
			default: body = qs.stringify(body); break
			}
		}

		const req = protocol.request(urlobj, res => {
			const st=res.statusCode
			const loc=res.headers.location
			if (st>=300 && st<400 && loc) return callee(method,loc,params,opt,cb,userData)
			res.setEncoding('utf8')
			const err=(300>st || !st) ? null : {error:res.statusMessage,code:st,params:arguments}
			cb(err, 2, null, userData)
			let data = ''
			res.on('data', (chunk)=>{
				data += chunk
				cb(err, 3, data, userData)
			})
			res.on('end', ()=>{
				cb(err, 4, data, userData)
			})
		})

		req.setTimeout(opt.timeout||0, err => {
			cb({error:err.message,code:599,src:err,params:arguments}, 4, null, userData)
		})
		req.on('error', err => {
			cb({error:err.message,code:500,src:err,params:arguments}, 4, null, userData)
		})

		if (isGet) req.end()
		else req.end(body)
		return req
	}
689796
function UrlNode(data){
    this.append = function(next){
        this.next = next;
    };
    this.getData = function(){
        return this.data;
    };
    this.setData = function(data){
        this.data = data;
    }
    this.getNext = function(){
        return this.next;
    };
    this.setParams = function(params){
        var queryParameters = params.split("&");
        if(queryParameters != null){
            this.params = [];
            for(var counter = 0; counter < queryParameters.length; counter++) {
                var keyValuePair = queryParameters[counter].split("=");
                this.params[keyValuePair[0]] = keyValuePair[1];
            }
        } else{
            queryParameters = null;
        }
    };
    this.getParams = function(){
        return this.params;
    };

    //set var's for this object
    var queryParamSplit = data.split("?");
    this.params = null;
    this.data = null;
    this.next = null;
    if(queryParamSplit != null && queryParamSplit.length > 1){
        this.setData(queryParamSplit[0]);
        this.setParams(queryParamSplit[1]);
    } else{
        this.setData(data);
    }
}
1202383
function(router, pathname, handler, msg_, preMsg, msg2) {

const msg = (msg2 && ` ${msg2}`) || (msg_ && `@${msg_}`) || '';

if (msg) {
  console.log(`${pad(preMsg, 35)} ${lpad(pathname,55)} ${msg}`);
}

  router.addRoute(pathname, function(req, res, params) {

    if (getDumpReqVerbosity() > 0) {
      dumpReq(req, res, `--------vvvvv\n${msg2} handling`, {skipBody:true, verbosity:getDumpReqVerbosity(), postMsg: '------^^^^^'});
    }

    return handler.apply(this, arguments);
  });
}
71072
function getServerHandler(basePath, adapter) {
    basePath = basePath || '/';
    if (basePath.length > 0 && basePath[basePath.length - 1] === '/') {
        basePath = basePath.substring(0, basePath.length - 2);
    }
    return function(req, res, next) {
        return teleport.Promise.resolve().then(function() {
            var params = req.params = req.params || {};
            var path = params.path || params['0'] || '';
            if (path[0] !== '/') {
                path = '/' + path;
            }
            path = basePath + path;
            var query = req.query || {};
            var headers = req.headers || {};
            var data = req.data || req.body || {};
            var overrideKey = 'X-HTTP-Method-Override';
            var method = //
            headers[overrideKey] || query[overrideKey] || //
            req.method || 'get';
            delete query[overrideKey];
            method = method.toLowerCase();
            var options = {
                path : path,
                method : method,
                params : params,
                query : query,
                headers : headers,
                data : data
            };
            return adapter.handle(options);
        }).then(function(result) {
            result = result || {};
            var headers = result.headers || {};
            res.set(headers);
            res.send(result.data || {});
        }, function(err) {
            res.status(500).send({
                error : err.stack,
                params : req.params
            });
        });
    }
}
947311
function Router(options) {
  if ( !(this instanceof Router) ) {
    return new Router(options);
  }
  options = options || {};
  var self = this;
  this.routes = [];
  this.caseSensitive = options.caseSensitive;
  this.strict = options.strict;
  this.connect = connect();
  this.middleware = function (req, res, next){
    dispatch(self, req, res, next);
  };
  this.eventHandlers = {
    404 : function(req, res){
      res.writeHead(404);
      res.end('Not found');
    },
    405 : function(req, res, resource){
      res.setHeader('Allow', allowHeader(self, resource));
      res.writeHead(405);
      res.end('Not allowed');
    },
    'HEAD' : function(req, res, resource){
      if (!resource.GET){
        return self.eventHandlers[405](req, res, resource);
      }
      // node server suppresses the response output
      // on a HEAD response so we don't need to mute it like this:
      /*

      var origResWrite = res.write;
      var origResEnd = res.end;

      res.write = function(){
        origResWrite.apply(res, ['']);
      };
      res.end = function(){
        console.log("in muted end()");
        origResEnd.apply(res, ['']);
      };
      */
      // re-distpach as a GET
      req.method = "GET";
      return dispatch(self, req, res, function(){});
    },
    'OPTIONS' : function(req, res, resource){
      var header = allowHeader(self, resource);
      res.setHeader('Allow', header);
      res.writeHead(200);
      res.end('Allow: ' + header);
    }
  };
  // we never tackle 501, because the node server just drops requests
  // with invalid methods
}
326485
function parseRepoURL(inputUrl) {
  if (!inputUrl) {
    throw new ServerlessError('URL is required');
  }

  const url = URL.parse(inputUrl.replace(/\/$/, ''));

  // check if url parameter is a valid url
  if (!url.host) {
    throw new ServerlessError('The URL you passed is not a valid URL');
  }

  switch (url.hostname) {
    case 'github.com': {
      return parseGitHubURL(url);
    }
    case 'bitbucket.org': {
      return parseBitbucketURL(url);
    }
    case 'gitlab.com': {
      return parseGitlabURL(url);
    }
    default: {
      const msg =
        'The URL you passed is not one of the valid providers: "GitHub", "Bitbucket", or "GitLab".';
      throw new ServerlessError(msg);
    }
  }
}
1034634
function buildRoutes(router, apiOrBuilder) {
    // if it's a builder function, build it...
    let pathPrefix = null;
    let api = null;
    let registry = null;
    let instanceName = null;
    if (_.isObject(apiOrBuilder)) {
        pathPrefix = apiOrBuilder.path;
        api = apiOrBuilder.api;
        registry = apiOrBuilder.registry;
        instanceName = apiOrBuilder.instanceName;
    } else {
        api = apiOrBuilder;
    }

    if (_.isFunction(api)) {
        api = api();
    }

    if (!registry && _.isFunction(api.registry)) {
        registry = api.registry();
    }

    if (!registry) {
        // print errors here
        return;
    }

    _.forEach(registry, (value, key) => {
        if (_.isArray(value)) {
            _.forEach(value, item => buildRoute(router, api, key, item, pathPrefix, instanceName));
        } else {
            buildRoute(router, api, key, value, pathPrefix, instanceName);
        }
    });
}
1233492
function makeRouter() {

    // Solving arguments
    var args = [].slice.call(arguments);

    var beforeMiddlewares = args.slice(0, -1),
        routes = args[args.length - 1];

    var router = express.Router();

    routes.forEach(function(route) {
      if (!route.url)
        throw Error('dolman.router: one route has no url: ' + util.inspect(route));

      if (!route.action)
        throw Error('dolman.router: the route for url ' + route.url + ' has no action.');

      var actions = [].concat(route.action);

      // Storing the route
      routesMap.set(actions[0], route);

      // Applying before middlewares
      var routeMiddlewares = beforeMiddlewares.slice();

      // Validation
      if (route.validate)
        routeMiddlewares.push(middlewares.validate(types, route.validate));

      // Mask
      if (route.mask)
        routeMiddlewares.push(middlewares.mask(route.mask));

      // RAM cache
      if (route.cache)
        routeMiddlewares.push(middlewares.cache(cache, route.cache));

      // HTTP cache
      if (route.httpCache)
        routeMiddlewares.push(middlewares.httpCache(route.httpCache));

      // Determining the method
      var methods = [].concat(route.method || route.methods || 'ALL');

      methods.forEach(function(method) {
        router[method.toLowerCase()].apply(
          router,
          [route.url]
            .concat(routeMiddlewares)
            .concat(actions)
        );
      });
    });

    return router;
  }