Skip to Content
URNOverview

Ahead of the release

npm install @evanion/urn gives you 2.0.0. These pages document main, which has changes that release does not.

@evanion/urn

Uniform Resource Names, as defined by RFC 8141 , with an API shaped like the JSON class: stringify writes one, parse reads one.

A URN is an identifier that carries its own namespace:

urn : user : 1337 ↑ ↑ ↑ scheme NID NSS

Nothing downstream has to be told what a bare 1337 refers to. AWS’s ARNs are the same idea with a longer NSS.

Installation

npm install @evanion/urn

Quick start

A subclass is the extension point. Override the statics and every inherited method reads the new values:

import { } from '@evanion/urn'; // A subclass is the extension point: override the statics and every inherited // method reads the new values. class extends { static override readonly = 'trn'; } .('foo', 'bar'); // -> 'trn:bar:foo' // `bar` is not this class's own NID, which is still the inherited `nid`, so // parse keeps it in the nss rather than discarding the namespace. const = .('trn:bar:foo'); // -> { urn: 'trn', nid: 'bar', nss: 'bar:foo' }

bar is not this class’s own NID — TRN inherits the base class’s nid, which is the placeholder 'nid' — so parse keeps it in the nss rather than discarding the namespace. Give the class its own NID and the nss comes back clean:

class UserTRN extends TRN { static override readonly nid = 'user'; } UserTRN.stringify('1337'); // 'trn:user:1337' UserTRN.parse('trn:user:1337'); // { urn: 'trn', nid: 'user', nss: '1337' }

Parsing and namespaces covers that retention rule in full.

What is in the package

ExportWhat it is
URNthe class: sixteen statics, all inheritable
encodeNss, decodeNsspercent-encoding, as an explicit step
ValidationError, InvalidErrorthe error hierarchy
ParsedURN, URNParts, IFullURNthe shapes parse returns and stringify accepts
URNComponentsthe three optional RFC 8141 §2.3 components

URN carries stringify, parse, isValidFormat, extractId, sameNamespace, belongsToNamespace and equals, plus the six grammar getters. The API reference has them all.

What this library does not do

  • It does not normalise. parse returns every part in the case it was written in, with percent-triplets intact, because RFC 8141 §3.1 requires that an encoded octet stay opaque for equivalence purposes. Use equals to compare.
  • It does not encode. stringify rejects an NSS containing a literal space rather than encoding it, so nothing can be double-encoded by accident. encodeNss is the explicit step.
  • It does not deduplicate. An NSS whose first segment happens to equal the NID survives the round trip, which is what keeps a composite key imported from another system recoverable.
  • It does not resolve. A URN names a resource; finding it is somebody else’s job. The r- and q-components exist to carry parameters to whoever does.

Where to go next

Last updated on