json-stream-lite 1.0.9 → 1.0.11

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/EXAMPLES.md CHANGED
@@ -2,9 +2,16 @@
2
2
 
3
3
  This directory contains example scripts demonstrating how to use the JSON-Stream-Lite library.
4
4
 
5
- ## Helper to convert string to bytes
5
+ ## Basic JSON Parsing Example
6
6
 
7
7
  ```typescript
8
+ /**
9
+ * This example demonstrates how to parse a simple JSON object using json-stream-lite.
10
+ */
11
+
12
+ import { JsonObject, JsonArray, JsonValue } from 'json-stream-lite'
13
+
14
+ // Helper to convert string to bytes
8
15
  function stringToBytes(str: string): number[] {
9
16
  return Array.from(new TextEncoder().encode(str))
10
17
  }
@@ -50,9 +57,21 @@ const value = valueEntity.read()
50
57
  console.log('Result:', value)
51
58
  ```
52
59
 
53
- ## Example 1: Stream through object members
60
+ ## Streaming Object Members Example
54
61
 
55
62
  ```typescript
63
+ /**
64
+ * This example shows how to iterate through object members without loading
65
+ * the entire object into memory at once.
66
+ */
67
+
68
+ import { JsonObject } from 'json-stream-lite'
69
+
70
+ function stringToBytes(str: string): number[] {
71
+ return Array.from(new TextEncoder().encode(str))
72
+ }
73
+
74
+ // Example 1: Stream through object members
56
75
  console.log('=== Example 1: Stream Object Members ===')
57
76
  const userJson =
58
77
  '{"id": 123, "name": "Alice", "email": "alice@example.com", "age": 30}'
@@ -132,9 +151,17 @@ for (const { key: keyEntity, value: valueEntity } of searchParser.members()) {
132
151
  console.log("Early exit - didn't process remaining fields")
133
152
  ```
134
153
 
135
- ## Example 1: Flatten a simple nested object
154
+ ## Key-Value Extraction Example
136
155
 
137
156
  ```typescript
157
+ /**
158
+ * This example demonstrates how to flatten nested JSON structures into
159
+ * key-value pairs using dot notation and array indices.
160
+ */
161
+
162
+ import { jsonKeyValueParser } from 'json-stream-lite'
163
+
164
+ // Example 1: Flatten a simple nested object
138
165
  console.log('=== Example 1: Simple Nested Object ===')
139
166
  const simpleNested = '{"user": {"name": "Alice", "age": 30}}'
140
167
 
@@ -240,9 +267,21 @@ for (const [key, value] of jsonKeyValueParser(arrayStructure)) {
240
267
  // [2][1] = 6
241
268
  ```
242
269
 
243
- ## Helper to simulate an async byte stream
270
+ ## Async Streaming Example
244
271
 
245
272
  ```typescript
273
+ /**
274
+ * This example demonstrates how to process JSON from async sources
275
+ * like streams, fetch responses, or async iterables.
276
+ */
277
+
278
+ import {
279
+ JsonObject,
280
+ JsonArray,
281
+ jsonKeyValueParserAsync,
282
+ } from 'json-stream-lite'
283
+
284
+ // Helper to simulate an async byte stream
246
285
  async function* createAsyncByteStream(
247
286
  json: string,
248
287
  chunkSize: number = 10,
@@ -414,9 +453,17 @@ await processLargeDataset()
414
453
  console.log('\n=== All async examples completed ===')
415
454
  ```
416
455
 
417
- ## Example 1: Basic stringify
456
+ ## JSON Stringify Example
418
457
 
419
458
  ```typescript
459
+ /**
460
+ * This example demonstrates how to convert JavaScript objects to JSON
461
+ * in a streaming fashion, which is useful for large objects.
462
+ */
463
+
464
+ import { jsonStreamStringify, jsonStreamStringifyBytes } from 'json-stream-lite'
465
+
466
+ // Example 1: Basic stringify
420
467
  console.log('=== Example 1: Basic Stringify ===')
421
468
  const simpleObj = {
422
469
  name: 'Alice',
@@ -576,9 +623,21 @@ console.log('Output matches JSON.stringify:', streamResult === standardResult)
576
623
  console.log('Stream result:', streamResult)
577
624
  ```
578
625
 
579
- ## Example 1: Feed bytes one at a time
626
+ ## Incremental Feeding Example
580
627
 
581
628
  ```typescript
629
+ /**
630
+ * This example shows how to feed bytes into the parser incrementally,
631
+ * which is useful when receiving data in chunks from a network or file.
632
+ */
633
+
634
+ import { JsonObject, JsonArray } from 'json-stream-lite'
635
+
636
+ function stringToBytes(str: string): number[] {
637
+ return Array.from(new TextEncoder().encode(str))
638
+ }
639
+
640
+ // Example 1: Feed bytes one at a time
582
641
  console.log('=== Example 1: Feed Bytes One at a Time ===')
583
642
  const json1 = '{"name": "Alice"}'
584
643
  const parser1 = new JsonObject()
@@ -729,9 +788,21 @@ console.log('Result:', result7)
729
788
  console.log('Note: Can feed bytes individually, as arrays, or spread arrays')
730
789
  ```
