Something went wrong. Try again.
A URI parser and formatter for Zig, modelled on Python's hyperlink package, with LDAP URLs, file: URIs and sdns:// DNS stamps beside it.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The WebAssembly surface: a flat, C-style ABI over the library, meant to be//! driven from JavaScript by `web/uri.js`.//!//! `Uri` is a Zig value with an arena behind it, which is not a thing a//! JavaScript caller can hold, so nothing here hands out object handles. Every//! entry point instead takes UTF-8 text in linear memory and returns UTF-8//! text, parsing and freeing a `Uri` in between. Reading a reference apart is//! `uri_parse`, which answers with JSON; putting one back together is//! `uri_format`, which takes the same JSON. Everything else — resolution,//! normalization, IDNA — is text in and text out, so those never leave wasm.//!//! ## Calling convention//!//! Arguments are `(ptr, len)` pairs of UTF-8 bytes in the module's memory,//! which the caller obtains from `uri_alloc` and releases with `uri_dealloc`.//! Every operation returns a pointer to a static three-word record://!//! struct { ok: u32, ptr: u32, len: u32 }//!//! `ok` is 1 for a result and 0 for a failure, and `ptr`/`len` are the UTF-8//! payload — the answer, or the name of the error that stopped it. The record//! and its payload stay valid until the next call, so the caller must copy the//! bytes out and then call `uri_release` to hand the memory back.//!//! ## Flags//!//! Option structs are passed as bitfields so that the ABI stays scalar; see//! `TextFlags`, `ParseFlags`, `NormalizeFlags` and `IdnaFlags` for the layout.//! Each has the library's own defaults at a known constant, which `web/uri.js`//! mirrors.
const std = @import("std");
const uri_mod = @import("root.zig");
const Components = uri_mod.Components;const Host = uri_mod.Host;const QueryParam = uri_mod.QueryParam;const Uri = uri_mod.Uri;
/// Linear memory is grown by the allocator and never shrinks, which is why/// results have to be released rather than merely forgotten.const gpa = std.heap.wasm_allocator;
/// Bumped whenever the shape of an export changes, so that a stale `uri.wasm`/// paired with a newer `uri.js` fails loudly instead of subtly.pub const abi_version: u32 = 1;
// -- results ---------------------------------------------------------------
/// The record every operation returns a pointer to. `extern` so that its/// layout is the three consecutive `u32`s JavaScript reads.const Result = extern struct { ok: u32 = 0, ptr: u32 = 0, len: u32 = 0,};
/// A single static slot: there is one thread and the caller copies the payload/// out before calling again, so a queue would buy nothing.var result: Result = .{};/// The part of the payload that came from the allocator. A failure payload is/// a static error name, and must not be freed, so it leaves this empty.var result_owned: []u8 = &.{};
fn releaseResult() void { if (result_owned.len != 0) gpa.free(result_owned); result_owned = &.{}; result = .{};}
/// Take ownership of `bytes` and report it as the result.fn succeed(bytes: []u8) u32 { releaseResult(); result_owned = bytes; result = .{ .ok = 1, .ptr = @intFromPtr(bytes.ptr), .len = @intCast(bytes.len), }; return @intFromPtr(&result);}
/// Report a failure. `name` must outlive the call, which every `@errorName`/// and string literal does.fn fail(name: []const u8) u32 { releaseResult(); result = .{ .ok = 0, .ptr = @intFromPtr(name.ptr), .len = @intCast(name.len), }; return @intFromPtr(&result);}
fn succeedDupe(bytes: []const u8) u32 { return succeed(gpa.dupe(u8, bytes) catch return fail("OutOfMemory"));}
// -- memory ----------------------------------------------------------------
/// Allocate `len` bytes for the caller to write arguments into. Returns 0 on/// failure, and for `len == 0`, which needs no allocation.export fn uri_alloc(len: u32) u32 { if (len == 0) return 0; const buf = gpa.alloc(u8, len) catch return 0; return @intFromPtr(buf.ptr);}
/// Release what `uri_alloc` returned. `len` must be the length it was called/// with.export fn uri_dealloc(ptr: u32, len: u32) void { if (ptr == 0 or len == 0) return; const p: [*]u8 = @ptrFromInt(ptr); gpa.free(p[0..len]);}
/// Release the payload of the last result. Calling it twice is harmless.export fn uri_release() void { releaseResult();}
export fn uri_abi_version() u32 { return abi_version;}
/// Whether this module was built with `-Dunicode=true`. When it was not, the/// IDNA and IRI entry points all fail with `UnicodeUnavailable`.export fn uri_has_unicode() u32 { return @intFromBool(uri_mod.unicode_enabled);}
fn argument(ptr: u32, len: u32) []const u8 { if (len == 0) return &.{}; const p: [*]const u8 = @ptrFromInt(ptr); return p[0..len];}
// -- flags -----------------------------------------------------------------
/// `Uri.ParseOptions` as a bitfield.pub const ParseFlags = struct { pub const strict_percent: u32 = 1 << 0; /// What `Uri.parse` uses. pub const default: u32 = 0;};
/// `Uri.TextOptions` as a bitfield. Bits 0 and 1 together are the `form`.pub const TextFlags = struct { pub const form_mask: u32 = 0b11; pub const form_uri: u32 = 0; pub const form_iri: u32 = 1; pub const form_iri_query: u32 = 2; pub const with_password: u32 = 1 << 2; pub const default: u32 = form_uri;};
/// `Uri.NormalizeOptions` as a bitfield.pub const NormalizeFlags = struct { pub const scheme: u32 = 1 << 0; pub const host: u32 = 1 << 1; pub const path: u32 = 1 << 2; pub const drop_default_port: u32 = 1 << 3; pub const root_empty_path: u32 = 1 << 4; /// The three that `NormalizeOptions` turns on by default. pub const default: u32 = scheme | host | path;};
/// `idna.Options` as a bitfield.pub const IdnaFlags = struct { pub const transitional: u32 = 1 << 0; pub const use_std3_ascii_rules: u32 = 1 << 1; pub const check_hyphens: u32 = 1 << 2; pub const check_joiners: u32 = 1 << 3; pub const check_bidi: u32 = 1 << 4; pub const verify_dns_length: u32 = 1 << 5; /// The five that `idna.Options` turns on by default. pub const default: u32 = check_hyphens | check_joiners | check_bidi | verify_dns_length;};
fn parseOptions(flags: u32) Uri.ParseOptions { return .{ .strict_percent = flags & ParseFlags.strict_percent != 0 };}
fn textOptions(flags: u32) Uri.TextOptions { return .{ .form = switch (flags & TextFlags.form_mask) { TextFlags.form_iri => .iri, TextFlags.form_iri_query => .iri_query, else => .uri, }, .with_password = flags & TextFlags.with_password != 0, };}
fn normalizeOptions(flags: u32) Uri.NormalizeOptions { return .{ .scheme = flags & NormalizeFlags.scheme != 0, .host = flags & NormalizeFlags.host != 0, .path = flags & NormalizeFlags.path != 0, .drop_default_port = flags & NormalizeFlags.drop_default_port != 0, .root_empty_path = flags & NormalizeFlags.root_empty_path != 0, };}
// -- the JSON shape of a reference ----------------------------------------
/// How `Host` is written: the tag separately from the text, so that JavaScript/// sees a string rather than a one-key object it has to unwrap.const HostJson = struct { /// `"name"`, `"ipv4"` or `"ipv6"`. kind: []const u8, /// An IPv6 literal appears without its surrounding brackets. text: []const u8,};
const QueryJson = struct { key: []const u8, value: ?[]const u8 = null,};
/// `Components`, with every field spelled out — `emit_null_optional_fields`/// leaves the absent ones as an explicit `null`, which is easier to consume/// than a missing key.const ComponentsJson = struct { scheme: ?[]const u8 = null, username: ?[]const u8 = null, password: ?[]const u8 = null, host: ?HostJson = null, port: ?u16 = null, rooted: bool = false, path: []const []const u8 = &.{}, query: []const QueryJson = &.{}, fragment: ?[]const u8 = null,};
fn toJson(alloc: std.mem.Allocator, c: Components) ![]u8 { const query = try alloc.alloc(QueryJson, c.query.len); for (c.query, query) |src, *dst| dst.* = .{ .key = src.key, .value = src.value };
const dto: ComponentsJson = .{ .scheme = c.scheme, .username = c.username, .password = c.password, .host = if (c.host) |h| .{ .kind = switch (h) { .hostname => "name", .ipv4 => "ipv4", .ipv6 => "ipv6", }, .text = h.text(), } else null, .port = c.port, .rooted = c.rooted, .path = c.path, .query = query, .fragment = c.fragment, }; return std.json.Stringify.valueAlloc(alloc, dto, .{});}
const FromJsonError = error{InvalidHostKind};
fn fromJson(alloc: std.mem.Allocator, dto: ComponentsJson) (FromJsonError || std.mem.Allocator.Error)!Components { const query = try alloc.alloc(QueryParam, dto.query.len); for (dto.query, query) |src, *dst| dst.* = .{ .key = src.key, .value = src.value };
return .{ .scheme = dto.scheme, .username = dto.username, .password = dto.password, .host = if (dto.host) |h| if (std.mem.eql(u8, h.kind, "name")) Host{ .hostname = h.text } else if (std.mem.eql(u8, h.kind, "ipv4")) Host{ .ipv4 = h.text } else if (std.mem.eql(u8, h.kind, "ipv6")) Host{ .ipv6 = h.text } else return error.InvalidHostKind else null, .port = dto.port, .rooted = dto.rooted, .path = dto.path, .query = query, .fragment = dto.fragment, };}
// -- operations ------------------------------------------------------------
/// Parse a URI reference and answer with its components as JSON.export fn uri_parse(text_ptr: u32, text_len: u32, parse_flags: u32) u32 { var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit();
const c = uri_mod.parse.parse( arena.allocator(), argument(text_ptr, text_len), parseOptions(parse_flags), ) catch |err| return fail(@errorName(err));
const json = toJson(arena.allocator(), c) catch |err| return fail(@errorName(err)); return succeedDupe(json);}
/// Write the components in `json` back out as URI text.export fn uri_format(json_ptr: u32, json_len: u32, text_flags: u32) u32 { var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const alloc = arena.allocator();
const parsed = std.json.parseFromSliceLeaky( ComponentsJson, alloc, argument(json_ptr, json_len), .{ .ignore_unknown_fields = true }, ) catch |err| return fail(@errorName(err));
const c = fromJson(alloc, parsed) catch |err| return fail(@errorName(err)); const text = uri_mod.format.toText(alloc, c, textOptions(text_flags)) catch |err| return fail(@errorName(err)); return succeedDupe(text);}
/// Resolve `href` against `base`, per RFC 3986 §5. This is `Uri.click`, which/// parses `href` itself — `parse_flags` therefore governs only `base`.export fn uri_resolve( base_ptr: u32, base_len: u32, href_ptr: u32, href_len: u32, parse_flags: u32, text_flags: u32,) u32 { const base = Uri.parseOpts(gpa, argument(base_ptr, base_len), parseOptions(parse_flags)) catch |err| return fail(@errorName(err)); defer base.deinit();
const target = base.click(gpa, argument(href_ptr, href_len)) catch |err| return fail(@errorName(err)); defer target.deinit();
return succeed(target.toText(gpa, textOptions(text_flags)) catch |err| return fail(@errorName(err)));}
/// The authority — `[user[:password]@]host[:port]` — of a reference, or an/// empty string when it has none.export fn uri_authority(text_ptr: u32, text_len: u32, parse_flags: u32, text_flags: u32) u32 { const u = Uri.parseOpts(gpa, argument(text_ptr, text_len), parseOptions(parse_flags)) catch |err| return fail(@errorName(err)); defer u.deinit();
return succeed(u.authority(gpa, textOptions(text_flags)) catch |err| return fail(@errorName(err)));}
/// The IANA-registered default port for a scheme, or 0 when it has none —/// 0 is not a usable port, so it doubles as the absent value.export fn uri_default_port(scheme_ptr: u32, scheme_len: u32) u32 { return uri_mod.defaultPort(argument(scheme_ptr, scheme_len)) orelse 0;}
/// Whether a scheme is written `scheme://host/...` rather than `scheme:body`.export fn uri_uses_netloc(scheme_ptr: u32, scheme_len: u32) u32 { return @intFromBool(uri_mod.usesNetloc(argument(scheme_ptr, scheme_len)));}
/// Syntax-based normalization, in text and out again.export fn uri_normalize( text_ptr: u32, text_len: u32, parse_flags: u32, normalize_flags: u32, text_flags: u32,) u32 { const u = Uri.parseOpts(gpa, argument(text_ptr, text_len), parseOptions(parse_flags)) catch |err| return fail(@errorName(err)); defer u.deinit();
const n = u.normalize(gpa, normalizeOptions(normalize_flags)) catch |err| return fail(@errorName(err)); defer n.deinit();
return succeed(n.toText(gpa, textOptions(text_flags)) catch |err| return fail(@errorName(err)));}
/// The two directions of host conversion, which differ only in which `Uri`/// method they reach for.const HostForm = enum { ascii, unicode };
fn convert(text: []const u8, form: HostForm, parse_flags: u32, text_flags: u32) u32 { if (uri_mod.unicode_enabled) { const u = Uri.parseOpts(gpa, text, parseOptions(parse_flags)) catch |err| return fail(@errorName(err)); defer u.deinit();
const converted = (switch (form) { .ascii => u.toUri(gpa), .unicode => u.toIri(gpa), }) catch |err| return fail(@errorName(err)); defer converted.deinit();
return succeed(converted.toText(gpa, textOptions(text_flags)) catch |err| return fail(@errorName(err))); } else return fail("UnicodeUnavailable");}
/// IDNA-encode the host to its `xn--` form, so the whole reference is ASCII./// Requires a module built with `-Dunicode=true`.export fn uri_to_uri(text_ptr: u32, text_len: u32, parse_flags: u32, text_flags: u32) u32 { return convert(argument(text_ptr, text_len), .ascii, parse_flags, text_flags);}
/// Decode an `xn--` host back to Unicode for display. Pair it with the `iri`/// text form to leave the rest of the reference unescaped too. Requires a/// module built with `-Dunicode=true`.export fn uri_to_iri(text_ptr: u32, text_len: u32, parse_flags: u32, text_flags: u32) u32 { return convert(argument(text_ptr, text_len), .unicode, parse_flags, text_flags);}
/// UTS #46 `ToASCII` on a bare domain name — no URI around it. Requires a/// module built with `-Dunicode=true`.export fn uri_idna_to_ascii(name_ptr: u32, name_len: u32, idna_flags: u32) u32 { return idna(argument(name_ptr, name_len), .ascii, idna_flags);}
/// UTS #46 `ToUnicode` on a bare domain name. Requires a module built with/// `-Dunicode=true`.export fn uri_idna_to_unicode(name_ptr: u32, name_len: u32, idna_flags: u32) u32 { return idna(argument(name_ptr, name_len), .unicode, idna_flags);}
fn idna(name: []const u8, form: HostForm, flags: u32) u32 { if (uri_mod.unicode_enabled) { const opts: uri_mod.idna.Options = .{ .transitional = flags & IdnaFlags.transitional != 0, .use_std3_ascii_rules = flags & IdnaFlags.use_std3_ascii_rules != 0, .check_hyphens = flags & IdnaFlags.check_hyphens != 0, .check_joiners = flags & IdnaFlags.check_joiners != 0, .check_bidi = flags & IdnaFlags.check_bidi != 0, .verify_dns_length = flags & IdnaFlags.verify_dns_length != 0, }; const out = (switch (form) { .ascii => uri_mod.idna.toAscii(gpa, name, opts), .unicode => uri_mod.idna.toUnicode(gpa, name, opts), }) catch |err| return fail(@errorName(err)); return succeed(out); } else return fail("UnicodeUnavailable");}
/// Which `percent.CharSet` `uri_percent_encode` should keep unescaped. The/// numbering is part of the ABI, so only ever append to it.pub const CharSetId = enum(u32) { scheme = 0, username = 1, password = 2, host = 3, segment = 4, segment_nc = 5, query_key = 6, query_value = 7, fragment = 8,};
/// Percent-encode everything outside the named character set.export fn uri_percent_encode(text_ptr: u32, text_len: u32, set_id: u32, text_flags: u32) u32 { const set: *const uri_mod.percent.CharSet = switch (std.enums.fromInt(CharSetId, set_id) orelse return fail("InvalidCharSet")) { .scheme => &uri_mod.percent.scheme, .username => &uri_mod.percent.username, .password => &uri_mod.percent.password, .host => &uri_mod.percent.host, .segment => &uri_mod.percent.segment, .segment_nc => &uri_mod.percent.segment_nc, .query_key => &uri_mod.percent.query_key, .query_value => &uri_mod.percent.query_value, .fragment => &uri_mod.percent.fragment, };
var aw: std.Io.Writer.Allocating = .init(gpa); defer aw.deinit(); uri_mod.percent.encodeForm( &aw.writer, argument(text_ptr, text_len), set, textOptions(text_flags).form, ) catch return fail("OutOfMemory");
return succeedDupe(aw.written());}
/// Decode `%XX` escapes. With `ParseFlags.strict_percent` a stray `%` is an/// error rather than a literal.export fn uri_percent_decode(text_ptr: u32, text_len: u32, parse_flags: u32) u32 { const out = uri_mod.percent.decode( gpa, argument(text_ptr, text_len), parseOptions(parse_flags).strict_percent, ) catch |err| return fail(@errorName(err)); return succeed(out);}