// PROTOCOL BUFFERS (architecture, "Other wires": the gRPC wire): a message's proto3 JSON form // (https://protobuf.dev/programming-guides/json/) to its binary encoding (https://protobuf.dev/programming-guides/encoding/) // and back, over the schema the derive writes for a proto unit (`src/generated/proto.gen.json`, twin-standard's // `protoSchema`). A handler reads and answers the JSON form; the wire carries the bytes. The JSON form names a field by // its JSON name, writes 64-bit integers as decimal strings, bytes as base64, enums by their value names, a map as an // object, and leaves out a field holding its default; `google.protobuf.Timestamp`, `Duration`, the wrappers and `Empty` // take their own JSON forms. Importing it does nothing. type Row = Record; export type ProtoField = { name: string; json: string; number: number; type: string; kind: 'scalar' | 'message' | 'enum'; repeated?: true; map?: { key: string; value: string; valueKind: 'scalar' | 'message' | 'enum' } }; export type ProtoSchema = { messages: Record; enums: Record>; rpcs: Record; }; const VARINT = new Set(['int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64', 'bool']); const FIXED64 = new Set(['fixed64', 'sfixed64', 'double']); const FIXED32 = new Set(['fixed32', 'sfixed32', 'float']); const WRAPPERS: Record = { 'google.protobuf.DoubleValue': 'double', 'google.protobuf.FloatValue': 'float', 'google.protobuf.Int64Value': 'int64', 'google.protobuf.UInt64Value': 'uint64', 'google.protobuf.Int32Value': 'int32', 'google.protobuf.UInt32Value': 'uint32', 'google.protobuf.BoolValue': 'bool', 'google.protobuf.StringValue': 'string', 'google.protobuf.BytesValue': 'bytes', }; const ENC = new TextEncoder(); const DEC = new TextDecoder(); const wireOf = (f: { type: string; kind: string }): number => f.kind === 'enum' || VARINT.has(f.type) ? 0 : FIXED64.has(f.type) ? 1 : FIXED32.has(f.type) ? 5 : 2; // ── writing ──────────────────────────────────────────────────────────────────────────────────── class Writer { private parts: number[] = []; varint(v: bigint): void { let x = BigInt.asUintN(64, v); while (x >= 0x80n) { this.parts.push(Number((x & 0x7fn) | 0x80n)); x >>= 7n; } this.parts.push(Number(x)); } tag(number: number, wire: number): void { this.varint((BigInt(number) << 3n) | BigInt(wire)); } bytes(b: Uint8Array): void { this.varint(BigInt(b.length)); for (const x of b) this.parts.push(x); } raw(b: Uint8Array): void { for (const x of b) this.parts.push(x); } fixed(v: bigint | number, size: 4 | 8, float = false): void { const buf = new DataView(new ArrayBuffer(size)); if (float) { if (size === 8) buf.setFloat64(0, Number(v), true); else buf.setFloat32(0, Number(v), true); } else if (size === 8) buf.setBigUint64(0, BigInt.asUintN(64, BigInt(v)), true); else buf.setUint32(0, Number(BigInt.asUintN(32, BigInt(v))), true); for (const x of new Uint8Array(buf.buffer)) this.parts.push(x); } done(): Uint8Array { return Uint8Array.from(this.parts); } } const zigzag = (v: bigint, bits: 32 | 64): bigint => (v << 1n) ^ (v >> BigInt(bits - 1)); const b64decode = (s: string): Uint8Array => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0)); const b64encode = (b: Uint8Array): string => btoa(Array.from(b, (x) => String.fromCharCode(x)).join('')); function enumNumber(schema: ProtoSchema, type: string, v: unknown): number { if (typeof v === 'number') return v; const n = schema.enums[type]?.[String(v)]; if (n === undefined) throw new Error(`protobuf: ${String(v)} is not a value of ${type}`); return n; } function writeScalar(w: Writer, type: string, v: unknown): void { switch (type) { case 'int32': case 'int64': case 'uint32': case 'uint64': w.varint(BigInt(v as string | number)); break; case 'sint32': w.varint(zigzag(BigInt(v as number), 32)); break; case 'sint64': w.varint(zigzag(BigInt(v as string), 64)); break; case 'bool': w.varint(v ? 1n : 0n); break; case 'fixed64': case 'sfixed64': w.fixed(BigInt(v as string), 8); break; case 'double': w.fixed(Number(v), 8, true); break; case 'fixed32': case 'sfixed32': w.fixed(BigInt(v as string | number), 4); break; case 'float': w.fixed(Number(v), 4, true); break; default: throw new Error(`protobuf: ${type} is not a packable scalar`); } } /** A well-known type's JSON form as the message it stands for, or undefined for any other type. */ function wellKnownIn(type: string, v: unknown): Row | undefined { if (type === 'google.protobuf.Timestamp' && typeof v === 'string') { const ms = Date.parse(v); const frac = /\.(\d+)/.exec(v)?.[1] ?? ''; return { seconds: String(Math.floor(ms / 1000)), nanos: Number(frac.padEnd(9, '0').slice(0, 9)) }; } if (type === 'google.protobuf.Duration' && typeof v === 'string') { const [s, f = ''] = v.replace(/s$/, '').split('.'); return { seconds: s, nanos: (s!.startsWith('-') ? -1 : 1) * Number(f.padEnd(9, '0').slice(0, 9)) }; } if (WRAPPERS[type] !== undefined) return { value: v }; return undefined; } function writeValue(schema: ProtoSchema, w: Writer, f: { number: number; type: string; kind: string }, v: unknown): void { if (f.kind === 'message') { w.tag(f.number, 2); w.bytes(encodeMessage(schema, f.type, v)); return; } if (f.kind === 'enum') { w.tag(f.number, 0); w.varint(BigInt(enumNumber(schema, f.type, v))); return; } if (f.type === 'string') { w.tag(f.number, 2); w.bytes(ENC.encode(String(v))); return; } if (f.type === 'bytes') { w.tag(f.number, 2); w.bytes(typeof v === 'string' ? b64decode(v) : (v as Uint8Array)); return; } w.tag(f.number, wireOf(f)); writeScalar(w, f.type, v); } /** A message's JSON form (proto3 JSON) as its binary encoding. */ export function encodeMessage(schema: ProtoSchema, type: string, value: unknown): Uint8Array { const known = wellKnownIn(type, value); const v = (known ?? (value && typeof value === 'object' ? value : {})) as Row; const fields = schema.messages[type]; if (!fields) throw new Error(`protobuf: ${type} is not a message of the schema`); const w = new Writer(); for (const f of fields) { const x = v[f.json] ?? v[f.name]; if (x === undefined || x === null) continue; if (f.map) { for (const [k, mv] of Object.entries(x as Row)) { const entry = new Writer(); const keyType = f.map.key; writeValue(schema, entry, { number: 1, type: keyType, kind: 'scalar' }, keyType === 'bool' ? k === 'true' : k); writeValue(schema, entry, { number: 2, type: f.map.value, kind: f.map.valueKind }, mv); w.tag(f.number, 2); w.bytes(entry.done()); } } else if (f.repeated) { const list = x as unknown[]; if (f.kind === 'enum' || (f.kind === 'scalar' && f.type !== 'string' && f.type !== 'bytes')) { // proto3 packs repeated scalars and enums const packed = new Writer(); for (const item of list) { if (f.kind === 'enum') packed.varint(BigInt(enumNumber(schema, f.type, item))); else writeScalar(packed, f.type, item); } w.tag(f.number, 2); w.bytes(packed.done()); } else for (const item of list) writeValue(schema, w, f, item); } else writeValue(schema, w, f, x); } return w.done(); } // ── reading ──────────────────────────────────────────────────────────────────────────────────── class Reader { at = 0; constructor(readonly b: Uint8Array) {} get done(): boolean { return this.at >= this.b.length; } varint(): bigint { let out = 0n; let shift = 0n; for (;;) { if (this.at >= this.b.length) throw new Error('protobuf: a varint runs past the end'); const x = this.b[this.at++]!; out |= BigInt(x & 0x7f) << shift; if (!(x & 0x80)) return out; shift += 7n; } } take(n: number): Uint8Array { if (n < 0 || this.at + n > this.b.length) throw new Error(`protobuf: a field runs past the message's end (${n} bytes at ${this.at} of ${this.b.length})`); const out = this.b.subarray(this.at, this.at + n); this.at += n; return out; } bytes(): Uint8Array { return this.take(Number(this.varint())); } skip(wire: number, number?: number): void { if (wire === 0) this.varint(); else if (wire === 1) this.take(8); else if (wire === 5) this.take(4); else if (wire === 2) this.bytes(); else if (wire === 3) { while (!this.done) { const tag = this.varint(); if (tag > 0xffffffffn || (tag >> 3n) === 0n) throw new Error('protobuf: invalid group field tag'); const field = Number(tag >> 3n), kind = Number(tag & 7n); if (kind === 4) { if (number !== undefined && field !== number) throw new Error('protobuf: mismatched group end'); return; } this.skip(kind, field); } throw new Error('protobuf: unterminated group'); } else throw new Error(`protobuf: wire type ${wire} is not supported`); } } const unzigzag = (v: bigint): bigint => (v >> 1n) ^ -(v & 1n); function readScalar(r: Reader, type: string): unknown { switch (type) { case 'int32': return Number(BigInt.asIntN(32, r.varint())); case 'uint32': return Number(BigInt.asUintN(32, r.varint())); case 'int64': return String(BigInt.asIntN(64, r.varint())); case 'uint64': return String(BigInt.asUintN(64, r.varint())); case 'sint32': return Number(BigInt.asIntN(32, unzigzag(r.varint()))); case 'sint64': return String(unzigzag(r.varint())); case 'bool': return r.varint() !== 0n; case 'fixed64': return String(new DataView(r.take(8).slice().buffer).getBigUint64(0, true)); case 'sfixed64': return String(new DataView(r.take(8).slice().buffer).getBigInt64(0, true)); case 'double': return new DataView(r.take(8).slice().buffer).getFloat64(0, true); case 'fixed32': return new DataView(r.take(4).slice().buffer).getUint32(0, true); case 'sfixed32': return new DataView(r.take(4).slice().buffer).getInt32(0, true); case 'float': return new DataView(r.take(4).slice().buffer).getFloat32(0, true); default: throw new Error(`protobuf: ${type} is not a scalar`); } } function enumName(schema: ProtoSchema, type: string, n: number): string | number { for (const [name, v] of Object.entries(schema.enums[type] ?? {})) if (v === n) return name; return n; } function readValue(schema: ProtoSchema, r: Reader, f: { type: string; kind: string }, wire: number): unknown { if (f.kind === 'message') return decodeMessage(schema, f.type, r.bytes()); if (f.kind === 'enum') return enumName(schema, f.type, Number(BigInt.asIntN(32, r.varint()))); if (f.type === 'string') return DEC.decode(r.bytes()); if (f.type === 'bytes') return b64encode(r.bytes()); void wire; return readScalar(r, f.type); } /** A well-known message's JSON form from its decoded fields, or the fields as they are for any other type. */ function wellKnownOut(type: string, m: Row): unknown { if (type === 'google.protobuf.Timestamp') { const whole = new Date(Number(m.seconds ?? 0) * 1000).toISOString().replace(/\.000Z$/, ''); const nanos = Number(m.nanos ?? 0); return `${whole}${protoFraction(nanos)}Z`; } if (type === 'google.protobuf.Duration') { const seconds = BigInt(String(m.seconds ?? '0')); const nanos = Number(m.nanos ?? 0); const negative = seconds < 0n || nanos < 0; return `${negative ? '-' : ''}${seconds < 0n ? -seconds : seconds}${protoFraction(Math.abs(nanos))}s`; } if (WRAPPERS[type] !== undefined) return m.value ?? (WRAPPERS[type] === 'bool' ? false : WRAPPERS[type] === 'string' || WRAPPERS[type] === 'bytes' ? '' : 0); return m; } /** ProtoJSON emits 0, 3, 6 or 9 fractional digits, retaining the full nanosecond value. */ function protoFraction(nanos: number): string { if (!nanos) return ''; const digits = String(nanos).padStart(9, '0'); return `.${digits.slice(0, nanos % 1e6 === 0 ? 3 : nanos % 1000 === 0 ? 6 : 9)}`; } /** A message's binary encoding as its JSON form (proto3 JSON; a field at its default is left out). */ export function decodeMessage(schema: ProtoSchema, type: string, bytes: Uint8Array): unknown { const fields = schema.messages[type]; if (!fields) throw new Error(`protobuf: ${type} is not a message of the schema`); const byNumber = new Map(fields.map((f) => [f.number, f] as const)); const out: Row = {}; const r = new Reader(bytes); while (!r.done) { const rawKey = r.varint(); if (rawKey > 0xffffffffn) throw new Error('protobuf: field tag exceeds 32 bits'); const key = Number(rawKey); const number = key >>> 3; const wire = key & 7; const f = byNumber.get(number); if (!f) { r.skip(wire); continue; } if (f.map) { const entry = new Reader(r.bytes()); let k: unknown; let v: unknown; while (!entry.done) { const rawKey = entry.varint(); if (rawKey > 0xffffffffn) throw new Error('protobuf: map field tag exceeds 32 bits'); const ek = Number(rawKey); if ((ek >>> 3) === 1) k = readValue(schema, entry, { type: f.map.key, kind: 'scalar' }, ek & 7); else if ((ek >>> 3) === 2) v = readValue(schema, entry, { type: f.map.value, kind: f.map.valueKind }, ek & 7); else entry.skip(ek & 7); } ((out[f.json] ??= {}) as Row)[String(k ?? '')] = v; } else if (f.repeated) { const list = (out[f.json] ??= []) as unknown[]; // a packed run of scalars or enums, or one element if (wire === 2 && (f.kind === 'enum' || (f.kind === 'scalar' && f.type !== 'string' && f.type !== 'bytes'))) { const packed = new Reader(r.bytes()); while (!packed.done) list.push(f.kind === 'enum' ? enumName(schema, f.type, Number(BigInt.asIntN(32, packed.varint()))) : readScalar(packed, f.type)); } else list.push(readValue(schema, r, f, wire)); } else out[f.json] = readValue(schema, r, f, wire); } return wellKnownOut(type, out); } /** Rewrite selected length-delimited fields without decoding/re-encoding the rest of a message. * Undefined keeps the original field bytes; null removes that occurrence. Nested rewrites use this same visitor. * This is for transparent vendor fronts: unknown fields, ordering and untouched encodings survive unchanged. */ export function rewriteProtobufFields( bytes: Uint8Array, fields: Readonly Uint8Array | null | undefined>>, ): Uint8Array { const reader = new Reader(bytes), writer = new Writer(); while (!reader.done) { const start = reader.at, tag = reader.varint(); if (tag > 0xffffffffn || (tag >> 3n) === 0n) throw new Error('protobuf: invalid field tag'); const number = Number(tag >> 3n), wire = Number(tag & 7n); const rewrite = Object.hasOwn(fields, number) ? fields[number] : undefined; if (wire === 2 && rewrite) { const changed = rewrite(reader.bytes()); if (changed === undefined) writer.raw(bytes.subarray(start, reader.at)); else if (changed !== null) { writer.tag(number, wire); writer.bytes(changed); } } else { reader.skip(wire, number); writer.raw(bytes.subarray(start, reader.at)); } } return writer.done(); }