731
790
 
732
- ## Scenario 1: Processing a configuration file
791
+ ## Real-World Scenarios Example
733
792
 
734
793
  ```typescript
794
+ /**
795
+ * This example demonstrates practical use cases for json-stream-lite
796
+ * in real-world applications.
797
+ */
798
+
799
+ import { JsonObject, JsonArray, jsonKeyValueParser } from 'json-stream-lite'
800
+
801
+ function stringToBytes(str: string): number[] {
802
+ return Array.from(new TextEncoder().encode(str))
803
+ }
804
+
805
+ // Scenario 1: Processing a configuration file
735
806
  console.log('=== Scenario 1: Configuration File Processing ===')
736
807
  function processConfig() {
737
808
  const configJson = JSON.stringify({
package/README.md CHANGED
@@ -109,6 +109,22 @@ const response = await fetch('https://api.example.com/data.json')
109
109
  await processStream(response.body!)
110
110
  ```
111
111
 
112
+ ### Controlling Buffer Size
113
+
114
+ Limit memory usage by setting a maximum buffer size:
115
+
116
+ ```typescript
117
+ import { JsonObject } from 'json-stream-lite'
118
+
119
+ const parser = new JsonObject()
120
+ parser.maxBufferSize = 1024 * 1024 // 1 MB
121
+
122
+ // Feed data into the parser
123
+ parser.feed('...large JSON data...')
124
+ const result = parser.read()
125
+ console.log(result)
126
+ ```
127
+
112
128
  ### Key-Value Extraction
113
129
 
114
130
  Flatten nested JSON structures into dot-notation key-value pairs:
@@ -1,4 +1,4 @@
1
- import { ByteStream } from './types.js';
1
+ import type { ByteStream, JsonStreamInput } from './types.js';
2
2
  export declare class NoMoreTokensError extends Error {
3
3
  }
4
4
  export declare class EofReachedError extends Error {
@@ -28,7 +28,7 @@ export declare class ByteBuffer {
28
28
  *
29
29
  * @param input - Input items to add to the buffer
30
30
  */
31
- feed(...input: (number | number[] | Uint8Array)[]): void;
31
+ feed(...input: JsonStreamInput[]): void;
32
32
  /**
33
33
  * Checks if end of file has been reached and buffer is exhausted.
34
34
  *
@@ -1,11 +1,13 @@
1
1
  import { bytesToString } from './utils.js';
2
+ const textEncoder = new TextEncoder();
3
+ const DEFAULT_MAX_BUFFER_SIZE = 1024 * 100; // 100 KB
2
4
  export class NoMoreTokensError extends Error {
3
5
  }
4
6
  export class EofReachedError extends Error {
5
7
  }
6
8
  export class ByteBuffer {
7
9
  /** Maximum size of the buffer before compaction */
8
- maxBufferSize = 1000;
10
+ maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
9
11
  /** Whether end of file has been signaled */
10
12
  eof = false;
11
13
  /** Current position in the buffer */
@@ -34,7 +36,8 @@ export class ByteBuffer {
34
36
  this.eof = true;
35
37
  break;
36
38
  }
37
- this.feed(nextByte.value);
39
+ const value = nextByte.value;
40
+ this.feed(value);
38
41
  i++;
39
42
  }
40
43
  }
@@ -60,6 +63,13 @@ export class ByteBuffer {
60
63
  }
61
64
  continue;
62
65
  }
66
+ else if (typeof item === 'string') {
67
+ const encoded = textEncoder.encode(item);
68
+ for (const byte of encoded) {
69
+ this.buffer.push(byte);
70
+ }
71
+ continue;
72
+ }
63
73
  this.buffer.push(item);
64
74
  }
65
75
  }
package/dist/parser.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ByteBuffer } from './byte-buffer.js';
2
- import { ByteStream, JsonKeyValuePair } from './types.js';
2
+ import { ByteStream, JsonKeyValuePair, JsonStreamInput } from './types.js';
3
3
  export declare abstract class JsonEntity<T> {
4
4
  consumed: boolean;
5
5
  protected buffer: ByteBuffer;
@@ -7,7 +7,7 @@ export declare abstract class JsonEntity<T> {
7
7
  get entityType(): string;
8
8
  set maxBufferSize(size: number);
9
9
  get bufferLength(): number;
10
- feed(...input: (number | number[])[]): void;
10
+ feed(...input: JsonStreamInput[]): void;
11
11
  protected abstract parse(): T;
12
12
  protected skipWhitespace(): void;
13
13
  read(): T;
package/dist/types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export type ByteStream = AsyncIterable<number | number[] | Uint8Array>;
1
+ export type JsonStreamInput = string | number | number[] | Uint8Array;
2
+ export type ByteStream = AsyncIterable<JsonStreamInput>;
2
3
  export type JsonPrimitive = string | number | boolean | null;
3
4
  export type JsonKeyValuePair = [string, JsonPrimitive];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-stream-lite",
3
- "version": "1.0.9",
3
+ "version": "1.0.11",
4
4
  "description": "A lightweight, memory-efficient, zero-dependency streaming JSON parser and stringifier for JavaScript and TypeScript. It works in both Node.js and browser environments.",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",