json-stream-lite 1.0.0
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 +528 -0
- package/dist/byte-buffer.d.ts +76 -0
- package/dist/byte-buffer.js +175 -0
- package/dist/generators.d.ts +3 -0
- package/dist/generators.js +51 -0
- package/dist/incremental-parser.d.ts +103 -0
- package/dist/incremental-parser.js +184 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/json-key-value-pair.d.ts +6 -0
- package/dist/json-key-value-pair.js +8 -0
- package/dist/json-parser.d.ts +64 -0
- package/dist/json-parser.js +428 -0
- package/dist/parser.d.ts +67 -0
- package/dist/parser.js +453 -0
- package/dist/stringify.d.ts +6 -0
- package/dist/stringify.js +92 -0
- package/dist/types.d.ts +3 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +3 -0
- package/dist/utils.js +10 -0
- package/package.json +39 -0
package/README.md
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
# json-stream-lite
|
|
2
|
+
|
|
3
|
+
A lightweight, memory-efficient streaming JSON parser and stringifier for JavaScript and TypeScript. Process large JSON files without loading them entirely into memory.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🚀 **Stream parsing**: Parse JSON incrementally as data arrives
|
|
8
|
+
- 💾 **Memory efficient**: Process large JSON files without loading them entirely into memory
|
|
9
|
+
- 🔄 **Bidirectional**: Both parse and stringify JSON in streaming fashion
|
|
10
|
+
- 🎯 **Type-safe**: Full TypeScript support with comprehensive type definitions
|
|
11
|
+
- 🔌 **Flexible input**: Support for sync/async iterables, ReadableStreams, strings, and byte arrays
|
|
12
|
+
- 🎨 **Key-value extraction**: Flatten nested JSON structures into key-value pairs
|
|
13
|
+
- âš¡ **Zero dependencies**: Minimal footprint with no external runtime dependencies
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install json-stream-lite
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pnpm add json-stream-lite
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
yarn add json-stream-lite
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
### Parsing JSON
|
|
32
|
+
|
|
33
|
+
#### Parse a complete JSON object incrementally
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import { JsonObject } from 'json-stream-lite'
|
|
37
|
+
|
|
38
|
+
const json = '{"name": "Alice", "age": 30, "active": true}'
|
|
39
|
+
const parser = new JsonObject()
|
|
40
|
+
|
|
41
|
+
// Feed bytes into the parser
|
|
42
|
+
parser.feed(...new TextEncoder().encode(json))
|
|
43
|
+
|
|
44
|
+
// Read the complete object
|
|
45
|
+
const result = parser.read()
|
|
46
|
+
console.log(result) // { name: 'Alice', age: 30, active: true }
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
#### Stream through object members
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { JsonObject } from 'json-stream-lite'
|
|
53
|
+
|
|
54
|
+
const json = '{"name": "Alice", "age": 30, "city": "NYC"}'
|
|
55
|
+
const parser = new JsonObject()
|
|
56
|
+
parser.feed(...new TextEncoder().encode(json))
|
|
57
|
+
|
|
58
|
+
// Iterate through key-value pairs without loading the entire object
|
|
59
|
+
for (const [keyEntity, valueEntity] of parser.members()) {
|
|
60
|
+
const key = keyEntity.read()
|
|
61
|
+
const value = valueEntity.read().read()
|
|
62
|
+
console.log(`${key}: ${value}`)
|
|
63
|
+
}
|
|
64
|
+
// Output:
|
|
65
|
+
// name: Alice
|
|
66
|
+
// age: 30
|
|
67
|
+
// city: NYC
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
#### Parse JSON arrays incrementally
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
import { JsonArray } from 'json-stream-lite'
|
|
74
|
+
|
|
75
|
+
const json = '[1, 2, 3, 4, 5]'
|
|
76
|
+
const parser = new JsonArray()
|
|
77
|
+
parser.feed(...new TextEncoder().encode(json))
|
|
78
|
+
|
|
79
|
+
// Process each item individually
|
|
80
|
+
for (const item of parser.items()) {
|
|
81
|
+
console.log(item.read())
|
|
82
|
+
}
|
|
83
|
+
// Output: 1, 2, 3, 4, 5
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Async Streaming
|
|
87
|
+
|
|
88
|
+
Process JSON from async sources like HTTP responses or file streams:
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
import { JsonObject } from 'json-stream-lite'
|
|
92
|
+
|
|
93
|
+
async function processStream(stream: ReadableStream<Uint8Array>) {
|
|
94
|
+
const parser = new JsonObject(stream)
|
|
95
|
+
|
|
96
|
+
// Asynchronously iterate through members
|
|
97
|
+
for await (const [keyEntity, valueEntity] of parser.membersAsync()) {
|
|
98
|
+
const key = keyEntity.read()
|
|
99
|
+
const value = await valueEntity.readValueAsync()
|
|
100
|
+
console.log(`${key}: ${value}`)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Example with fetch
|
|
105
|
+
const response = await fetch('https://api.example.com/data.json')
|
|
106
|
+
await processStream(response.body!)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Key-Value Extraction
|
|
110
|
+
|
|
111
|
+
Flatten nested JSON structures into dot-notation key-value pairs:
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
import { jsonKeyValueParser } from 'json-stream-lite'
|
|
115
|
+
|
|
116
|
+
const json = '{"user": {"name": "Alice", "scores": [95, 87, 92]}}'
|
|
117
|
+
|
|
118
|
+
for (const [key, value] of jsonKeyValueParser(json)) {
|
|
119
|
+
console.log(`${key} = ${value}`)
|
|
120
|
+
}
|
|
121
|
+
// Output:
|
|
122
|
+
// user.name = Alice
|
|
123
|
+
// user.scores[0] = 95
|
|
124
|
+
// user.scores[1] = 87
|
|
125
|
+
// user.scores[2] = 92
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
#### Async key-value extraction
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
import { jsonKeyValueParserAsync } from 'json-stream-lite'
|
|
132
|
+
|
|
133
|
+
async function extractKeyValues(stream: ReadableStream) {
|
|
134
|
+
for await (const [key, value] of jsonKeyValueParserAsync(stream)) {
|
|
135
|
+
console.log(`${key} = ${value}`)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Stringifying JSON
|
|
141
|
+
|
|
142
|
+
Convert JavaScript objects to JSON strings in a streaming fashion:
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
import { jsonStreamStringify } from 'json-stream-lite'
|
|
146
|
+
|
|
147
|
+
const data = {
|
|
148
|
+
name: 'Alice',
|
|
149
|
+
scores: [95, 87, 92],
|
|
150
|
+
metadata: { verified: true },
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Generate JSON in chunks
|
|
154
|
+
for (const chunk of jsonStreamStringify(data, null, 2)) {
|
|
155
|
+
process.stdout.write(chunk)
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
#### Stringify to bytes
|
|
160
|
+
|
|
161
|
+
```typescript
|
|
162
|
+
import { jsonStreamStringifyBytes } from 'json-stream-lite'
|
|
163
|
+
|
|
164
|
+
const data = { name: 'Alice', age: 30 }
|
|
165
|
+
|
|
166
|
+
for (const bytes of jsonStreamStringifyBytes(data)) {
|
|
167
|
+
// bytes is a Uint8Array
|
|
168
|
+
await writeToFile(bytes)
|
|
169
|
+
}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
#### Control chunk size
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { jsonStreamStringify } from 'json-stream-lite'
|
|
176
|
+
|
|
177
|
+
const data = { longString: 'x'.repeat(10000) }
|
|
178
|
+
|
|
179
|
+
// Control how strings are chunked (default: 1024 bytes)
|
|
180
|
+
for (const chunk of jsonStreamStringify(data, null, 0, {
|
|
181
|
+
stringChunkSize: 512,
|
|
182
|
+
})) {
|
|
183
|
+
console.log(chunk.length) // Chunks will be ~512 bytes
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
## API Reference
|
|
188
|
+
|
|
189
|
+
### Parser Classes
|
|
190
|
+
|
|
191
|
+
#### `JsonValue`
|
|
192
|
+
|
|
193
|
+
Represents any JSON value. Automatically detects the type and returns the appropriate entity.
|
|
194
|
+
|
|
195
|
+
```typescript
|
|
196
|
+
import { JsonValue } from 'json-stream-lite'
|
|
197
|
+
|
|
198
|
+
const parser = new JsonValue()
|
|
199
|
+
parser.feed(...bytes)
|
|
200
|
+
const valueEntity = parser.read() // Returns JsonString, JsonNumber, etc.
|
|
201
|
+
const actualValue = valueEntity.read()
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
#### `JsonObject`
|
|
205
|
+
|
|
206
|
+
Parses JSON objects.
|
|
207
|
+
|
|
208
|
+
```typescript
|
|
209
|
+
class JsonObject<T = unknown> extends JsonEntity<T>
|
|
210
|
+
|
|
211
|
+
// Methods
|
|
212
|
+
members(): Generator<[JsonString, JsonValue]>
|
|
213
|
+
membersAsync(): AsyncGenerator<[JsonString, JsonValue]>
|
|
214
|
+
read(): T
|
|
215
|
+
readAsync(): Promise<T>
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
#### `JsonArray`
|
|
219
|
+
|
|
220
|
+
Parses JSON arrays.
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
class JsonArray<T = unknown> extends JsonEntity<T[]>
|
|
224
|
+
|
|
225
|
+
// Methods
|
|
226
|
+
items(): Generator<JsonValueType>
|
|
227
|
+
itemsAsync(): AsyncGenerator<JsonValueType>
|
|
228
|
+
read(): T[]
|
|
229
|
+
readAsync(): Promise<T[]>
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
#### `JsonString`, `JsonNumber`, `JsonBoolean`, `JsonNull`
|
|
233
|
+
|
|
234
|
+
Parse primitive JSON values.
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
const str = new JsonString()
|
|
238
|
+
str.feed(...bytes)
|
|
239
|
+
console.log(str.read()) // Returns a string
|
|
240
|
+
|
|
241
|
+
const num = new JsonNumber()
|
|
242
|
+
num.feed(...bytes)
|
|
243
|
+
console.log(num.read()) // Returns a number
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
#### `JsonKeyValueParser`
|
|
247
|
+
|
|
248
|
+
Flattens nested JSON into key-value pairs.
|
|
249
|
+
|
|
250
|
+
```typescript
|
|
251
|
+
class JsonKeyValueParser extends JsonEntity<Generator<JsonKeyValuePair>>
|
|
252
|
+
|
|
253
|
+
// Methods
|
|
254
|
+
parse(): Generator<[string, JsonPrimitive]>
|
|
255
|
+
parseAsync(): AsyncGenerator<[string, JsonPrimitive]>
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### Base Class: `JsonEntity`
|
|
259
|
+
|
|
260
|
+
All parser classes extend `JsonEntity<T>`:
|
|
261
|
+
|
|
262
|
+
```typescript
|
|
263
|
+
// Properties
|
|
264
|
+
consumed: boolean
|
|
265
|
+
bufferLength: number
|
|
266
|
+
maxBufferSize: number
|
|
267
|
+
|
|
268
|
+
// Methods
|
|
269
|
+
feed(...input: (number | number[])[]): void
|
|
270
|
+
read(): T
|
|
271
|
+
readAsync(): Promise<T>
|
|
272
|
+
consume(): void
|
|
273
|
+
consumeAsync(): Promise<void>
|
|
274
|
+
tryParse<T>(cb: (entity: this) => T): T | undefined
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
### Generator Functions
|
|
278
|
+
|
|
279
|
+
#### `jsonKeyValueParser(bytes: Iterable<number> | string)`
|
|
280
|
+
|
|
281
|
+
Synchronously parse JSON into key-value pairs.
|
|
282
|
+
|
|
283
|
+
```typescript
|
|
284
|
+
import { jsonKeyValueParser } from 'json-stream-lite'
|
|
285
|
+
|
|
286
|
+
for (const [key, value] of jsonKeyValueParser('{"a": 1, "b": [2, 3]}')) {
|
|
287
|
+
console.log(key, value)
|
|
288
|
+
}
|
|
289
|
+
// a 1
|
|
290
|
+
// b[0] 2
|
|
291
|
+
// b[1] 3
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
#### `jsonKeyValueParserAsync(bytes: AsyncIterable<number> | ReadableStream | string)`
|
|
295
|
+
|
|
296
|
+
Asynchronously parse JSON into key-value pairs.
|
|
297
|
+
|
|
298
|
+
```typescript
|
|
299
|
+
import { jsonKeyValueParserAsync } from 'json-stream-lite'
|
|
300
|
+
|
|
301
|
+
for await (const [key, value] of jsonKeyValueParserAsync(stream)) {
|
|
302
|
+
console.log(key, value)
|
|
303
|
+
}
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
### Stringify Functions
|
|
307
|
+
|
|
308
|
+
#### `jsonStreamStringify(value, replacer?, indent?, options?)`
|
|
309
|
+
|
|
310
|
+
Generate JSON string chunks.
|
|
311
|
+
|
|
312
|
+
```typescript
|
|
313
|
+
function jsonStreamStringify(
|
|
314
|
+
value: unknown,
|
|
315
|
+
replacer?: any,
|
|
316
|
+
indent?: number,
|
|
317
|
+
options?: JsonStreamStringifyOptions,
|
|
318
|
+
): Generator<string>
|
|
319
|
+
|
|
320
|
+
interface JsonStreamStringifyOptions {
|
|
321
|
+
stringChunkSize?: number // Default: 1024
|
|
322
|
+
}
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
**Parameters:**
|
|
326
|
+
|
|
327
|
+
- `value`: The value to stringify
|
|
328
|
+
- `replacer`: Optional replacer function (like `JSON.stringify`)
|
|
329
|
+
- `indent`: Number of spaces for indentation (0 for compact)
|
|
330
|
+
- `options.stringChunkSize`: Maximum size of string chunks in bytes
|
|
331
|
+
|
|
332
|
+
#### `jsonStreamStringifyBytes(value, replacer?, indent?, options?)`
|
|
333
|
+
|
|
334
|
+
Generate JSON as Uint8Array chunks.
|
|
335
|
+
|
|
336
|
+
```typescript
|
|
337
|
+
function jsonStreamStringifyBytes(
|
|
338
|
+
value: unknown,
|
|
339
|
+
replacer?: any,
|
|
340
|
+
indent?: number,
|
|
341
|
+
options?: JsonStreamStringifyOptions,
|
|
342
|
+
): Generator<Uint8Array>
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
## Advanced Usage
|
|
346
|
+
|
|
347
|
+
### Processing Large Files
|
|
348
|
+
|
|
349
|
+
```typescript
|
|
350
|
+
import { createReadStream } from 'fs'
|
|
351
|
+
import { JsonObject } from 'json-stream-lite'
|
|
352
|
+
|
|
353
|
+
async function processLargeFile(filePath: string) {
|
|
354
|
+
const stream = createReadStream(filePath)
|
|
355
|
+
const parser = new JsonObject(stream)
|
|
356
|
+
|
|
357
|
+
for await (const [keyEntity, valueEntity] of parser) {
|
|
358
|
+
const key = keyEntity.read()
|
|
359
|
+
const value = await valueEntity.readValueAsync()
|
|
360
|
+
|
|
361
|
+
// Process each key-value pair without loading entire file
|
|
362
|
+
await processRecord(key, value)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
### Handling Nested Structures
|
|
368
|
+
|
|
369
|
+
```typescript
|
|
370
|
+
import { JsonObject, JsonArray } from 'json-stream-lite'
|
|
371
|
+
|
|
372
|
+
const json = '{"users": [{"name": "Alice"}, {"name": "Bob"}]}'
|
|
373
|
+
const parser = new JsonObject()
|
|
374
|
+
parser.feed(...new TextEncoder().encode(json))
|
|
375
|
+
|
|
376
|
+
for (const [keyEntity, valueEntity] of parser) {
|
|
377
|
+
const key = keyEntity.read()
|
|
378
|
+
const value = valueEntity.read()
|
|
379
|
+
|
|
380
|
+
if (key === 'users' && value instanceof JsonArray) {
|
|
381
|
+
for (const userEntity of value.items()) {
|
|
382
|
+
const user = userEntity.read()
|
|
383
|
+
console.log(user) // Each user object
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
### Incremental Feeding
|
|
390
|
+
|
|
391
|
+
```typescript
|
|
392
|
+
import { JsonObject } from 'json-stream-lite'
|
|
393
|
+
|
|
394
|
+
const parser = new JsonObject()
|
|
395
|
+
|
|
396
|
+
// Feed data incrementally as it arrives
|
|
397
|
+
parser.feed(123) // {
|
|
398
|
+
parser.feed(34, 110, 97, 109, 101, 34) // "name"
|
|
399
|
+
parser.feed(58, 34, 65, 108, 105, 99, 101, 34) // :"Alice"
|
|
400
|
+
parser.feed(125) // }
|
|
401
|
+
|
|
402
|
+
const result = parser.read()
|
|
403
|
+
console.log(result) // { name: 'Alice' }
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
## Use Cases
|
|
407
|
+
|
|
408
|
+
### 1. Processing API Responses
|
|
409
|
+
|
|
410
|
+
```typescript
|
|
411
|
+
async function processApiResponse(url: string) {
|
|
412
|
+
const response = await fetch(url)
|
|
413
|
+
const parser = new JsonObject(response.body!)
|
|
414
|
+
|
|
415
|
+
for await (const [keyEntity, valueEntity] of parser.membersAsync()) {
|
|
416
|
+
const key = keyEntity.read()
|
|
417
|
+
const value = await valueEntity.readValueAsync()
|
|
418
|
+
console.log(`Processing ${key}:`, value)
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
### 2. Log File Analysis
|
|
424
|
+
|
|
425
|
+
```typescript
|
|
426
|
+
import { jsonKeyValueParserAsync } from 'json-stream-lite'
|
|
427
|
+
|
|
428
|
+
async function analyzeLogFile(stream: ReadableStream) {
|
|
429
|
+
const metrics: Record<string, number> = {}
|
|
430
|
+
|
|
431
|
+
for await (const [key, value] of jsonKeyValueParserAsync(stream)) {
|
|
432
|
+
if (typeof value === 'number') {
|
|
433
|
+
metrics[key] = (metrics[key] || 0) + value
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return metrics
|
|
438
|
+
}
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
### 3. Generating Large JSON Files
|
|
442
|
+
|
|
443
|
+
```typescript
|
|
444
|
+
import { jsonStreamStringifyBytes } from 'json-stream-lite'
|
|
445
|
+
import { createWriteStream } from 'fs'
|
|
446
|
+
|
|
447
|
+
async function generateLargeFile(data: unknown, outputPath: string) {
|
|
448
|
+
const writeStream = createWriteStream(outputPath)
|
|
449
|
+
|
|
450
|
+
for (const chunk of jsonStreamStringifyBytes(data, null, 2)) {
|
|
451
|
+
writeStream.write(chunk)
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
writeStream.end()
|
|
455
|
+
}
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
### 4. Database Export
|
|
459
|
+
|
|
460
|
+
```typescript
|
|
461
|
+
import { jsonStreamStringify } from 'json-stream-lite'
|
|
462
|
+
|
|
463
|
+
async function* exportDatabase(query: string) {
|
|
464
|
+
const records = await db.query(query)
|
|
465
|
+
|
|
466
|
+
for (const chunk of jsonStreamStringify(records, null, 2)) {
|
|
467
|
+
yield chunk
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// Stream to client
|
|
472
|
+
app.get('/export', async (req, res) => {
|
|
473
|
+
res.setHeader('Content-Type', 'application/json')
|
|
474
|
+
for await (const chunk of exportDatabase('SELECT * FROM users')) {
|
|
475
|
+
res.write(chunk)
|
|
476
|
+
}
|
|
477
|
+
res.end()
|
|
478
|
+
})
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
## Performance Tips
|
|
482
|
+
|
|
483
|
+
1. **Use async methods** for I/O-bound operations
|
|
484
|
+
2. **Set appropriate buffer limits** with `maxBufferSize`
|
|
485
|
+
3. **Stream member-by-member** instead of calling `read()` on large objects
|
|
486
|
+
4. **Control chunk size** in stringify operations for optimal throughput
|
|
487
|
+
5. **Avoid reading entire objects** when you only need specific fields
|
|
488
|
+
|
|
489
|
+
## Browser Support
|
|
490
|
+
|
|
491
|
+
Works in all modern browsers and Node.js environments that support:
|
|
492
|
+
|
|
493
|
+
- ES2015+ features
|
|
494
|
+
- Generators and async generators
|
|
495
|
+
- TextEncoder/TextDecoder (for string conversion)
|
|
496
|
+
- ReadableStream (for stream processing)
|
|
497
|
+
|
|
498
|
+
## TypeScript Support
|
|
499
|
+
|
|
500
|
+
Full TypeScript definitions included. All types are exported:
|
|
501
|
+
|
|
502
|
+
```typescript
|
|
503
|
+
import type {
|
|
504
|
+
JsonPrimitive,
|
|
505
|
+
JsonKeyValuePair,
|
|
506
|
+
JsonValueType,
|
|
507
|
+
JsonPrimitiveType,
|
|
508
|
+
JsonStreamStringifyOptions,
|
|
509
|
+
} from 'json-stream-lite'
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
## License
|
|
513
|
+
|
|
514
|
+
MIT
|
|
515
|
+
|
|
516
|
+
## Contributing
|
|
517
|
+
|
|
518
|
+
Contributions welcome! Please ensure:
|
|
519
|
+
|
|
520
|
+
- All tests pass: `pnpm test`
|
|
521
|
+
- Code compiles: `pnpm compile`
|
|
522
|
+
- Coverage maintained: `pnpm test -- --coverage`
|
|
523
|
+
|
|
524
|
+
## Related Projects
|
|
525
|
+
|
|
526
|
+
- [json-stream](https://www.npmjs.com/package/json-stream) - Alternative streaming JSON parser
|
|
527
|
+
- [stream-json](https://www.npmjs.com/package/stream-json) - Node.js streaming JSON parser
|
|
528
|
+
- [jsonparse](https://www.npmjs.com/package/jsonparse) - Pure JavaScript streaming JSON parser
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { ByteStream } from './types';
|
|
2
|
+
export declare class NoMoreTokensError extends Error {
|
|
3
|
+
}
|
|
4
|
+
export declare class EofReachedError extends Error {
|
|
5
|
+
}
|
|
6
|
+
export declare class ByteBuffer {
|
|
7
|
+
/** Maximum size of the buffer before compaction */
|
|
8
|
+
maxBufferSize: number;
|
|
9
|
+
/** Whether end of file has been signaled */
|
|
10
|
+
eof: boolean;
|
|
11
|
+
/** Current position in the buffer */
|
|
12
|
+
bufferIndex: number;
|
|
13
|
+
/** Whether the buffer is locked against compaction */
|
|
14
|
+
locked: boolean;
|
|
15
|
+
/** Current position in the input stream */
|
|
16
|
+
protected inputOffset: number;
|
|
17
|
+
/** Number of outputs generated */
|
|
18
|
+
protected outputOffset: number;
|
|
19
|
+
/** Buffer holding input items */
|
|
20
|
+
protected buffer: number[];
|
|
21
|
+
/** Optional async iterable input source */
|
|
22
|
+
protected asyncIterable?: ByteStream;
|
|
23
|
+
constructor(asyncIterable?: ByteStream);
|
|
24
|
+
readStream(): Promise<void>;
|
|
25
|
+
get length(): number;
|
|
26
|
+
/**
|
|
27
|
+
* Feeds input items into the parser buffer.
|
|
28
|
+
*
|
|
29
|
+
* @param input - Input items to add to the buffer
|
|
30
|
+
*/
|
|
31
|
+
feed(...input: (number | number[] | Uint8Array)[]): void;
|
|
32
|
+
/**
|
|
33
|
+
* Checks if end of file has been reached and buffer is exhausted.
|
|
34
|
+
*
|
|
35
|
+
* @returns True if no more input is available
|
|
36
|
+
*/
|
|
37
|
+
atEof(): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Peeks at an item in the buffer without consuming it.
|
|
40
|
+
*
|
|
41
|
+
* @param ahead - Number of positions to look ahead (default: 0)
|
|
42
|
+
* @returns The item at the peek position, or null if at EOF
|
|
43
|
+
* @throws NoMoreTokensError if more input is needed and EOF not signaled
|
|
44
|
+
*/
|
|
45
|
+
peek(ahead?: number): number | null;
|
|
46
|
+
/**
|
|
47
|
+
* Consumes and returns the next item from the buffer.
|
|
48
|
+
*
|
|
49
|
+
* @returns The next item
|
|
50
|
+
* @throws NoMoreTokensError if more input is needed and EOF not signaled
|
|
51
|
+
* @throws EofReachedError if at EOF and no more items available
|
|
52
|
+
*/
|
|
53
|
+
next(): number;
|
|
54
|
+
/**
|
|
55
|
+
* Consumes and validates the next item against an expected type or value.
|
|
56
|
+
*
|
|
57
|
+
* @typeParam T - The expected item type
|
|
58
|
+
* @param itemType - Constructor or value to match against
|
|
59
|
+
* @returns The consumed item cast to the expected type
|
|
60
|
+
* @throws Error if the item doesn't match the expected type/value
|
|
61
|
+
*/
|
|
62
|
+
expect<T extends number>(itemType: T): T;
|
|
63
|
+
/**
|
|
64
|
+
* Compacts the buffer by removing consumed items
|
|
65
|
+
*/
|
|
66
|
+
compact(): void;
|
|
67
|
+
/**
|
|
68
|
+
* Override to customize when to compact the buffer
|
|
69
|
+
* By default, compacts when more than 1000 items have been consumed
|
|
70
|
+
*
|
|
71
|
+
* @returns boolean indicating whether to compact the buffer
|
|
72
|
+
*/
|
|
73
|
+
canCompact(): boolean;
|
|
74
|
+
resetOnFail<T>(tryFn: () => T, onFail?: (e: Error) => void): T | undefined;
|
|
75
|
+
toString(): string;
|
|
76
|
+
}
|