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

@soluble/dsn-parser

v1.9.2

Published

Utility parser for DSN

Downloads

37,068

Readme

@soluble/dsn-parser

DSN parser, validation utilities, and query string helper in a light and modern package.

npm size bundles node codecov types npm license

Install

$ npm install @soluble-dsn-parser
$ yarn add @soluble/dsn-parser
$ pnpm add @soluble/dsn-parser

Features

  • [x] Parse individual fields (ie: driver, user, password, host...)
  • [x] Handle query string with casting of boolean and numeric values.
  • [x] Handle special characters like /, :... in the password (some libs won't).
  • [x] Error with indicative message / reasons (discriminative union or throwing).
  • [x] Don't leak passwords in the error message.
  • [x] Assertion and typeguard helpers (ie: easy integrate with zod).

Quick start

parseDsnOrThrow

Usage with exceptions

import { parseDsnOrThrow } from "@soluble/dsn-parser";

const dsn = "redis://user:p@/ssword@localhost:6379/0?ssl=true";

try {
  const parsedDsn = parseDsnOrThrow(dsn);
  assert.deepEqual(parsedDsn, {
    driver: "redis",
    pass: "p@/ssword",
    host: "localhost",
    user: "user",
    port: 6379,
    db: "0",
    params: {
      ssl: true,
    },
  });
} catch (e) {
  // example:
  // e -> Error("Can't parse dsn: Invalid port: 12345678 (INVALID_PORT)")
}

parseDsn

Usage with discriminated union.

import { parseDsn } from "@soluble/dsn-parser";

const dsn = "redis://user:p@/ssword@localhost:6379/0?ssl=true";

const parsed = parseDsn(dsn);

if (parsed.success) {
  assert.deepEqual(parsed.value, {
    driver: "redis",
    pass: "p@/ssword",
    host: "localhost",
    user: "user",
    port: 6379,
    db: "0",
    params: {
      ssl: true,
    },
  });
} else {
  assert.deepEqual(parsed, {
    success: false,
    // Reasons might vary
    reason: "INVALID_PORT",
    message: "Invalid http port: 12345678",
  });
}

Options

const dsn = "mySql://localhost:6379/db";
const parsed = parseDsn(dsn, {
  lowercaseDriver: true,
  overrides: {
    db: "db3",
    port: undefined,
  },
});

assert.deepEqual(parsed.value, {
  driver: "mysql",
  host: "localhost",
  db: "db3",
});

| Params | Type | Description | | ----------------- | ---------------------- | ----------------------------------------- | | lowercaseDriver | <boolean> | Driver name in lowercase, default false | | overrides | DSN must be a string | |

Assertion

import { assertParsableDsn, ParsableDsn } from "@soluble/dsn-parser";

try {
  assertParsableDsn("redis:/");
  // Type is narrowed to string (ParsableDsn) if it
  // didn't throw.
} catch (e) {
  assert.equal(e.message, "Cannot parse DSN (PARSE_ERROR)");
}

Typeguard

import { isParsableDsn, type ParsableDsn } from "@soluble/dsn-parser";

const dsn = "postgresql://localhost:6379/db";

if (isParsableDsn(dsn)) {
  // known to be ParsableDSN
}

DSN parsing

Requirements

The minimum requirement for dsn parsing is to have a host and a driver (/[a-z0-9]+/i) defined. All other options are optional.

export type ParsedDsn = {
  driver: string;
  host: string;
  user?: string;
  pass?: string;
  port?: number;
  db?: string;
  /** Query params */
  params?: Record<string, number | string | boolean>;
};

DSN support

Things like:

const validExamples = [
  "postgresql://postgres:@localhost:5432/prisma-db",
  "redis://us_er-name:P@ass-_:?/ssw/[email protected]:6379/0?cache=true",
  //...
];

should work.

Query parameters

Simple query parameters are supported (no arrays, no nested). For convenience it will cast 'true' and 'false' to booleans, parse numeric string to numbers if possible. When a query parameter does not contain a value, it will be returned as true.

const dsn = "redis://host?index=1&compress=false&ssl";
const parsed = parseDsn(dsn);
assert.deepEqual(parsed.value.params, {
  index: 1,
  compress: false,
  ssl: true,
});

Portability

parseDsn won't make any assumptions on default values (i.e: default port for mysql...).

Validation

parseDsn wraps its result in a discriminated union to allow the retrieval of validation errors. No try... catchneeded and full typescript support.

Reason codes are guaranteed in semantic versions and messages does not leak credentials

const parsed = parseDsn("redis://localhost:65636");
assert.deepEqual(parsed, {
  success: false,
  reason: "INVALID_PORT",
  message: "Invalid port: 65636",
});
if (!parsed.success) {
  // `success: false` narrows the type to
  // {
  //   reason: 'PARSE_ERROR'|'INVALID_ARGUMENT'|...
  //   message: string
  // }
  log(parsed.reason);
}

| Reason | Message | Comment | | -------------------- | ----------------------- | --------------- | | 'PARSE_ERROR' | Cannot parse DSN | Regexp failed | | 'INVALID_ARGUMENT' | DSN must be a string | | | 'EMPTY_DSN' | DSN cannot be empty | | | 'INVALID_PORT' | Invalid port: ${port} | [1-65535] |

Faq

Zod integration example

The isParsableDsn can be easily plugged into zod custom validation. Example:

import { z } from "zod";

export const serverEnvSchema = z.object({
  PRISMA_DATABASE_URL: z.custom(
    (dsn) => isParsableDsn(dsn),
    "Invalid DSN format."
  ),
});

serverEnvSchema.parse(process.env);

Why '/' in password matters

Some libs (ioredis...) still might fail parsing a password containing '/', unfortunately they're pretty convenient, i.e:

openssl rand 60 | openssl base64 -A

# YFUXIG9INIK7dFyE9aXtxLmjmnYL0zv6YluBJJbC6alKIBema/MwEGy3VUpx0oLAvWHUFGFMagAdLxrB

Sponsors ❤️

If you are enjoying some of my OSS guides or libs for your company, I'd really appreciate a sponsorship, a coffee or a dropped star. That gives me a tasty morning boost and help me to make some of my ideas come true 🙏

Special thanks