| 143 | * Parses an envelope |
| 144 | */ |
| 145 | export function parseEnvelope(env: string | Uint8Array): Envelope { |
| 146 | let buffer = typeof env === 'string' ? encodeUTF8(env) : env; |
| 147 | |
| 148 | function readBinary(length: number): Uint8Array { |
| 149 | const bin = buffer.subarray(0, length); |
| 150 | // Replace the buffer with the remaining data excluding trailing newline |
| 151 | buffer = buffer.subarray(length + 1); |
| 152 | return bin; |
| 153 | } |
| 154 | |
| 155 | function readJson<T>(): T { |
| 156 | let i = buffer.indexOf(0xa); |
| 157 | // If we couldn't find a newline, we must have found the end of the buffer |
| 158 | if (i < 0) { |
| 159 | i = buffer.length; |
| 160 | } |
| 161 | |
| 162 | return JSON.parse(decodeUTF8(readBinary(i))) as T; |
| 163 | } |
| 164 | |
| 165 | const envelopeHeader = readJson<BaseEnvelopeHeaders>(); |
| 166 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 167 | const items: [any, any][] = []; |
| 168 | |
| 169 | while (buffer.length) { |
| 170 | const itemHeader = readJson<BaseEnvelopeItemHeaders>(); |
| 171 | const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined; |
| 172 | |
| 173 | items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]); |
| 174 | } |
| 175 | |
| 176 | return [envelopeHeader, items]; |
| 177 | } |
| 178 | |
| 179 | /** |
| 180 | * Creates envelope item for a single span |