1.8.5 • Published 8 months ago

@httpx/dsn-parser v1.8.5

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

@httpx/dsn-parser

DSN & JDBC string parser with query params support in a light (~750B) and modern package.

npm changelog codecov bundles node browserslist size downloads license

Install

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

Features

  • šŸ‘‰Ā  Parse individual fields (ie: driver, user, password, host...)
  • šŸ––Ā  Handle query string parameters and converts to boolean and numeric values.
  • šŸ¦„Ā  Handle special characters like /, :... in the password (some libs won't).
  • šŸš€Ā  Error with indicative message / reasons (discriminated union or throwable).
  • šŸ›”ļøĀ  Don't leak passwords in the error message.
  • šŸ™Ā  Assertion and typeguard helpers
  • šŸ¤—Ā  Ecosystem friendly (ie: zod integration).

Documentation

šŸ‘‰ Official website or Github Readme

Usage

parseDsnOrThrow

Usage with exceptions

import { parseDsnOrThrow } from "@httpx/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 "@httpx/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

import { parseDsn, type ParseDsnOptions } from "@httpx/dsn-parser";

const dsn = "mySql://localhost:6379/db";
const parsed = parseDsn(dsn, {
  lowercaseDriver: true,
  // Overrides, allows to force some values (ParseDsnOptions)
  overrides: {
    db: "db3",
    port: undefined,
  },
});

assert.deepEqual(parsed.value, {
  driver: "mysql",
  host: "localhost",
  db: "db3",
});
ParamsTypeDescription
lowercaseDriverbooleanDriver name in lowercase, default false
overridesParseDsnOptionsOverrides allows to force specific values

Utilities

Typeguard

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

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

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

Assertion

import { assertParsableDsn, ParsableDsn } from "@httpx/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)");
}

ParsableDsn

ParsableDsn is a weak opaque type.

declare const tag: unique symbol;
export type WeakOpaqueContainer<Token> = {
  readonly [tag]: Token;
};
export type ParsableDsn = string & WeakOpaqueContainer<'ParsableDsn'>;

It can be used to enforce that the isParsableDsn or assertParsableDsn have been used before usage.

import type { ParsableDsn } from "./dsn-parser.type";
import { assertParsableDsn } from "./assert-parsable-dsn";

// to opt-in, just change the dsn param type to `ParsableDsn` instead of `string` 
const fnWithWeakOpaqueType = (dsn: ParsableDsn) => {
    // by explictly requiring a ParsableDsn, we can rely on typescript
    // to be sure that a validation has occured before (isParsableDsn or assertParsableDsn)  
}

fnWithWeakOpaqueType('redis://localhost');  // āŒ typescript will complain

const dsn = 'redis://localhost';
assertParsableDsn(dsn);
fnWithWeakOpaqueType(dsn);  // āœ… working cause it was checked before

PS: WeakOpaque usage is totally optional, a nice to have if applicable

convertJdbcToDsn

Utility to convert jdbc dsn. Useful for prisma using sqlserver.

import { convertJdbcToDsn } from "@httpx/dsn-parser";

const jdbcDsn =
  "sqlserver://localhost:1433;database=my-db;authentication=default;user=sa;password=pass03$;encrypt=true;trustServerCertificate=true";

const dsn = convertJdbcToDsn(jdbc);

// -> 'sqlserver://localhost:1433?database=my-db&authentication=default&user=sa&password=pass03$&encrypt=true&trustServerCertificate=true'

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/rd@www.example.com: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);
}
ReasonMessageComment
'PARSE_ERROR'Cannot parse DSNRegexp failed
'INVALID_ARGUMENT'DSN must be a string
'EMPTY_DSN'DSN cannot be empty
'INVALID_PORT'Invalid port: ${port}1-65535

Ecosystem

Zod integration example

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

import { z } from "zod";
import { isParsableDsn, type ParsableDsn } from "@httpx/dsn-parser";

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

serverEnvSchema.parse(process.env);

Faq

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

Bundle size

Bundle size is tracked by a size-limit configuration

Scenario (esm)Size (compressed)
import { parseDsn } from '@httpx/dsn-parser~ 750B

Compatibility

LevelCIDescription
Nodeāœ…CI for 18.x, 20.x & 22.x.
Browserāœ…Tested with latest chrome (vitest/playwright)
Browserslistāœ…> 95% on 12/2023. Mins to Chrome 96+, Firefox 90+, Edge 19+, iOS 12+, Safari 12+, Opera 77+
Edgeāœ…Ensured on CI with @vercel/edge-runtime.
Cloudflareāœ…Ensured with @cloudflare/vitest-pool-workers (see wrangler.toml
Typescriptāœ…TS 5.0 + / are-the-type-wrong checks on CI.
ES2022āœ…Dist files checked with es-check

For older browsers: most frontend frameworks can transpile the library (ie: nextjs...)

Contributors

Contributions are warmly appreciated. Have a look to the CONTRIBUTING document.

Sponsors

If my OSS work brightens your day, let's take it to new heights together! Sponsor, coffee, or star – any gesture of support fuels my passion to improve. Thanks for being awesome! šŸ™ā¤ļø

Special thanks to

License

MIT Ā© belgattitude and contributors.

1.8.2

10 months ago

1.8.1

10 months ago

1.8.5

8 months ago

1.8.4

9 months ago

1.8.3

9 months ago

1.8.0

1 year ago

1.7.1

1 year ago

1.7.0

1 year ago

1.6.8

1 year ago

1.6.6

1 year ago

1.6.5

1 year ago

1.6.4

1 year ago

1.6.3

2 years ago

1.6.2

2 years ago

1.6.1

2 years ago

1.6.0

2 years ago

1.5.0

2 years ago

1.4.0

2 years ago

1.3.0

2 years ago

1.2.0

2 years ago

1.1.0

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.10.1

2 years ago

0.10.0

2 years ago