! Rewrite ROUTES and ALIASES
763594
protected function rewrite() {
		$routes=array();
		$aliases=&$this->f3->ref('ALIASES');
		$redirects=array();
		foreach($this->f3->get('ROUTES') as $old=>$data) {
			$route=current(current($data));//let's pick up any route just to get the URL name
			$name=@$route[3];//PHP 5.3 compatibility
			$new=$old;
			if (!($name && in_array($name,$this->global_aliases)
				|| isset($this->global_regex) && preg_match($this->global_regex,$old))) {
				if (isset($this->rules[$this->current][$name])) {
					$new=$this->rules[$this->current][$name];
					if ($new===FALSE) {
						if (isset($aliases[$name]))
							unset($aliases[$name]);
						continue;
					}
				}
				$new=rtrim('/'.$this->current.($new),'/');
				if ($this->migrate && $this->auto) {
					$redir=$old;
					if (isset($this->rules[$this->primary][$name]))
						$redir=$this->rules[$this->primary][$name];
					if ($redir!==FALSE)
						$redirects[$old]=rtrim('/'.$this->primary.($redir),'/');
				}
			}
			if (isset($routes[$new]) && $this->strict)
				user_error(sprintf(self::E_Duplicate,$new),E_USER_ERROR);
			$routes[$new]=$data;
			if (isset($aliases[$name]))
				$aliases[$name]=$new;
		}
		$this->f3->set('ROUTES',$routes);
		foreach($redirects as $old=>$new)
			$this->f3->route('GET '.$old,function($f3)use($new){$f3->reroute($new,TRUE);});
	}
1212831
public function formatRouteNameAndViewPathModifiers()
    {
        if ($this->alias) {
            $this->alias = str_finish($this->alias, '.');
        }

        if ($this->theme) {
            $this->theme = str_finish($this->theme, '.');
        }

        if ($this->prefix) {
            $this->prefix = str_finish($this->prefix, '.');
        }

        if ($this->module) {
            if (!ends_with($this->module, '::')) {
                $this->module .= '::';
            }
        }
    }
1067914
function redirect($to) {

    if ($this->performed) {
      throw new Trails_DoubleRenderError();
    }

    $this->performed = TRUE;

    # get uri; keep absolute URIs
    $url = preg_match('#^(/|\w+://)#', $to)
           ? $to
           : $this->url_for($to);

    $this->response->add_header('Location', $url)->set_status(302);
  }
1273038
static function substituteUrlArgTokens($route)
	{	
		$orig = $route;
		$tokens = [];
		// look for things like this {id} and like this {id?},
		// optionally preceeded by a forward slash
		while(preg_match('#/?({([\w\_]+)\??})#i', $route, $matches)) {
			// get the argument name:
			$arg = $matches[2];
			$tokens[] = $arg;
			// capture what we're going to replace 
			$subject = $matches[0];
			// make the replacement, e.g., (?P<id>[a-z\-\_]+)
			$replacement = '(?P<'.$arg.'>[^/]+)';
			// if the original arg was preceeded by a forward slash, we need to put it back
			if (stripos($subject, '/') === 0) {
				$replacement = '/' . $replacement;
			}
			// if the original arg has a ?, then we need to wrap our new token in the same
			if (stripos($subject, '?') !== false) {
				$replacement = '('.$replacement.')?';
			}
			// make the substitution
			$route = str_replace($subject, $replacement, $route);
		}
		
		return [ $route, $tokens ];
	}
145969
private static function format() {

		$routes = static :: getRoutes();

		foreach($routes as $identifier => $route) {

			$url = preg_quote($route -> getUrl(), '/'); 

			//Prepend prefix for url
			if($prefix = $route -> getPrefix()) {
				$url = $prefix['url'] . $url;
			}

			if(preg_match_all('#(\\\/)*\\\{([a-zA-Z0-9_.]+)(\\\\\?)?\\\}#i', $url, $matches)) {
				
				foreach($matches[0] as $index => $match) {

					$match 		= $matches[0][$index];
					$slash 		= $matches[1][$index];
					$type 		= $matches[2][$index];
					$optional 	= $matches[3][$index];
					$where 		= $route -> getWhere();
					$variable 	= '';
					$typefound 	= false;

					if('' !== $slash) {
						$variable .= '\/';
					}

					if(true === is_array($where)) {
						
						foreach($where as $key => $regex) {
							
							if($key === $type) {
								
								$variable .= $regex;
								$typefound = true;
								break;
							}
						}
					}

					if(false === $typefound) {

						if(isset(static :: $types[$type])) {
							$variable .= static :: $types[$type];
						}
						else {
							$variable .= static :: $types['string'];	
						}
					}

					if('' !== $optional) {
						$variable = '('. $variable .')?';
					}
					else {
						$variable = '('. $variable .')';
					}
					
					$url = preg_replace('#' . preg_quote($match, '/') . '#', $variable, $url, 1);
				}
			}

			$route -> setMatch($url);
		}
	}
