npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

als-normalize-urlpath

v2.3.0

Published

Normalize and sanitize relative URL paths

Downloads

18

Readme

als-normalize-urlpath

als-normalize-urlpath is a library designed for normalizing and sanitizing URL paths in both Node.js and browser environments. It's especially useful for standardizing relative URL paths, removing unsafe characters, and ensuring URL consistency across different platforms.

Installation

Node.js

Node.js version 10 or higher is required, as the library utilizes the URL class, which is not available in older versions of Node.js.

To install als-normalize-urlpath, use npm:

npm install als-normalize-urlpath

Browser

For browser usage, include the library script in your HTML. Ensure you have a browser-compatible version of the library.

<script src="path_to_als-normalize-urlpath.js"></script>

Usage

Node.js

After installation, you can require and use the als-normalize-urlpath in your Node.js application:

const normalizeUrlPath = require('als-normalize-urlpath');

const result = normalizeUrlPath('/some/path');
console.log(result);

Browser

In the browser, the normalizeUrlPath function will be available after including the script:

const result = normalizeUrlPath('/some/path');
console.log(result);

Functionality

The normalizeUrlPath function processes and normalizes relative URL paths. It performs the following operations:

  • Input Validation: Checks if the input is a string.
  • URL Validation: Ensures that the URL is not a full URL (e.g., starting with 'http:', 'mailto:', etc.) or a special URL (e.g., 'data:', 'blob:').
  • Length Restriction: Limits the URL length to a maximum of 2000 characters.
  • Security: Removes dot segments to prevent directory traversal attacks, illustrated by transforming /../test to /test.
  • Normalization: Replaces backslashes with forward slashes and removes redundant slashes, turning \test\path into /test/path.
  • Path Formatting: Adds a leading slash if absent and removes a trailing slash if present (except for the root /).
  • Query Parsing: Parses query parameters into an object and retains the hash fragment.

Api

Syntax:

const params = {lower: false, translate: false, slug: false, trim: false};
const urlPath = 'String';
const throwError = false;
const result = normalizeUrlPath(urlPath, params, throwError);

Parameters

  • urlPath (String): The URL path to be normalized. This should be a relative URL.

  • params (Object): Parameters for normalizing

    • default: {lower:false,translate:false,slug:false,trim:false}
      • lower: Converts the pathname to lowercase, enhancing URL consistency.
      • special: Converts special symbols to dash (-)
        • Symbols: , ; ' " ? # @ & = + * % ( ) @ : ! [ ] { } | \ ^ $
      • translate: Transliterates non-English characters to their English equivalents.
      • slug: Converts spaces and other special characters to hyphens, making URLs SEO-friendly.
      • trim: Removes leading and trailing hyphens from the path.
      • encode: Encodes characters to URL-encoded
  • throwError (Boolean): throw error insted returning {pathname:null}

    • default:false

Return Value

  • Object: An object containing the following properties:
    • pathname (String): The normalized pathname of the URL.
    • query (Object): An object representing the query parameters of the URL.
    • hash (String): The hash fragment of the URL.

If the URL path is invalid or cannot be processed, the function returns an object with pathname set to null and error.

Error Handling

The function allows users to choose their preferred method of error notification. If throwError is set to true, the function will throw a descriptive error when encountering an invalid URL path. Otherwise, it will return an object with pathname as null, which should be checked in the calling code.

Examples

Basic usage:


normalizeUrlPath('/test?param=1#section') 
// {pathname:'/test',query:{ param: '1' },hash:'#section'}

normalizeUrlPath('/../test').pathname 
// '/test'

normalizeUrlPath('/test/..').pathname 
// '/'

normalizeUrlPath('\\test\\path').pathname 
// '/test/path'

normalizeUrlPath('/test//path').pathname 
// '/test/path'

normalizeUrlPath('/Test/Path',{lower:true}).pathname 
// '/test/path'

normalizeUrlPath('/test&url/some.html?k=v&k1=v1').pathname 
// '/test&url/some.html'

normalizeUrlPath('').pathname 
// '/'

normalizeUrlPath('///').pathname 
// '/'

normalizeUrlPath('/path-with-@-symbol').pathname 
// '/path-with-@-symbol'

normalizeUrlPath('/path-with-semicolon;').pathname 
// '/path-with-semicolon;'

normalizeUrlPath('/TeSt/MiXeDcAsE').pathname 
// '/TeSt/MiXeDcAsE'

normalizeUrlPath('http://example.com:8080/test').pathname // null

Normalize with params:

const params1 = {lower: true, translate: true, slug: true, trim: true}
const slug = normalizeUrlPath('Hello, World!',params1).pathname; 
// '/hello-world'

const url = 'some/url/with?query=string&unsafe=chars';
const { pathname, query } = normalizeUrlPath(url); 
// { pathname:'/some/url/with', query:{ query: 'string', unsafe: 'chars' } }

normalizeUrlPath('/test-url-', {trim: true}).pathname 
// '/test-url'

normalizeUrlPath('/test%20url',{encode:true}).pathname 
// '/test%20url'

normalizeUrlPath('/test/path with spaces',{encode:true}).pathname 
// '/test/path%20with%20spaces'

normalizeUrlPath('/привет',{encode:true}).pathname 
// '/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82'

Normalize another language:

normalizeUrlPath('Café', {translate: true}).pathname;
// '/Cafe'

normalizeUrlPath('/こんにちは',{translate: true}).pathname
// '/konnitiha

normalizeUrlPath('/안녕하세요', {translate: true}).pathname
// '/annyeonghaseyo'

normalizeUrlPath('/спасибо', {translate: true}).pathname;
// '/spasibo'