// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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("uri"); const uri_unicode = @import("uri_unicode"); 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 the IDNA and IRI entry points are available. Always 1: the module /// is built with `uri_unicode` in it. Kept so that a loader written against a /// module that might lack them can still ask. export fn uri_has_unicode() u32 { return 1; } 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_unicode` function they reach for. const HostForm = enum { ascii, unicode }; fn convert(text: []const u8, form: HostForm, parse_flags: u32, text_flags: u32) u32 { const u = Uri.parseOpts(gpa, text, parseOptions(parse_flags)) catch |err| return fail(@errorName(err)); defer u.deinit(); const converted = (switch (form) { .ascii => uri_unicode.toUri(gpa, u), .unicode => uri_unicode.toIri(gpa, u), }) catch |err| return fail(@errorName(err)); defer converted.deinit(); return succeed(converted.toText(gpa, textOptions(text_flags)) catch |err| return fail(@errorName(err))); } /// IDNA-encode the host to its `xn--` form, so the whole reference is ASCII. 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. 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. 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. 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 { const opts: uri_unicode.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_unicode.idna.toAscii(gpa, name, opts), .unicode => uri_unicode.idna.toUnicode(gpa, name, opts), }) catch |err| return fail(@errorName(err)); return succeed(out); } /// 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); }