json-stream-lite 1.3.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -209,10 +209,63 @@ for (const chunk of jsonStreamStringify(data, null, 0, {
209
209
  }
210
210
  ```
211
211
 
212
+ ## RFC 8259 Conformance Notes
213
+
214
+ json-stream-lite reads and writes JSON as defined by [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259). Like `JSON.parse`, it accepts any value at the top level (not only objects and arrays) and treats only space, tab, line feed and carriage return as whitespace. To stream without validating every byte, the parser is lenient in some places. The writer follows `JSON.stringify` with a few differences.
215
+
216
+ ### Parser leniencies
217
+
218
+ - **Comments and trailing commas**: JSONC comments (`//` and `/* */`) are accepted around values and before a closing bracket, and so is a trailing comma after the last item or member (`[1, 2,]`). The same parser reads JSON and JSONC, including the stringifier's `jsonc: true` output.
219
+ - **Byte order mark**: a UTF-8 BOM at the very start of the input is ignored, as RFC 8259 section 8.1 allows.
220
+ - **Separators**: commas and colons are not validated. Missing, leading or repeated commas (`[1 2]`, `[,1]`, `[1,,2]`) and a missing colon (`{"a" 1}`) are accepted.
221
+ - **Trailing content**: only the first value is read. Anything after it is not checked (`{} x` reads `{}`, and `truex` reads `true`).
222
+ - **Numbers**: the number grammar is not enforced. Leading zeros (`01`) and a trailing decimal point (`1.`) are accepted, and malformed numbers such as `-` or `1e` read as `NaN`. Numbers are JavaScript numbers, so integers beyond 2^53 lose precision and exponents that overflow become `Infinity`, as with `JSON.parse`.
223
+ - **Strings**: unescaped control characters (such as a raw tab or newline) are accepted. Unknown escapes (`\x`) are dropped, and a `\u` escape is not checked for valid hex digits. Invalid UTF-8 and lone surrogate escapes (`\ud800`) are replaced with U+FFFD.
224
+ - **Duplicate keys**: the last member with a given name wins, as with `JSON.parse`. RFC 8259 leaves the behaviour undefined.
225
+ - **Nesting**: parsing is recursive. Thousands of levels of nesting work, but extremely deep input (around 10,000 levels) throws a `RangeError`, as `JSON.parse` does.
226
+
227
+ ### Writer defaults
228
+
229
+ - **Escaping**: `"`, `\\` and control characters are escaped (using `\n`, `\t` and so on where available, otherwise `\u00XX`). `/` and non-ASCII characters, including U+2028 and U+2029, are written as-is.
230
+ - **Lone surrogates**: unpaired surrogates in strings are written as-is, and `jsonStreamStringifyBytes` encodes them as U+FFFD. `JSON.stringify` escapes them (`\ud800`) instead.
231
+ - **Values with no JSON representation**: as with `JSON.stringify`, `NaN` and `±Infinity` are written as `null`. `undefined`, functions and symbols are left out of objects and written as `null` in arrays, and at the top level produce no output. A BigInt throws a `TypeError` unless `toJSON` or the replacer converts it.
232
+ - **Replacer**: as with `JSON.stringify`, a function is called with each key and value (with the containing object as `this`) after `toJSON`, and an array lists the object properties to write.
233
+ - **`toJSON` and `toString`**: a `toJSON()` method is used when present. Otherwise an object with its own `toString()` (anything but the default `Object` and `Array` ones) is written as that string, for example class instances and boxed numbers (`new Number(5)` gives `"5"`). `JSON.stringify` would write their properties or the number.
234
+ - **Indentation**: `indent` is a number of spaces. Strings such as `'\t'` are not supported.
235
+ - **JSONC**: `jsonc: true` adds a trailing comma after the last item of every object and array, which is not valid JSON, and `comments` writes comments when indenting.
236
+ - **Circular references**: these are not detected and overflow the stack (`RangeError`). `JSON.stringify` throws a `TypeError`.
237
+
212
238
  ## API Reference
213
239
 
214
240
  See [docs](https://jacobshirley.github.io/json-stream-lite/v1).
215
241
 
242
+ ### JSON Lines (JSONL / NDJSON)
243
+
244
+ ```typescript
245
+ import { JsonLines } from 'json-stream-lite'
246
+
247
+ // Parse lazily, one value per line (blank lines are skipped)
248
+ for (const line of new JsonLines('{"a":1}\n{"a":2}\n')) {
249
+ console.log(line.readValue())
250
+ }
251
+
252
+ // Async streaming from any byte/string stream
253
+ const response = await fetch('https://api.example.com/data.jsonl')
254
+ for await (const line of new JsonLines(response.body!)) {
255
+ console.log(await line.readValueAsync())
256
+ }
257
+
258
+ // Stringify: one compact value per line, newline-terminated
259
+ // (values with no JSON representation, e.g. undefined, are written as null)
260
+ for (const chunk of JsonLines.stringify([{ a: 1 }, { a: 2 }])) {
261
+ process.stdout.write(chunk)
262
+ }
263
+ ```
264
+
265
+ By default the parser is lenient: blank lines are ignored and several values may share a line. Set `lines.strict = true` on a `JsonLines` instance to reject both, as the [JSON Lines](https://jsonlines.org/) format requires.
266
+
267
+ Also available: `JsonLines.stringifyBytes`, `JsonLines.stringifyAsync` (accepts sync or async iterables) and `JsonLines.stringifyBytesAsync`, plus the equivalent standalone functions `jsonLinesStringify`, `jsonLinesStringifyBytes`, `jsonLinesStringifyAsync` and `jsonLinesStringifyBytesAsync`.
268
+
216
269
  ## Advanced Usage
217
270
 
218
271
  ### Processing Large Files
@@ -20,6 +20,8 @@ export declare class ByteBuffer {
20
20
  protected outputOffset: number;
21
21
  /** Buffer holding input items */
22
22
  protected buffer: number[];
23
+ /** Whether the start of the input has been checked for a byte order mark */
24
+ private bomChecked;
23
25
  /** Optional async iterable input source */
24
26
  protected asyncIterable?: ByteStream;
25
27
  /** Cached sync iterator */
@@ -66,6 +68,14 @@ export declare class ByteBuffer {
66
68
  * @returns True if no more input is available
67
69
  */
68
70
  atEof(): boolean;
71
+ /**
72
+ * Drops a UTF-8 byte order mark (EF BB BF) from the very start of the
73
+ * input. RFC 8259 section 8.1 lets parsers ignore one.
74
+ *
75
+ * @throws NoMoreTokensError if the input might start with a byte order mark
76
+ * but too few bytes have arrived to tell
77
+ */
78
+ private skipByteOrderMark;
69
79
  /**
70
80
  * Peeks at an item in the buffer without consuming it.
71
81
  *
@@ -98,6 +108,7 @@ export declare class ByteBuffer {
98
108
  /**
99
109
  * Override to customize when to compact the buffer
100
110
  * By default, compacts when more than maxBufferSize bytes have been consumed
111
+ * and the consumed part is at least half the buffer
101
112
  *
102
113
  * @returns boolean indicating whether to compact the buffer
103
114
  */
@@ -42,6 +42,8 @@ export class ByteBuffer {
42
42
  outputOffset = 0;
43
43
  /** Buffer holding input items */
44
44
  buffer = [];
45
+ /** Whether the start of the input has been checked for a byte order mark */
46
+ bomChecked = false;
45
47
  /** Optional async iterable input source */
46
48
  asyncIterable;
47
49
  /** Cached sync iterator */
@@ -100,8 +102,16 @@ export class ByteBuffer {
100
102
  if (!this.asyncIterator) {
101
103
  this.asyncIterator = this.asyncIterable[Symbol.asyncIterator]();
102
104
  }
105
+ // Everything from bufferIndex on is parsed again after this read; when
106
+ // readAsync() retries a whole document that is all of it. Reading at
107
+ // least that many new bytes grows the buffer geometrically, so a large
108
+ // document is re-parsed O(log n) times instead of once per chunk.
109
+ const pending = this.length - this.bufferIndex;
110
+ const target = this.allowBufferToBeExceeded
111
+ ? Math.max(this.maxBufferSize, this.length + pending)
112
+ : this.maxBufferSize;
103
113
  let processed = false;
104
- while (this.length < this.maxBufferSize || !processed) {
114
+ while (this.length < target || !processed) {
105
115
  processed = true;
106
116
  const next = await this.asyncIterator.next();
107
117
  if (next.done) {
@@ -171,6 +181,35 @@ export class ByteBuffer {
171
181
  atEof() {
172
182
  return this.eof && this.atEnd();
173
183
  }
184
+ /**
185
+ * Drops a UTF-8 byte order mark (EF BB BF) from the very start of the
186
+ * input. RFC 8259 section 8.1 lets parsers ignore one.
187
+ *
188
+ * @throws NoMoreTokensError if the input might start with a byte order mark
189
+ * but too few bytes have arrived to tell
190
+ */
191
+ skipByteOrderMark() {
192
+ const BOM = [0xef, 0xbb, 0xbf];
193
+ while (this.buffer.length < BOM.length && !this.eof) {
194
+ if (!this.readStream())
195
+ break;
196
+ }
197
+ for (let i = 0; i < BOM.length; i++) {
198
+ if (i >= this.buffer.length) {
199
+ if (this.eof)
200
+ break;
201
+ throw new NoMoreTokensError('No more items available');
202
+ }
203
+ if (this.buffer[i] !== BOM[i]) {
204
+ this.bomChecked = true;
205
+ return;
206
+ }
207
+ }
208
+ if (this.buffer.length >= BOM.length) {
209
+ this.buffer.splice(0, BOM.length);
210
+ }
211
+ this.bomChecked = true;
212
+ }
174
213
  /**
175
214
  * Peeks at an item in the buffer without consuming it.
176
215
  *
@@ -179,6 +218,8 @@ export class ByteBuffer {
179
218
  * @throws NoMoreTokensError if more input is needed and EOF not signaled
180
219
  */
181
220
  peek(ahead = 0) {
221
+ if (!this.bomChecked)
222
+ this.skipByteOrderMark();
182
223
  const index = this.bufferIndex + ahead;
183
224
  if (index >= this.buffer.length) {
184
225
  if (!this.eof) {
@@ -201,8 +242,10 @@ export class ByteBuffer {
201
242
  * @throws EofReachedError if at EOF and no more items available
202
243
  */
203
244
  next() {
245
+ if (!this.bomChecked)
246
+ this.skipByteOrderMark();
204
247
  if (this.bufferIndex >= this.buffer.length) {
205
- if (this.readStream()) {
248
+ if (!this.eof && this.readStream()) {
206
249
  return this.next();
207
250
  }
208
251
  if (!this.eof) {
@@ -240,11 +283,16 @@ export class ByteBuffer {
240
283
  /**
241
284
  * Override to customize when to compact the buffer
242
285
  * By default, compacts when more than maxBufferSize bytes have been consumed
286
+ * and the consumed part is at least half the buffer
243
287
  *
244
288
  * @returns boolean indicating whether to compact the buffer
245
289
  */
246
290
  canCompact() {
247
- return this.bufferIndex > this.maxBufferSize;
291
+ // Compacting copies everything not yet consumed, so only do it once
292
+ // the consumed part is at least as large: otherwise a large buffered
293
+ // input is copied again every maxBufferSize bytes (quadratic).
294
+ return (this.bufferIndex > this.maxBufferSize &&
295
+ this.bufferIndex * 2 >= this.buffer.length);
248
296
  }
249
297
  /**
250
298
  * Attempts to execute a function, resetting buffer position on failure.
package/dist/parser.d.ts CHANGED
@@ -102,6 +102,18 @@ export declare abstract class JsonEntity<T> {
102
102
  * Skips whitespace characters (and comments when JSONC is enabled) in the buffer.
103
103
  */
104
104
  protected skipWhitespace(): void;
105
+ /**
106
+ * If only whitespace and comments stand between the current position and
107
+ * `close` (a closing bracket), consumes up to and including `close`.
108
+ * Otherwise consumes nothing, so comments before a value stay available
109
+ * through its `preComments`.
110
+ *
111
+ * This lets a collection end after a trailing comma (JSONC) or a comment.
112
+ *
113
+ * @param close - The closing bracket byte
114
+ * @returns True if the closing bracket was consumed
115
+ */
116
+ protected consumeClosing(close: number): boolean;
105
117
  /**
106
118
  * Reads and parses the entity, consuming it in the process.
107
119
  *
@@ -124,6 +136,16 @@ export declare abstract class JsonEntity<T> {
124
136
  * Asynchronously consumes the entity by reading it if not already consumed.
125
137
  */
126
138
  consumeAsync(): Promise<void>;
139
+ /**
140
+ * Advances a restartable item generator (such as `items()` or
141
+ * `members()`), reading more input until the next item has started.
142
+ *
143
+ * @param generator - The generator to advance
144
+ * @param restart - Creates a fresh generator after a failed attempt; the
145
+ * buffer has been rewound to the same item boundary
146
+ * @returns The generator's next result
147
+ */
148
+ protected nextAsync<I>(generator: Generator<I>, restart: () => Generator<I>): Promise<IteratorResult<I>>;
127
149
  /**
128
150
  * Attempts to parse by executing a callback, reverting buffer state on failure.
129
151
  *
@@ -180,6 +202,7 @@ export declare class JsonComment extends JsonEntity<string> {
180
202
  get postComments(): Generator<JsonComment>;
181
203
  }
182
204
  export declare class JsonString<T extends string = string> extends JsonEntity<T> {
205
+ private midString;
183
206
  /**
184
207
  * Parses a JSON string from the buffer.
185
208
  *
@@ -194,6 +217,12 @@ export declare class JsonString<T extends string = string> extends JsonEntity<T>
194
217
  * @yields Uint8Array chunks containing the unescaped string bytes
195
218
  */
196
219
  streamBytes(chunkSize?: number): Generator<Uint8Array>;
220
+ /**
221
+ * If `charCode` is a high surrogate and the next six bytes are a `\uXXXX`
222
+ * escape for a low surrogate, returns that low surrogate without
223
+ * consuming anything.
224
+ */
225
+ private peekLowSurrogateEscape;
197
226
  /**
198
227
  * Async generator that yields the string content as raw byte chunks from a stream.
199
228
  * Handles escape sequences by converting them to their actual byte values.
@@ -203,6 +232,16 @@ export declare class JsonString<T extends string = string> extends JsonEntity<T>
203
232
  * @yields Uint8Array chunks containing the unescaped string bytes
204
233
  */
205
234
  streamBytesAsync(chunkSize?: number): AsyncGenerator<Uint8Array>;
235
+ /**
236
+ * Asynchronously reads the string from a stream.
237
+ *
238
+ * Reads through {@link streamBytesAsync}, which resumes mid-string when
239
+ * more input is needed, so a long string split across many chunks is
240
+ * not re-parsed from its opening quote on every refill.
241
+ *
242
+ * @returns A promise that resolves to the parsed string value
243
+ */
244
+ readAsync(): Promise<T>;
206
245
  /**
207
246
  * Generator that yields the string content as chunks of strings.
208
247
  *
@@ -366,6 +405,16 @@ export declare class JsonObject<T extends object = any> extends JsonEntity<T> {
366
405
  * @yields Object containing the key and value entities for each member
367
406
  */
368
407
  membersAsync(): AsyncGenerator<JsonObjectMember<T>>;
408
+ /**
409
+ * Asynchronously reads the whole object from a stream.
410
+ *
411
+ * Reads member by member through {@link membersAsync}, so when more
412
+ * input is needed only the current member is parsed again, not the
413
+ * whole object.
414
+ *
415
+ * @returns A promise that resolves to the parsed object
416
+ */
417
+ readAsync(): Promise<T>;
369
418
  /**
370
419
  * Returns an iterator for object members.
371
420
  * Enables use of for...of loops on JsonObject.
@@ -404,6 +453,15 @@ export declare class JsonArray<T = any> extends JsonEntity<T[]> {
404
453
  * @yields Each item entity in the array
405
454
  */
406
455
  itemsAsync(): AsyncGenerator<JsonValue<T>>;
456
+ /**
457
+ * Asynchronously reads the whole array from a stream.
458
+ *
459
+ * Reads item by item through {@link itemsAsync}, so when more input is
460
+ * needed only the current item is parsed again, not the whole array.
461
+ *
462
+ * @returns A promise that resolves to the parsed array
463
+ */
464
+ readAsync(): Promise<T[]>;
407
465
  /**
408
466
  * Returns an iterator for array items.
409
467
  * Enables use of for...of loops on JsonArray.
@@ -421,6 +479,95 @@ export declare class JsonArray<T = any> extends JsonEntity<T[]> {
421
479
  */
422
480
  protected parse(): T[];
423
481
  }
482
+ /**
483
+ * Represents a JSON Lines (JSONL / NDJSON) document: a sequence of JSON values
484
+ * separated by newlines. Provides streaming access to each line's value.
485
+ *
486
+ * @typeParam T - The expected type of each line's value
487
+ */
488
+ export declare class JsonLines<T = any> extends JsonEntity<T[]> {
489
+ private valuesRead;
490
+ /**
491
+ * When false (default), blank lines are silently ignored and several
492
+ * values may share a line. When true, the input must follow the JSON Lines
493
+ * format exactly: one value per line, no blank lines, and nothing after the
494
+ * final line terminator. Violations throw an Error.
495
+ */
496
+ strict: boolean;
497
+ /**
498
+ * Generator that yields one JsonValue per line. Blank lines are skipped
499
+ * unless `strict` is set.
500
+ *
501
+ * @yields Each value entity in the document
502
+ */
503
+ items(): Generator<JsonValue<T>>;
504
+ /**
505
+ * Async generator that yields one JsonValue per line from a stream.
506
+ *
507
+ * @yields Each value entity in the document
508
+ */
509
+ itemsAsync(): AsyncGenerator<JsonValue<T>>;
510
+ /**
511
+ * Enables use of for...of loops on JsonLines.
512
+ */
513
+ [Symbol.iterator](): Generator<JsonValue<T, string>, any, any>;
514
+ /**
515
+ * Enables use of for await...of loops on JsonLines.
516
+ */
517
+ [Symbol.asyncIterator](): AsyncGenerator<JsonValue<T, string>, any, any>;
518
+ /**
519
+ * Parses the entire document into an array of values.
520
+ *
521
+ * @returns The parsed values, one per line
522
+ */
523
+ protected parse(): T[];
524
+ /**
525
+ * Serializes values as JSON Lines (JSONL / NDJSON) using json-stream-lite.
526
+ * See `jsonLinesStringify` for more details.
527
+ * @param indent - Ignored: JSON Lines output is never indented
528
+ * @returns A generator yielding JSON Lines string chunks
529
+ */
530
+ static stringify(values: Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<string>;
531
+ /**
532
+ * Serializes values as JSON Lines as Uint8Array byte chunks using json-stream-lite.
533
+ * See `jsonLinesStringifyBytes` for more details.
534
+ * @param indent - Ignored: JSON Lines output is never indented
535
+ * @returns A generator yielding JSON Lines byte chunks
536
+ */
537
+ static stringifyBytes(values: Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<Uint8Array>;
538
+ /**
539
+ * Asynchronously serializes values as JSON Lines using json-stream-lite.
540
+ * See `jsonLinesStringifyAsync` for more details.
541
+ * @param indent - Ignored: JSON Lines output is never indented
542
+ * @returns An async generator yielding JSON Lines string chunks
543
+ * */
544
+ static stringifyAsync(values: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<string>;
545
+ /**
546
+ * Asynchronously serializes values as JSON Lines as Uint8Array byte chunks using json-stream-lite.
547
+ * See `jsonLinesStringifyBytesAsync` for more details.
548
+ * @param indent - Ignored: JSON Lines output is never indented
549
+ * @returns An async generator yielding JSON Lines byte chunks
550
+ * */
551
+ static stringifyBytesAsync(values: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<Uint8Array>;
552
+ /**
553
+ * Asynchronously reads the entire document into an array of values.
554
+ *
555
+ * Reads line by line: a value that is fully buffered is read
556
+ * synchronously, one that is not is read incrementally, so a refill
557
+ * re-parses at most the unfinished value and the buffer stays near
558
+ * `maxBufferSize`. Retrying the whole document instead would re-run the
559
+ * strict-mode checks with a stale line count.
560
+ *
561
+ * @returns The parsed values, one per line
562
+ */
563
+ readAsync(): Promise<T[]>;
564
+ /**
565
+ * Reads the entire document into an array of values.
566
+ *
567
+ * @returns The parsed values, one per line
568
+ */
569
+ read(): T[];
570
+ }
424
571
  /**
425
572
  * Parser that flattens nested JSON structures into key-value pairs.
426
573
  * Useful for extracting specific values from complex JSON without parsing the entire structure.