// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT /** * zig-uri for the browser. * * A thin JavaScript layer over `uri.wasm`, which is `src/wasm.zig` compiled * for `wasm32-freestanding`. Load the module once, then use `Uri`: * * ```js * import { init, Uri } from "./uri.js"; * * await init(); * const u = Uri.parse("https://example.com/a/b?q=1#top"); * u.host; // "example.com" * u.path; // ["a", "b"] * u.first("q"); // { key: "q", value: "1" } * u.resolve("../c/").toString(); // "https://example.com/c/" * ``` * * `Uri` is immutable, as it is in Zig: `with`, `child`, `resolve`, `set` and * the rest each return a new one, and instances are frozen. * * ## Components are decoded * * As in the Zig library, every component is held *decoded*: the path of * `http://x/a%2Fb` is the single segment `"a/b"`, and `toString` escapes it * again. Output is therefore canonically rather than identically escaped — * `%2f` comes back as `%2F` and `%41` as `A`. * * One caveat has no counterpart in Zig. A decoded component is a byte string, * and a JavaScript string is not, so a percent escape that is not valid UTF-8 * — `http://x/%FF`, a stray Latin-1 query from a legacy site — becomes U+FFFD * when it is read into a `Uri` field, and re-encodes as `%EF%BF%BD`. The * text-in/text-out functions (`resolve`, `normalize`, `toUri`, `toIri`, * `percentEncode`) never build a JavaScript string from a decoded component, * so they carry such bytes through unharmed; only reading components apart and * putting them back together is lossy. */ /** Must match `abi_version` in `src/wasm.zig`. */ const ABI_VERSION = 1; const encoder = new TextEncoder(); const decoder = new TextDecoder(); /** The instantiated module's exports, or null before `init`. */ let wasm = null; /** An error reported by the Zig library. `code` is the Zig error name. */ export class UriError extends Error { constructor(code) { super(code); this.name = "UriError"; this.code = code; } } // -- loading --------------------------------------------------------------- /** * Instantiate the WebAssembly module. Call once, before anything else. * * `source` may be omitted, in which case `uri.wasm` is fetched from beside * this file; or a URL or path, a `Response` (or a promise for one, so that * `init(fetch(...))` works), a `BufferSource`, or an already-compiled * `WebAssembly.Module`. */ export async function init(source) { if (wasm) return; if (source === undefined) source = new URL("uri.wasm", import.meta.url); if (typeof source === "string" || source instanceof URL) source = fetch(source); let instance; const resolved = await source; if (typeof Response !== "undefined" && resolved instanceof Response) { // Streaming instantiation insists on a `Content-Type: application/wasm` // that plenty of static servers do not send, so keep a second handle on // the body: buffering it works whatever the header says. The clone has to // be taken before the body is read. const buffered = resolved.clone(); try { ({ instance } = await WebAssembly.instantiateStreaming(resolved, {})); } catch { ({ instance } = await WebAssembly.instantiate(await buffered.arrayBuffer(), {})); } } else if (resolved instanceof WebAssembly.Module) { instance = await WebAssembly.instantiate(resolved, {}); } else { ({ instance } = await WebAssembly.instantiate(resolved, {})); } adopt(instance); } /** * `init` without the await, for when the bytes are already in hand — a * `BufferSource` or a compiled `WebAssembly.Module`. Compiling synchronously * is what browsers refuse to do for anything but a small module, so in a page * prefer `init`. */ export function initSync(source) { if (wasm) return; const module = source instanceof WebAssembly.Module ? source : new WebAssembly.Module(source); adopt(new WebAssembly.Instance(module, {})); } function adopt(instance) { const exports = instance.exports; const version = exports.uri_abi_version(); if (version !== ABI_VERSION) { throw new UriError( `uri.wasm speaks ABI version ${version}, uri.js speaks ${ABI_VERSION}`, ); } wasm = exports; } /** Whether `init` has run. */ export function ready() { return wasm !== null; } /** * Whether `toUri`, `toIri`, `idnaToAscii` and `idnaToUnicode` are available. * Always true of a module built by `zig build wasm`, which includes the * `uri_unicode` module; a module without it would throw `UnicodeUnavailable`. */ export function hasUnicode() { return module_().uri_has_unicode() !== 0; } function module_() { if (!wasm) throw new UriError("call init() before using zig-uri"); return wasm; } /** * How many bytes of linear memory the module has reserved. Nothing needs this * to use the library; it is here so that a leak has something to show up in. */ export function memoryBytes() { return module_().memory.buffer.byteLength; } // -- crossing the boundary ------------------------------------------------- /** Copy `text` into linear memory as UTF-8. */ function writeArgument(text) { const bytes = encoder.encode(text); if (bytes.length === 0) return { ptr: 0, len: 0 }; const ptr = wasm.uri_alloc(bytes.length); if (ptr === 0) throw new UriError("OutOfMemory"); new Uint8Array(wasm.memory.buffer, ptr, bytes.length).set(bytes); return { ptr, len: bytes.length }; } /** * Read the `{ ok, ptr, len }` record an operation returned. The views are made * fresh every time because allocating can grow the memory, which detaches any * `ArrayBuffer` taken from it earlier. */ function readResult(address) { const [ok, ptr, len] = new Uint32Array(wasm.memory.buffer, address, 3); const text = len === 0 ? "" : decoder.decode(new Uint8Array(wasm.memory.buffer, ptr, len)); if (!ok) throw new UriError(text); return text; } /** * Call an exported operation. String arguments are copied into linear memory * and expand into the `(ptr, len)` pair the ABI expects; numbers are passed * through. Everything allocated for the call is released before returning, * result included, so nothing accumulates in wasm memory. */ function invoke(operation, args) { module_(); const owned = []; const flat = []; try { for (const arg of args) { if (typeof arg === "number") { flat.push(arg); } else { const buffer = writeArgument(String(arg)); owned.push(buffer); flat.push(buffer.ptr, buffer.len); } } return readResult(operation(...flat)); } finally { for (const buffer of owned) wasm.uri_dealloc(buffer.ptr, buffer.len); wasm.uri_release(); } } // -- options --------------------------------------------------------------- const TEXT_FORMS = { uri: 0, iri: 1, "iri-query": 2 }; const WITH_PASSWORD = 1 << 2; const STRICT_PERCENT = 1 << 0; /** * How a `Uri` is serialized when it is only on its way back into wasm: keep * the password, and keep it ASCII. Anything the caller asked for applies to * the text they actually see, not to this. */ const ROUND_TRIP = TEXT_FORMS.uri | WITH_PASSWORD; const NORMALIZE_BITS = { scheme: 1 << 0, host: 1 << 1, path: 1 << 2, dropDefaultPort: 1 << 3, rootEmptyPath: 1 << 4, }; /** Mirrors the defaults on `normalize.Options`. */ const NORMALIZE_DEFAULTS = { scheme: true, host: true, path: true, dropDefaultPort: false, rootEmptyPath: false, }; const IDNA_BITS = { transitional: 1 << 0, useStd3AsciiRules: 1 << 1, checkHyphens: 1 << 2, checkJoiners: 1 << 3, checkBidi: 1 << 4, verifyDnsLength: 1 << 5, }; /** Mirrors the defaults on `idna.Options`. */ const IDNA_DEFAULTS = { transitional: false, useStd3AsciiRules: false, checkHyphens: true, checkJoiners: true, checkBidi: true, verifyDnsLength: true, }; /** The `percent.CharSet` values `percentEncode` can name. */ const CHAR_SETS = { scheme: 0, username: 1, password: 2, host: 3, segment: 4, "segment-nc": 5, "query-key": 6, "query-value": 7, fragment: 8, }; function bitsFrom(table, defaults, options) { let bits = 0; for (const key of Object.keys(table)) { const on = options?.[key] ?? defaults[key]; if (on) bits |= table[key]; } return bits; } /** `{ form, withPassword }` as `TextFlags`. */ function textFlags(options) { const name = options?.form ?? "uri"; const form = TEXT_FORMS[name]; if (form === undefined) throw new TypeError(`unknown text form: ${name}`); return form | (options?.withPassword ? WITH_PASSWORD : 0); } /** `{ strictPercent }` as `ParseFlags`. */ function parseFlags(options) { return options?.strictPercent ? STRICT_PERCENT : 0; } // -- text in, text out ----------------------------------------------------- /** * Resolve `href` against `base`, the way a browser resolves a link * (RFC 3986 §5). */ export function resolve(base, href, options) { return invoke(module_().uri_resolve, [ base, href, parseFlags(options), textFlags(options), ]); } /** * Syntax-based normalization (RFC 3986 §6.2.2): lowercase the scheme and host * and resolve `.`/`..` segments. `dropDefaultPort` and `rootEmptyPath` add the * scheme-based rules, which are worth enabling before comparing two URIs. */ export function normalize(text, options) { return invoke(module_().uri_normalize, [ text, parseFlags(options), bitsFrom(NORMALIZE_BITS, NORMALIZE_DEFAULTS, options), textFlags(options), ]); } /** * IDNA-encode the host to its `xn--` form, so that the whole reference is * ASCII. */ export function toUri(text, options) { return invoke(module_().uri_to_uri, [text, parseFlags(options), textFlags(options)]); } /** * Decode an `xn--` host back to Unicode, for display. Pass `{ form: "iri" }` * to leave the rest of the reference unescaped too. */ export function toIri(text, options) { return invoke(module_().uri_to_iri, [text, parseFlags(options), textFlags(options)]); } /** UTS #46 `ToASCII` on a bare domain name. */ export function idnaToAscii(name, options) { return invoke(module_().uri_idna_to_ascii, [ name, bitsFrom(IDNA_BITS, IDNA_DEFAULTS, options), ]); } /** UTS #46 `ToUnicode` on a bare domain name. */ export function idnaToUnicode(name, options) { return invoke(module_().uri_idna_to_unicode, [ name, bitsFrom(IDNA_BITS, IDNA_DEFAULTS, options), ]); } /** * Percent-encode everything outside a named character set — one of the keys of * `charSets`, defaulting to `"segment"`. */ export function percentEncode(text, options) { const name = options?.set ?? "segment"; const set = CHAR_SETS[name]; if (set === undefined) throw new TypeError(`unknown character set: ${name}`); return invoke(module_().uri_percent_encode, [text, set, textFlags(options)]); } /** * Decode `%XX` escapes. With `{ strictPercent: true }` a `%` that is not * followed by two hex digits is an error rather than a literal. */ export function percentDecode(text, options) { return invoke(module_().uri_percent_decode, [text, parseFlags(options)]); } /** The names `percentEncode` accepts for its `set`. */ export const charSets = Object.freeze(Object.keys(CHAR_SETS)); /** The IANA-registered default port for a scheme, or null if it has none. */ export function defaultPort(scheme) { if (scheme === null || scheme === undefined) return null; const buffer = writeArgumentIn(String(scheme)); try { return module_().uri_default_port(buffer.ptr, buffer.len) || null; } finally { wasm.uri_dealloc(buffer.ptr, buffer.len); } } /** Whether a scheme is written `scheme://host/...` rather than `scheme:body`. */ export function usesNetloc(scheme) { if (scheme === null || scheme === undefined) return false; const buffer = writeArgumentIn(String(scheme)); try { return module_().uri_uses_netloc(buffer.ptr, buffer.len) !== 0; } finally { wasm.uri_dealloc(buffer.ptr, buffer.len); } } /** `writeArgument`, but checking that the module is loaded first. */ function writeArgumentIn(text) { module_(); return writeArgument(text); } // -- Uri ------------------------------------------------------------------- const HOST_KINDS = ["name", "ipv4", "ipv6"]; /** * A parsed URI reference: the JavaScript face of Zig's `Uri`. * * Instances are frozen. Every method that would change one returns a new * `Uri` instead. */ export class Uri { /** * Parse a URI reference. Throws `UriError` if it is not well formed. */ static parse(text, options) { return Uri.fromJSON(JSON.parse(invoke(module_().uri_parse, [text, parseFlags(options)]))); } /** Rebuild a `Uri` from what `toJSON` produced. */ static fromJSON(value) { return new Uri(value); } /** * Build one from components. Everything is optional; see the fields below * for what each one means. */ constructor(components = {}) { const c = components ?? {}; /** Scheme without the `:`, or null for a relative reference. */ this.scheme = optionalString(c.scheme, "scheme"); /** Userinfo before any `:`. */ this.username = optionalString(c.username, "username"); /** Userinfo after the first `:`. */ this.password = optionalString(c.password, "password"); // `host` accepts either the string on its own or the `{ kind, text }` // object `toJSON` emits, so a `Uri` survives a JSON round trip. const host = c.host && typeof c.host === "object" ? c.host.text : c.host; /** The host, decoded, and *without* the brackets of an IPv6 literal. */ this.host = optionalString(host, "host"); const kind = (c.host && typeof c.host === "object" ? c.host.kind : c.hostKind) ?? "name"; if (this.host !== null && !HOST_KINDS.includes(kind)) { throw new TypeError(`unknown host kind: ${kind}`); } /** `"name"`, `"ipv4"` or `"ipv6"`; null when there is no host. */ this.hostKind = this.host === null ? null : kind; /** The port as written, with no default filled in. */ this.port = c.port === null || c.port === undefined ? null : checkPort(c.port); /** Whether the path is written with a leading `/`. */ this.rooted = Boolean(c.rooted); /** * Path segments, decoded, not counting the empty one implied by `rooted`: * `/a/b/` is `["a", "b", ""]` with `rooted` true. */ this.path = Object.freeze((c.path ?? []).map((s) => requireString(s, "path segment"))); /** * Query parameters in order, as `{ key, value }`. A null `value` is the * bare `?flag` form, which is distinct from the empty `?flag=`. */ this.query = Object.freeze((c.query ?? []).map(toParam)); /** Fragment without the `#`, decoded. */ this.fragment = optionalString(c.fragment, "fragment"); Object.freeze(this); } // -- text ---------------------------------------------------------------- /** * Render the reference. `{ form: "iri" }` keeps the non-ASCII characters * RFC 3987 permits; `{ withPassword: true }` includes the password, which is * withheld by default so that logging a `Uri` cannot leak a credential. */ toString(options) { return invoke(module_().uri_format, [JSON.stringify(this), textFlags(options)]); } /** The components, in the shape `new Uri(...)` and the wasm ABI both take. */ toJSON() { return { scheme: this.scheme, username: this.username, password: this.password, host: this.host === null ? null : { kind: this.hostKind, text: this.host }, port: this.port, rooted: this.rooted, path: [...this.path], query: this.query.map((p) => ({ key: p.key, value: p.value })), fragment: this.fragment, }; } /** The authority, `[user[:password]@]host[:port]`, or `""` if there is none. */ authority(options) { return invoke(module_().uri_authority, [this.#roundTrip(), 0, textFlags(options)]); } // -- inspection ---------------------------------------------------------- /** Whether the reference stands on its own: it has both a scheme and a host. */ isAbsolute() { return this.scheme !== null && this.host !== null; } /** Whether this scheme is written `scheme://host/...`. */ usesNetloc() { return usesNetloc(this.scheme); } /** The scheme's registered default port, ignoring any explicit one. */ defaultPort() { return defaultPort(this.scheme); } /** The port a client would connect to: the explicit one, else the default. */ effectivePort() { return this.port ?? this.defaultPort(); } /** Component-by-component equality, as Zig's `Uri.eql` does it. */ equals(other) { if (!(other instanceof Uri)) return false; return ( this.scheme === other.scheme && this.username === other.username && this.password === other.password && this.host === other.host && this.hostKind === other.hostKind && this.port === other.port && this.rooted === other.rooted && this.path.length === other.path.length && this.path.every((s, i) => s === other.path[i]) && this.query.length === other.query.length && this.query.every((p, i) => p.key === other.query[i].key && p.value === other.query[i].value) ); } // -- derivation ---------------------------------------------------------- /** * A copy with the named components changed. A key that is present and null * clears that component; a key that is absent leaves it alone, so * `u.with({ port: null })` drops the port and `u.with({})` changes nothing. */ with(changes = {}) { const next = this.toJSON(); for (const key of Object.keys(changes)) { if (key === "host") { const value = changes.host; next.host = value === null || value === undefined ? null : typeof value === "object" ? value : { kind: changes.hostKind ?? this.hostKind ?? "name", text: value }; } else if (key === "hostKind") { if (next.host !== null) next.host = { kind: changes.hostKind, text: next.host.text }; } else if (key in next) { next[key] = changes[key]; } else { throw new TypeError(`unknown component: ${key}`); } } return new Uri(next); } /** * Descend into path segments. A trailing empty segment — the one that makes * a path end in `/` — is replaced rather than appended to, so `/a/` and `/a` * both give `/a/b`. */ child(...segments) { if (segments.length === 0) return this; const base = this.path.length > 0 && this.path[this.path.length - 1] === "" ? this.path.slice(0, -1) : this.path.slice(); return this.with({ path: [...base, ...segments.map(String)] }); } /** Replace the last path segment, as if naming a file beside this one. */ sibling(segment) { return this.with({ path: [...this.path.slice(0, -1), String(segment)] }); } /** Resolve `href` against this reference, the way a browser resolves a link. */ resolve(href, options) { return Uri.parse(resolve(this.#roundTrip(), String(href), { form: "uri", withPassword: true }), options); } /** Syntax-based normalization. See the free `normalize` for the options. */ normalize(options) { return Uri.parse( invoke(module_().uri_normalize, [ this.#roundTrip(), parseFlags(options), bitsFrom(NORMALIZE_BITS, NORMALIZE_DEFAULTS, options), ROUND_TRIP, ]), ); } /** The same reference with an `xn--` host. */ toUri() { return Uri.parse(invoke(module_().uri_to_uri, [this.#roundTrip(), 0, ROUND_TRIP])); } /** * The same reference with a Unicode host. Render it with `{ form: "iri" }`, * or the host is escaped straight back to ASCII. */ toIri() { return Uri.parse(invoke(module_().uri_to_iri, [this.#roundTrip(), 0, ROUND_TRIP])); } // -- query --------------------------------------------------------------- /** Every value recorded for `name`, in order. A bare `?name` gives null. */ get(name) { return this.query.filter((p) => p.key === name).map((p) => p.value); } /** The first parameter named `name`, or null. */ first(name) { return this.query.find((p) => p.key === name) ?? null; } /** The last parameter named `name`, or null. */ last(name) { for (let i = this.query.length - 1; i >= 0; i -= 1) { if (this.query[i].key === name) return this.query[i]; } return null; } /** Whether any parameter is named `name`. */ has(name) { return this.query.some((p) => p.key === name); } /** Append `name=value`, keeping any parameter that already uses that name. */ add(name, value = null) { return this.with({ query: [...this.query, toParam({ key: name, value })] }); } /** * Make `name` appear exactly once, with `value`. The first parameter with * that name is overwritten in place, so ordering is preserved, and any later * duplicates are dropped; if the name is absent it is appended. */ set(name, value = null) { const at = this.query.findIndex((p) => p.key === name); if (at === -1) return this.add(name, value); const query = []; this.query.forEach((p, i) => { if (i === at) query.push(toParam({ key: name, value })); else if (p.key !== name) query.push(p); }); return this.with({ query }); } /** Drop every parameter named `name`. */ remove(name) { return this.removeWhere(name); } /** * Drop parameters named `name`, optionally only those whose value matches * `value`, and optionally only the first `limit` of them. * * Omitting `value` means "any value"; `{ value: null }` matches only the * bare `?name` form. */ removeWhere(name, options = {}) { const anyValue = !Object.hasOwn(options, "value"); const wanted = anyValue ? null : (options.value ?? null); const limit = options.limit ?? null; const matches = (p) => p.key === name && (anyValue || (wanted === null ? p.value === null : p.value === wanted)); let dropped = 0; const query = this.query.filter((p) => { if ((limit === null || dropped < limit) && matches(p)) { dropped += 1; return false; } return true; }); return this.with({ query }); } /** How this reference is handed back to wasm without losing anything. */ #roundTrip() { return invoke(module_().uri_format, [JSON.stringify(this), ROUND_TRIP]); } } // -- component checking ---------------------------------------------------- function requireString(value, what) { if (typeof value !== "string") throw new TypeError(`${what} must be a string`); return value; } function optionalString(value, what) { if (value === null || value === undefined) return null; return requireString(value, what); } function checkPort(value) { if (!Number.isInteger(value) || value < 0 || value > 65535) { throw new TypeError("port must be an integer in 0..65535"); } return value; } function toParam(param) { const [key, value] = Array.isArray(param) ? param : [param.key, param.value]; return Object.freeze({ key: requireString(key, "query key"), value: value === null || value === undefined ? null : requireString(value, "query value"), }); }