(options?: {
readonly ignoreEmptyLines?: boolean | undefined
readonly maxLineBytes?: number | undefined
})
| 332 | * @since 4.0.0 |
| 333 | */ |
| 334 | export const decode = <IE = never, Done = unknown>(options?: { |
| 335 | readonly ignoreEmptyLines?: boolean | undefined |
| 336 | readonly maxLineBytes?: number | undefined |
| 337 | }): Channel.Channel< |
| 338 | Arr.NonEmptyReadonlyArray<unknown>, |
| 339 | IE | NdjsonError, |
| 340 | Done, |
| 341 | Arr.NonEmptyReadonlyArray<Uint8Array>, |
| 342 | IE, |
| 343 | Done |
| 344 | > => |
| 345 | Channel.fromTransform((upstream, _scope) => |
| 346 | Effect.sync(() => { |
| 347 | const ignoreEmptyLines = options?.ignoreEmptyLines === true |
| 348 | const maxLineBytes = options?.maxLineBytes ?? Number.POSITIVE_INFINITY |
| 349 | // The first decoder strips a leading BOM. `\n` and `\r` never occur |
| 350 | // inside a multi-byte character, so each line is decoded on its own. |
| 351 | let decoder = new TextDecoder("utf-8", { fatal: true }) |
| 352 | // Bytes of the current line from earlier chunks |
| 353 | let pending: Array<Uint8Array> = [] |
| 354 | let pendingBytes = 0 |
| 355 | // The previous byte was `\r`, so a `\n` right after it ends nothing |
| 356 | let afterCR = false |
| 357 | |
| 358 | const takeLine = (chunk: Uint8Array, start: number, end: number): Uint8Array => { |
| 359 | if (pendingBytes === 0) return chunk.subarray(start, end) |
| 360 | const line = new Uint8Array(pendingBytes + end - start) |
| 361 | let offset = 0 |
| 362 | for (const bytes of pending) { |
| 363 | line.set(bytes, offset) |
| 364 | offset += bytes.length |
| 365 | } |
| 366 | line.set(chunk.subarray(start, end), offset) |
| 367 | pending = [] |
| 368 | pendingBytes = 0 |
| 369 | return line |
| 370 | } |
| 371 | |
| 372 | const decodeLine = (bytes: Uint8Array, out: Array<unknown>, unterminated: boolean) => { |
| 373 | let line: string |
| 374 | try { |
| 375 | line = decoder.decode(bytes) |
| 376 | } catch (cause) { |
| 377 | return new NdjsonError({ kind: "Unpack", reason: "InvalidUtf8", unterminated, cause }) |
| 378 | } |
| 379 | const firstLine = decoder !== utf8Decoder |
| 380 | decoder = utf8Decoder |
| 381 | // A stripped BOM alone is not an unterminated record. |
| 382 | if (firstLine && unterminated && line.length === 0) return |
| 383 | return parseLine(line, out, ignoreEmptyLines, unterminated) |
| 384 | } |
| 385 | |
| 386 | const step: DecodeStep<Arr.NonEmptyReadonlyArray<Uint8Array>> = (chunks, out) => { |
| 387 | for (const chunk of chunks) { |
| 388 | let start = 0 |
| 389 | for (let i = 0; i < chunk.length; i++) { |
| 390 | const byte = chunk[i] |
| 391 | if (byte === LF || byte === CR) { |
no test coverage detected