Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Reading members out of a `std.json.Value` without failing on the ones that//! are not there.//!//! Every resource in this library is parsed this way rather than by mapping a//! Zig struct onto the JSON, and the reason is what a Graph response actually//! looks like. A response carries only the properties that were asked for --//! `$select=subject,sender` really does return three members and no more -- and//! Microsoft adds new ones without warning, so `std.json.parseFromSlice` into a//! struct fails on a live mailbox in two different ways: `MissingField` for//! everything `$select` left out, and `UnknownField` for everything added since//! this was written. A client that walks a mailbox cannot afford either.//!//! There is a second reason, particular to OData. Half the members that matter//! are *annotations* rather than properties -- `@odata.nextLink`,//! `@odata.deltaLink`, `@odata.etag`, `@removed` -- and a name beginning with//! `@` and containing a `.` is not a Zig identifier. Reading them by string is//! the only way that is not an escaping exercise.
const std = @import("std");
const iso8601 = @import("iso8601.zig");
pub fn object(value: std.json.Value, name: []const u8) ?std.json.Value { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .object => member, else => null, };}
pub fn array(value: std.json.Value, name: []const u8) ?[]const std.json.Value { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .array => |a| a.items, else => null, };}
pub fn string(value: std.json.Value, name: []const u8) ?[]const u8 { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .string => |s| s, else => null, };}
/// A string with at least one byte in it.////// The distinction is worth having because an empty `@odata.nextLink` would be/// followed as a URL if it were taken at face value, and because Graph writes/// `""` for a `subject` that was never set rather than omitting it.pub fn nonEmptyString(value: std.json.Value, name: []const u8) ?[]const u8 { const s = string(value, name) orelse return null; return if (s.len == 0) null else s;}
/// An `Int32` member, which Graph sends as a JSON number rather than as the/// quoted decimal string Gmail uses.////// A negative count is `null` rather than a wrapped huge one: `totalItemCount`/// of `-1` is not a folder with four billion messages in it.pub fn unsigned(value: std.json.Value, name: []const u8) ?u32 { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .integer => |i| std.math.cast(u32, i), // Costs one branch, and a proxy or a test fixture may quote it. .string => |s| std.fmt.parseInt(u32, s, 10) catch null, .number_string => |s| std.fmt.parseInt(u32, s, 10) catch null, else => null, };}
pub fn signed64(value: std.json.Value, name: []const u8) ?i64 { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .integer => |i| i, .string => |s| std.fmt.parseInt(i64, s, 10) catch null, .number_string => |s| std.fmt.parseInt(i64, s, 10) catch null, else => null, };}
/// A `Boolean` member. Absent is `null` rather than `false`, because the two/// are different: a message with no `isRead` was fetched with a `$select` that/// left it out, and reporting that as "unread" would mark a whole mailbox/// unread.pub fn boolean(value: std.json.Value, name: []const u8) ?bool { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .bool => |b| b, // Graph itself does not do this, but its delta responses have been // seen to: the reference's own example for a changed message shows // `"isRead": "true"`, quoted. .string => |s| if (std.ascii.eqlIgnoreCase(s, "true")) true else if (std.ascii.eqlIgnoreCase(s, "false")) false else null, else => null, };}
/// A `DateTimeOffset` member: an ISO 8601 string, read into an instant./// `null` for a member that is absent or is not a timestamp.pub fn dateTime(value: std.json.Value, name: []const u8) ?std.Io.Timestamp { const text = string(value, name) orelse return null; return iso8601.parse(text);}
/// The strings of a string array member, borrowed from `value`. Members of/// the array that are not strings are skipped rather than being fatal.pub fn stringList( alloc: std.mem.Allocator, value: std.json.Value, name: []const u8,) std.mem.Allocator.Error![]const []const u8 { const items = array(value, name) orelse return &.{}; var list: std.ArrayList([]const u8) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| switch (item) { .string => |s| list.appendAssumeCapacity(s), else => {}, }; return list.toOwnedSlice(alloc);}
/// Decodes a base64 member, which is how an attachment's bytes arrive in/// `contentBytes`.////// Standard base64 with padding, which is what Graph sends and what makes this/// different from Gmail's base64url. Both alphabets are tried anyway, because/// the cost is one more attempt on a string that has already failed and the/// alternative is an attachment that silently comes back empty.pub fn base64( alloc: std.mem.Allocator, value: std.json.Value, name: []const u8,) std.mem.Allocator.Error!?[]u8 { const encoded = string(value, name) orelse return null; return decodeBase64(alloc, encoded) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // Undecodable content is not worth failing a whole message over; the // caller sees an attachment with no bytes rather than no message. error.InvalidBase64 => null, };}
pub fn decodeBase64( alloc: std.mem.Allocator, encoded: []const u8,) (std.mem.Allocator.Error || error{InvalidBase64})![]u8 { const decoders = [_]std.base64.Base64Decoder{ std.base64.standard.Decoder, std.base64.standard_no_pad.Decoder, std.base64.url_safe.Decoder, std.base64.url_safe_no_pad.Decoder, }; for (decoders) |decoder| { const size = decoder.calcSizeForSlice(encoded) catch continue; const out = try alloc.alloc(u8, size); errdefer alloc.free(out); decoder.decode(out, encoded) catch { alloc.free(out); continue; }; return out; } return error.InvalidBase64;}
const testing = std.testing;
fn parse(text: []const u8) !std.json.Parsed(std.json.Value) { return std.json.parseFromSlice(std.json.Value, testing.allocator, text, .{});}
test "a missing member is null, not an error" { var p = try parse("{}"); defer p.deinit(); try testing.expectEqual(@as(?[]const u8, null), string(p.value, "nope")); try testing.expectEqual(@as(?u32, null), unsigned(p.value, "nope")); try testing.expectEqual(@as(?i64, null), signed64(p.value, "nope")); try testing.expectEqual(@as(?bool, null), boolean(p.value, "nope")); try testing.expectEqual(@as(?std.Io.Timestamp, null), dateTime(p.value, "nope")); try testing.expectEqual(@as(?[]const std.json.Value, null), array(p.value, "nope")); try testing.expectEqual(@as(?std.json.Value, null), object(p.value, "nope"));}
test "a member of the wrong type is null, not an error" { var p = try parse("{\"a\":[],\"b\":{},\"c\":\"x\",\"d\":true}"); defer p.deinit(); try testing.expectEqual(@as(?[]const u8, null), string(p.value, "a")); try testing.expectEqual(@as(?u32, null), unsigned(p.value, "d")); try testing.expectEqual(@as(?bool, null), boolean(p.value, "c")); try testing.expectEqual(@as(?std.json.Value, null), object(p.value, "a")); try testing.expectEqual(@as(?[]const std.json.Value, null), array(p.value, "b"));}
test "the OData annotations are readable, @ and dot and all" { var p = try parse( \\{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#Collection(message)", \\ "@odata.nextLink":"https://graph.microsoft.com/v1.0/me/messages?$skiptoken=x", \\ "@odata.etag":"W/\"CQAAABYAAAC4\"", \\ "@removed":{"reason":"deleted"}} ); defer p.deinit();
try testing.expect(std.mem.endsWith( u8, nonEmptyString(p.value, "@odata.nextLink").?, "$skiptoken=x", )); try testing.expectEqualStrings("W/\"CQAAABYAAAC4\"", string(p.value, "@odata.etag").?); try testing.expectEqualStrings("deleted", string(object(p.value, "@removed").?, "reason").?);}
test "an empty link is not a link" { var p = try parse("{\"@odata.nextLink\":\"\",\"other\":\"x\"}"); defer p.deinit(); try testing.expectEqual(@as(?[]const u8, null), nonEmptyString(p.value, "@odata.nextLink")); try testing.expectEqualStrings("x", nonEmptyString(p.value, "other").?);}
test "counts are numbers here, not quoted strings" { var p = try parse( \\{"totalItemCount":1024,"unreadItemCount":0,"negative":-1,"quoted":"7"} ); defer p.deinit(); try testing.expectEqual(@as(?u32, 1024), unsigned(p.value, "totalItemCount")); try testing.expectEqual(@as(?u32, 0), unsigned(p.value, "unreadItemCount")); // Not a folder with four billion messages in it. try testing.expectEqual(@as(?u32, null), unsigned(p.value, "negative")); try testing.expectEqual(@as(?u32, 7), unsigned(p.value, "quoted")); try testing.expectEqual(@as(?i64, -1), signed64(p.value, "negative"));}
test "absent is not false" { var p = try parse("{\"isRead\":false,\"isDraft\":true,\"quoted\":\"true\"}"); defer p.deinit(); try testing.expectEqual(@as(?bool, false), boolean(p.value, "isRead")); try testing.expectEqual(@as(?bool, true), boolean(p.value, "isDraft")); // The distinction the whole optional exists for: a `$select` that left // `hasAttachments` out must not read as "no attachments". try testing.expectEqual(@as(?bool, null), boolean(p.value, "hasAttachments")); // A delta response's own reference shows this quoted. try testing.expectEqual(@as(?bool, true), boolean(p.value, "quoted"));}
test "a timestamp member" { var p = try parse( \\{"receivedDateTime":"2018-09-09T03:15:08Z","bad":"whenever","n":7} ); defer p.deinit(); try testing.expectEqual( @as(i96, 1536462908) * std.time.ns_per_s, dateTime(p.value, "receivedDateTime").?.nanoseconds, ); try testing.expectEqual(@as(?std.Io.Timestamp, null), dateTime(p.value, "bad")); try testing.expectEqual(@as(?std.Io.Timestamp, null), dateTime(p.value, "n"));}
test "a string list skips what is not a string" { var p = try parse("{\"categories\":[\"red\",7,null,{},\"blue\"]}"); defer p.deinit();
var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const list = try stringList(arena.allocator(), p.value, "categories"); try testing.expectEqual(@as(usize, 2), list.len); try testing.expectEqualStrings("red", list[0]); try testing.expectEqualStrings("blue", list[1]);
const none = try stringList(arena.allocator(), p.value, "absent"); try testing.expectEqual(@as(usize, 0), none.len);}
test "base64, which Graph pads" { // "hello world" in standard base64, then in the three other spellings. for ([_][]const u8{ "aGVsbG8gd29ybGQ=", "aGVsbG8gd29ybGQ", }) |encoded| { const out = try decodeBase64(testing.allocator, encoded); defer testing.allocator.free(out); try testing.expectEqualStrings("hello world", out); }
// The `+/` alphabet, which url_safe would reject and standard accepts. const plus = try decodeBase64(testing.allocator, "Pz8/Pg=="); defer testing.allocator.free(plus); try testing.expectEqualStrings("???>", plus);}
test "base64 that is not base64" { try testing.expectError( error.InvalidBase64, decodeBase64(testing.allocator, "not base64!"), ); try testing.expectError( error.InvalidBase64, decodeBase64(testing.allocator, "====="), );}
test "undecodable content yields no content rather than an error" { var p = try parse("{\"contentBytes\":\"!!!not base64!!!\"}"); defer p.deinit(); try testing.expectEqual( @as(?[]u8, null), try base64(testing.allocator, p.value, "contentBytes"), );}
test { _ = iso8601;}