941574
function routeIsActive(pathname, routes, params, indexOnly) {
  // TODO: This is a bit ugly. It keeps around support for treating pathnames
  // without preceding slashes as absolute paths, but possibly also works
  // around the same quirks with basenames as in matchRoutes.
  if (pathname.charAt(0) !== '/') {
    pathname = `/${pathname}`
  }

  const i = getMatchingRouteIndex(pathname, routes, params)

  if (i === null) {
    // No match.
    return false
  } else if (!indexOnly) {
    // Any match is good enough.
    return true
  }

  // If any remaining routes past the match index have paths, then we can't
  // be on the index route.
  return routes.slice(i + 1).every(route => !route.path)
}
1092803
function reroute($url=NULL,$permanent=FALSE,$die=TRUE) {
		if (!$url)
			$url=$this->hive['REALM'];
		if (is_array($url))
			$url=call_user_func_array([$this,'alias'],$url);
		elseif (preg_match('/^(?:@?([^\/()?]+)(?:(\(.+?)\))*(\?.+)*)/',
			$url,$parts) &&
			isset($this->hive['ALIASES'][$parts[1]]))
			$url=$this->hive['ALIASES'][$parts[1]];
		$url=$this->build($url,isset($parts[2])?$this->parse($parts[2]):[]).
			(isset($parts[3])?$parts[3]:'');
		if (($handler=$this->hive['ONREROUTE']) &&
			$this->call($handler,[$url,$permanent,$die])!==FALSE)
			return;
		if ($url[0]!='/' && !preg_match('/^\w+:\/\//i',$url))
			$url='/'.$url;
		if ($url[0]=='/' && (empty($url[1]) || $url[1]!='/')) {
			$port=$this->hive['PORT'];
			$port=in_array($port,[80,443])?'':(':'.$port);
			$url=$this->hive['SCHEME'].'://'.
				$this->hive['HOST'].$port.$this->hive['BASE'].$url;
		}
		if ($this->hive['CLI'])
			$this->mock('GET '.$url.' [cli]');
		else {
			header('Location: '.$url);
			$this->status($permanent?301:302);
			if ($die)
				die;
		}
	}
399618
function rerouteLinks (html) {
  return html.replace(/href="(\.\/[a-z0-9\-]+\.md)"/g, (all, key) => {
    const found = documentationPages.filter((page) => page.key === key)[0]
    if (!found) return all
    /* global __legendary_pancake_base_pathname__ */
    const base = __legendary_pancake_base_pathname__ // eslint-disable-line camelcase
    const pathname = found.pathname
    return `href="${base}${pathname}" data-to="${pathname}"`
  })
}
674587
function generate_routes(dir_name, controller, routes) {
	let route_def = cli.cat(dir_name + '/config/routes.js');
	let lines = [], line;
	let method, path, action;

	routes.forEach((route) => {
		// set parameters
		method = route.method; path = route.path;
		controller = route.controller; action = route.action;
		// create and add line
		line = `		this.${method}('${path}', '${controller}#${action}');`;
		lines.push(line);
	});
	// add lines to config file
	route_def = route_def.replace(/use\s?\(\)\s?{/, `use() {
${lines.join('\n')}${route_def.match(/use\s?\(\)\s?{\s*}/) ? '' : '\n'}`);
	fs.writeFileSync(dir_name + '/config/routes.js', route_def);
}
991505
protected function addAliasRoutes($aliasRoutes)
    {
        $aliasRoutes = (array) $aliasRoutes;
        foreach ($aliasRoutes as $aliasRoute)
        {
            $aliasRoute = (string) $aliasRoute;
            $this->aliasRouteNames[$aliasRoute] = $aliasRoute;
        }

        return $this;
    }
383476
def render_path_alias(path):
    

    redir = path_alias.get_redirect('/' + path)
    if not redir:
        raise http_error.NotFound("Path redirection not found")
    return redir
369594
private static function cleanUrls()
    {
        foreach (static::$register as $route) {
            $route->url = static::cleanUrl($route->url);
        }

        foreach (static::$register as $route) {
            if (str_contains($route->url, '{}')) {
                $route->url = str_replace('{}', '(.*)?', $route->url);
            }
        }
    }
1039653
function replaceWith(to, params, query) {
        location.replace(Router.makePath(to, params, query));
      }
1051987
function remove_routes(dir_name, controller) {
	let route_def = cli.cat(dir_name + '/config/routes.js');
	let lines = route_def.split('\n');
	let new_lines = [], match;
	lines.forEach((line, index) => {
		match = line.match(new RegExp(`${controller}#.+('|")`));
		if (!match) {
			new_lines.push(line);
		}
	});
	// add lines to config file
	fs.writeFileSync(dir_name + '/config/routes.js', new_lines.join('\n'));
}
767559
function navigate(path, replace){
    if (replace)
      location.replace(location.pathname + '#' + path);
    else
      location.hash = path;

    if (started)
      checkUrl();
  }
556985
function route($pattern,$handler,$ttl=0,$kbps=0) {
		$types=['sync','ajax','cli'];
		$alias=null;
		if (is_array($pattern)) {
			foreach ($pattern as $item)
				$this->route($item,$handler,$ttl,$kbps);
			return;
		}
		preg_match('/([\|\w]+)\h+(?:(?:@?(.+?)\h*:\h*)?(@(\w+)|[^\h]+))'.
			'(?:\h+\[('.implode('|',$types).')\])?/u',$pattern,$parts);
		if (isset($parts[2]) && $parts[2])
			$this->hive['ALIASES'][$alias=$parts[2]]=$parts[3];
		elseif (!empty($parts[4])) {
			if (empty($this->hive['ALIASES'][$parts[4]]))
				user_error(sprintf(self::E_Named,$parts[4]),E_USER_ERROR);
			$parts[3]=$this->hive['ALIASES'][$alias=$parts[4]];
		}
		if (empty($parts[3]))
			user_error(sprintf(self::E_Pattern,$pattern),E_USER_ERROR);
		$type=empty($parts[5])?0:constant('self::REQ_'.strtoupper($parts[5]));
		foreach ($this->split($parts[1]) as $verb) {
			if (!preg_match('/'.self::VERBS.'/',$verb))
				$this->error(501,$verb.' '.$this->hive['URI']);
			$this->hive['ROUTES'][$parts[3]][$type][strtoupper($verb)]=
				[$handler,$ttl,$kbps,$alias];
		}
	}
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
}