json-stream-lite 1.2.1 → 1.3.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/EXAMPLES.md CHANGED
@@ -90,13 +90,13 @@ console.log('\n=== Example 2: Stream Array Items ===')
90
90
  import { JsonArray } from 'json-stream-lite'
91
91
 
92
92
  const numbersJson = '[10, 20, 30, 40, 50]'
93
- const numbersParser = new JsonArray()
93
+ const numbersParser = new JsonArray<number>()
94
94
  numbersParser.feed(...stringToBytes(numbersJson))
95
95
 
96
96
  console.log('Processing items one by one:')
97
97
  let sum = 0
98
98
  for (const item of numbersParser.items()) {
99
- const value = item.read() as number
99
+ const value = item.readValue()
100
100
  sum += value
101
101
  console.log(` Current value: ${value}, Running sum: ${sum}`)
102
102
  }
@@ -326,7 +326,7 @@ async function parseAsyncArray() {
326
326
  console.log('Processing items as they arrive:')
327
327
  let sum = 0
328
328
  for await (const item of parser) {
329
- const value = await item.readAsync()
329
+ const value = await item.readValueAsync()
330
330
  sum += value as number
331
331
  console.log(` Received: ${value}, Running sum: ${sum}`)
332
332
  }
@@ -1167,3 +1167,142 @@ for await (const streamChunk of jsonObject.streamAsync(2)) {
1167
1167
  * Received string chunk: le
1168
1168
  */
1169
1169
  ```
1170
+
1171
+ ## JSON Comments (JSONC) Parsing Example
1172
+
1173
+ ```typescript
1174
+ /**
1175
+ * This example demonstrates how to parse JSON with comments (JSONC format) using JsonComment.
1176
+ * Supports both single-line (//) and block (/* *\/) comments.
1177
+ */
1178
+
1179
+ import { JsonObject, JsonComment } from 'json-stream-lite'
1180
+
1181
+ // Helper to convert string to bytes
1182
+ function stringToBytes(str: string): number[] {
1183
+ return Array.from(new TextEncoder().encode(str))
1184
+ }
1185
+
1186
+ // Example 1: Parse single-line comments
1187
+ console.log('=== Example 1: Single-line Comments ===')
1188
+ const jsoncWithLineComments = `{
1189
+ // This is a name field
1190
+ // Another comment
1191
+ "name": "Alice",
1192
+ // Age in years
1193
+ "age": 30
1194
+ }`
1195
+
1196
+ const parser1 = new JsonObject()
1197
+ parser1.feed(...stringToBytes(jsoncWithLineComments))
1198
+
1199
+ // Access pre-comments for object members
1200
+ for (const { key: keyEntity, value: valueEntity } of parser1) {
1201
+ // Get comments before the key
1202
+ const preComments = keyEntity.preCommentStrings
1203
+
1204
+ const key = keyEntity.read()
1205
+ if (preComments.length > 0) {
1206
+ console.log(`Comment for "${key}":`, preComments.join(', '))
1207
+ }
1208
+
1209
+ const value = valueEntity.readValue()
1210
+ console.log(`${key}: ${value}`)
1211
+ }
1212
+
1213
+ // Example 2: Parse block comments
1214
+ console.log('\n=== Example 2: Block Comments ===')
1215
+ const jsoncWithBlockComments = `{
1216
+ /*
1217
+ * User identification
1218
+ * Required field
1219
+ */
1220
+ "id": 123,
1221
+ /* Status flag */ "active": true
1222
+ }`
1223
+
1224
+ const parser2 = new JsonObject()
1225
+ parser2.feed(...stringToBytes(jsoncWithBlockComments))
1226
+
1227
+ for (const { key: keyEntity, value: valueEntity } of parser2) {
1228
+ const preComment = keyEntity.singlePreCommentString
1229
+ const key = keyEntity.read()
1230
+
1231
+ if (preComment) {
1232
+ console.log(`Comment: ${preComment}`)
1233
+ }
1234
+
1235
+ const value = valueEntity.readValue()
1236
+ console.log(`Key: ${key}, Value: ${value}`)
1237
+ }
1238
+
1239
+ // Example 3: Direct JsonComment parsing
1240
+ console.log('\n=== Example 3: Direct Comment Parsing ===')
1241
+ const lineComment = '// This is a single-line comment\n'
1242
+ const commentParser1 = new JsonComment()
1243
+ commentParser1.feed(...stringToBytes(lineComment))
1244
+ const comment1 = commentParser1.read()
1245
+ console.log('Line comment:', comment1)
1246
+ console.log('Comment style:', commentParser1.style) // 'line'
1247
+
1248
+ const blockComment = '/* This is a block comment */'
1249
+ const commentParser2 = new JsonComment()
1250
+ commentParser2.feed(...stringToBytes(blockComment))
1251
+ const comment2 = commentParser2.read()
1252
+ console.log('Block comment:', comment2)
1253
+ console.log('Comment style:', commentParser2.style) // 'block'
1254
+
1255
+ // Example 4: Comments after values
1256
+ console.log('\n=== Example 4: Post-value Comments ===')
1257
+ const jsoncWithPostComments = `{
1258
+ "status": "ok" // Everything is fine
1259
+ }`
1260
+
1261
+ const parser4 = new JsonObject()
1262
+ parser4.feed(...stringToBytes(jsoncWithPostComments))
1263
+
1264
+ for (const { key: keyEntity, value: valueEntity } of parser4) {
1265
+ const key = keyEntity.read()
1266
+ const value = valueEntity.readValue()
1267
+
1268
+ // Get comments after the value
1269
+ const postComments = valueEntity.postCommentStrings
1270
+ if (postComments.length > 0) {
1271
+ console.log(`${key}: ${value} // ${postComments.join(', ')}`)
1272
+ } else {
1273
+ console.log(`${key}: ${value}`)
1274
+ }
1275
+ }
1276
+
1277
+ // Example 5: Mixed comments
1278
+ console.log('\n=== Example 5: Mixed Comment Styles ===')
1279
+ const jsoncMixed = `{
1280
+ // Configuration file
1281
+ "version": "1.0", /* semantic versioning */
1282
+ /*
1283
+ * Environment settings
1284
+ */
1285
+ "env": "production" // current environment
1286
+ }`
1287
+
1288
+ const parser5 = new JsonObject()
1289
+ parser5.feed(...stringToBytes(jsoncMixed))
1290
+
1291
+ console.log('Parsing JSONC with mixed comment styles:')
1292
+ for (const { key: keyEntity, value: valueEntity } of parser5) {
1293
+ const pre = keyEntity.preCommentStrings
1294
+ const key = keyEntity.read()
1295
+ const value = valueEntity.readValue()
1296
+ const post = valueEntity.postCommentStrings
1297
+
1298
+ if (pre.length > 0) {
1299
+ console.log(` [Pre] ${pre.join(' | ')}`)
1300
+ }
1301
+ console.log(` ${key}: ${value}`)
1302
+ if (post.length > 0) {
1303
+ console.log(` [Post] ${post.join(' | ')}`)
1304
+ }
1305
+ }
1306
+
1307
+ console.log('\n✅ All comment parsing examples completed!')
1308
+ ```
package/README.md CHANGED
@@ -4,6 +4,9 @@
4
4
 
5
5
  A lightweight, memory-efficient, zero-dependency streaming JSON parser and stringifier written in TypeScript. Process large JSON files without loading them entirely into memory.
6
6
 
7
+ [![npm version](https://img.shields.io/npm/v/json-stream-lite.svg)](https://www.npmjs.com/package/json-stream-lite)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+
7
10
  ## Features
8
11
 
9
12
  - 🚀 **Stream parsing**: Parse JSON incrementally as data arrives
@@ -182,6 +185,9 @@ import { jsonStreamStringifyBytes } from 'json-stream-lite'
182
185
 
183
186
  const data = { name: 'Alice', age: 30 }
184
187
 
188
+ // Example with a hypothetical writeToFile function
189
+ declare function writeToFile(data: Uint8Array): Promise<void>
190
+
185
191
  for (const bytes of jsonStreamStringifyBytes(data)) {
186
192
  // bytes is a Uint8Array
187
193
  await writeToFile(bytes)
@@ -215,6 +221,9 @@ See [docs](https://jacobshirley.github.io/json-stream-lite/v1).
215
221
  import { createReadStream } from 'fs'
216
222
  import { JsonObject } from 'json-stream-lite'
217
223
 
224
+ // Example processing function
225
+ declare function processRecord(key: string, value: unknown): Promise<void>
226
+
218
227
  async function processLargeFile(filePath: string) {
219
228
  const stream = createReadStream(filePath)
220
229
  const parser = new JsonObject(stream)
@@ -277,6 +286,8 @@ See [string streaming](./EXAMPLES.md#streaming-json-strings-advanced-usage) for
277
286
  ### 1. Processing API Responses
278
287
 
279
288
  ```typescript
289
+ import { JsonObject } from 'json-stream-lite'
290
+
280
291
  async function processApiResponse(url: string) {
281
292
  const response = await fetch(url)
282
293
  const parser = new JsonObject(response.body!)
@@ -329,7 +340,10 @@ async function generateLargeFile(data: unknown, outputPath: string) {
329
340
  ```typescript
330
341
  import { jsonStreamStringify } from 'json-stream-lite'
331
342
 
332
- async function* exportDatabase(query: string) {
343
+ async function* exportDatabase(
344
+ query: string,
345
+ db: { query: (sql: string) => Promise<unknown[]> },
346
+ ) {
333
347
  const records = await db.query(query)
334
348
 
335
349
  for (const chunk of jsonStreamStringify(records, null, 2)) {
@@ -337,10 +351,13 @@ async function* exportDatabase(query: string) {
337
351
  }
338
352
  }
339
353
 
340
- // Stream to client
341
- app.get('/export', async (req, res) => {
354
+ // Example usage with Express-like server
355
+ declare const db: { query: (sql: string) => Promise<unknown[]> }
356
+ declare const app: any
357
+
358
+ app.get('/export', async (req: any, res: any) => {
342
359
  res.setHeader('Content-Type', 'application/json')
343
- for await (const chunk of exportDatabase('SELECT * FROM users')) {
360
+ for await (const chunk of exportDatabase('SELECT * FROM users', db)) {
344
361
  res.write(chunk)
345
362
  }
346
363
  res.end()
@@ -51,6 +51,11 @@ export declare class ByteBuffer {
51
51
  */
52
52
  feed(...input: StreamInput[]): void;
53
53
  push(byte: number): void;
54
+ /**
55
+ * Checks if the buffer has been fully consumed.
56
+ * @returns True if buffer index is at or beyond the end of the buffer
57
+ * */
58
+ atEnd(): boolean;
54
59
  /**
55
60
  * Checks if end of file has been reached and buffer is exhausted.
56
61
  *
@@ -148,13 +148,20 @@ export class ByteBuffer {
148
148
  }
149
149
  this.buffer.push(byte);
150
150
  }
151
+ /**
152
+ * Checks if the buffer has been fully consumed.
153
+ * @returns True if buffer index is at or beyond the end of the buffer
154
+ * */
155
+ atEnd() {
156
+ return this.bufferIndex >= this.buffer.length;
157
+ }
151
158
  /**
152
159
  * Checks if end of file has been reached and buffer is exhausted.
153
160
  *
154
161
  * @returns True if no more input is available
155
162
  */
156
163
  atEof() {
157
- return this.eof && this.bufferIndex >= this.buffer.length;
164
+ return this.eof && this.atEnd();
158
165
  }
159
166
  /**
160
167
  * Peeks at an item in the buffer without consuming it.
@@ -4,6 +4,7 @@ import { JsonKeyValuePair } from './types.js';
4
4
  * Flattens nested structures using dot notation and array indices.
5
5
  *
6
6
  * @param bytes - The JSON input as bytes or string
7
+ * @param options - Optional parser options (jsonc, strict)
7
8
  * @yields Key-value pairs as [key, value] tuples
8
9
  *
9
10
  * @example
@@ -5,6 +5,7 @@ import { stringToBytes } from './utils.js';
5
5
  * Flattens nested structures using dot notation and array indices.
6
6
  *
7
7
  * @param bytes - The JSON input as bytes or string
8
+ * @param options - Optional parser options (jsonc, strict)
8
9
  * @yields Key-value pairs as [key, value] tuples
9
10
  *
10
11
  * @example
package/dist/parser.d.ts CHANGED
@@ -16,6 +16,50 @@ export declare abstract class JsonEntity<T> {
16
16
  * @param buffer - Optional ByteBuffer or ByteStream to read from
17
17
  */
18
18
  constructor(buffer?: ByteBuffer | ByteStream);
19
+ /**
20
+ * Sets the end-of-file (EOF) state of the buffer, indicating whether no more data will be added.
21
+ */
22
+ set eof(value: boolean);
23
+ /**
24
+ * Skips whitespace and yields any comments encountered.
25
+ */
26
+ private getComments;
27
+ /**
28
+ * Asynchronously skips whitespace and yields any comments encountered, waiting for more data if needed.
29
+ */
30
+ private getCommentsAsync;
31
+ /**
32
+ * Generators for pre-comments. In JSONC, comments can appear before or after any value.
33
+ */
34
+ get preComments(): Generator<JsonComment>;
35
+ /**
36
+ * Generators for post-comments. In JSONC, comments can appear before or after any value.
37
+ */
38
+ get postComments(): Generator<JsonComment>;
39
+ /**
40
+ * Async generators for pre-comments. In JSONC, comments can appear before or after any value.
41
+ */
42
+ get preCommentsAsync(): AsyncGenerator<JsonComment>;
43
+ /**
44
+ * Async generators for post-comments. In JSONC, comments can appear before or after any value.
45
+ */
46
+ get postCommentsAsync(): AsyncGenerator<JsonComment>;
47
+ /**
48
+ * Convenience getters to read all pre comments as strings. Consumes the comments in the process.
49
+ */
50
+ get preCommentStrings(): string[];
51
+ /**
52
+ * Convenience getters to read all post comments as strings. Consumes the comments in the process.
53
+ */
54
+ get postCommentStrings(): string[];
55
+ /**
56
+ * Convenience getter to read a single pre comment as a string. Returns null if no comments are present. Consumes the comment in the process.
57
+ */
58
+ get singlePreCommentString(): string | null;
59
+ /**
60
+ * Convenience getter to read a single post comment as a string. Returns null if no comments are present. Consumes the comment in the process.
61
+ */
62
+ get singlePostCommentString(): string | null;
19
63
  /**
20
64
  * Gets the type name of this entity.
21
65
  *
@@ -55,7 +99,7 @@ export declare abstract class JsonEntity<T> {
55
99
  */
56
100
  protected abstract parse(): T;
57
101
  /**
58
- * Skips whitespace characters in the buffer.
102
+ * Skips whitespace characters (and comments when JSONC is enabled) in the buffer.
59
103
  */
60
104
  protected skipWhitespace(): void;
61
105
  /**
@@ -92,13 +136,27 @@ export declare abstract class JsonEntity<T> {
92
136
  /**
93
137
  * Serializes a value into a JSON string using json-stream-lite.
94
138
  * See `jsonStreamStringify` for more details.
139
+ * @returns A generator yielding JSON string chunks
95
140
  */
96
141
  static stringify(value: unknown, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<string>;
97
142
  /**
98
143
  * Serializes a value into JSON as Uint8Array byte chunks using json-stream-lite.
99
144
  * See `jsonStreamStringifyBytes` for more details.
145
+ * @returns A generator yielding JSON byte chunks
100
146
  */
101
147
  static stringifyBytes(value: unknown, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<Uint8Array>;
148
+ /**
149
+ * Asynchronously serializes a value into a JSON string using json-stream-lite.
150
+ * See `jsonStreamStringifyAsync` for more details.
151
+ * @returns An async generator yielding JSON string chunks
152
+ * */
153
+ static stringifyAsync(value: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<string>;
154
+ /**
155
+ * Asynchronously serializes a value into JSON as Uint8Array byte chunks using json-stream-lite.
156
+ * See `jsonStreamStringifyBytesAsync` for more details.
157
+ * @returns An async generator yielding JSON byte chunks
158
+ * */
159
+ static stringifyBytesAsync(value: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<Uint8Array>;
102
160
  }
103
161
  /**
104
162
  * Represents a JSON string value.
@@ -106,6 +164,21 @@ export declare abstract class JsonEntity<T> {
106
164
  *
107
165
  * @typeParam T - The specific string type (defaults to string)
108
166
  */
167
+ /**
168
+ * Represents a JSONC comment (single-line or block).
169
+ * Extends JsonEntity so it can be yielded alongside other entities in JSONC containers.
170
+ */
171
+ /**
172
+ * Represents a JSONC comment (single-line or block).
173
+ * Parses lazily from the buffer — the comment text is only decoded when read().
174
+ */
175
+ export declare class JsonComment extends JsonEntity<string> {
176
+ /** The comment style: 'line' for //, 'block' for /* * / */
177
+ style: 'line' | 'block';
178
+ protected parse(): string;
179
+ get preComments(): Generator<JsonComment>;
180
+ get postComments(): Generator<JsonComment>;
181
+ }
109
182
  export declare class JsonString<T extends string = string> extends JsonEntity<T> {
110
183
  /**
111
184
  * Parses a JSON string from the buffer.
@@ -214,6 +287,7 @@ export type JsonValueType<T = any> = T extends string ? JsonString<Extract<T, st
214
287
  export declare class JsonValue<T = any, K extends string = string> extends JsonEntity<JsonValueType<T>> {
215
288
  private key?;
216
289
  private value?;
290
+ hasReadValue: boolean;
217
291
  /**
218
292
  * Creates a new JsonValue entity.
219
293
  *
@@ -322,24 +396,24 @@ export declare class JsonArray<T = any> extends JsonEntity<T[]> {
322
396
  *
323
397
  * @yields Each item entity in the array
324
398
  */
325
- items(): Generator<JsonValueType<T>>;
399
+ items(): Generator<JsonValue<T>>;
326
400
  /**
327
401
  * Async generator that yields array items from a stream.
328
402
  * Allows for asynchronous streaming/incremental processing.
329
403
  *
330
404
  * @yields Each item entity in the array
331
405
  */
332
- itemsAsync(): AsyncGenerator<JsonValueType<T>>;
406
+ itemsAsync(): AsyncGenerator<JsonValue<T>>;
333
407
  /**
334
408
  * Returns an iterator for array items.
335
409
  * Enables use of for...of loops on JsonArray.
336
410
  */
337
- [Symbol.iterator](): Generator<JsonValueType<T>, any, any>;
411
+ [Symbol.iterator](): Generator<JsonValue<T, string>, any, any>;
338
412
  /**
339
413
  * Returns an async iterator for array items.
340
414
  * Enables use of for await...of loops on JsonArray.
341
415
  */
342
- [Symbol.asyncIterator](): AsyncGenerator<JsonValueType<T>, any, any>;
416
+ [Symbol.asyncIterator](): AsyncGenerator<JsonValue<T, string>, any, any>;
343
417
  /**
344
418
  * Parses the entire array into a JavaScript array.
345
419
  *
package/dist/parser.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ByteBuffer } from './byte-buffer.js';
2
- import { jsonStreamStringify, jsonStreamStringifyBytes, } from './stringify.js';
2
+ import { jsonStreamStringify, jsonStreamStringifyAsync, jsonStreamStringifyBytes, jsonStreamStringifyBytesAsync, } from './stringify.js';
3
3
  import { bytesToNumber, bytesToString } from './utils.js';
4
4
  /**
5
5
  * Map of character names to their byte values for JSON parsing.
@@ -36,6 +36,8 @@ const BYTE_MAP = {
36
36
  backslash: 92,
37
37
  formFeed: 12,
38
38
  backspace: 8,
39
+ slash: 47,
40
+ asterisk: 42,
39
41
  };
40
42
  /**
41
43
  * Checks if a byte represents a whitespace character.
@@ -101,6 +103,118 @@ export class JsonEntity {
101
103
  this.buffer =
102
104
  buffer instanceof ByteBuffer ? buffer : new ByteBuffer(buffer);
103
105
  }
106
+ /**
107
+ * Sets the end-of-file (EOF) state of the buffer, indicating whether no more data will be added.
108
+ */
109
+ set eof(value) {
110
+ this.buffer.eof = value;
111
+ }
112
+ /**
113
+ * Skips whitespace and yields any comments encountered.
114
+ */
115
+ *getComments() {
116
+ while (true) {
117
+ this.skipWhitespace();
118
+ if (this.buffer.peek() === BYTE_MAP.colon) {
119
+ this.buffer.next(); // consume :
120
+ }
121
+ this.skipWhitespace();
122
+ const byte = this.buffer.peek();
123
+ if (byte === BYTE_MAP.slash) {
124
+ const next = this.buffer.peek(1);
125
+ if (next === BYTE_MAP.slash || next === BYTE_MAP.asterisk) {
126
+ const comment = new JsonComment(this.buffer);
127
+ yield comment;
128
+ comment.consume();
129
+ continue;
130
+ }
131
+ }
132
+ break;
133
+ }
134
+ }
135
+ /**
136
+ * Asynchronously skips whitespace and yields any comments encountered, waiting for more data if needed.
137
+ */
138
+ async *getCommentsAsync() {
139
+ while (true) {
140
+ const comments = this.getComments();
141
+ const comment = this.tryParse(() => comments.next());
142
+ if (comment === undefined) {
143
+ await this.buffer.readStreamAsync();
144
+ continue;
145
+ }
146
+ if (comment.done) {
147
+ break;
148
+ }
149
+ yield comment.value;
150
+ }
151
+ }
152
+ /**
153
+ * Generators for pre-comments. In JSONC, comments can appear before or after any value.
154
+ */
155
+ get preComments() {
156
+ return this.getComments();
157
+ }
158
+ /**
159
+ * Generators for post-comments. In JSONC, comments can appear before or after any value.
160
+ */
161
+ get postComments() {
162
+ return this.getComments();
163
+ }
164
+ /**
165
+ * Async generators for pre-comments. In JSONC, comments can appear before or after any value.
166
+ */
167
+ get preCommentsAsync() {
168
+ return this.getCommentsAsync();
169
+ }
170
+ /**
171
+ * Async generators for post-comments. In JSONC, comments can appear before or after any value.
172
+ */
173
+ get postCommentsAsync() {
174
+ return this.getCommentsAsync();
175
+ }
176
+ /**
177
+ * Convenience getters to read all pre comments as strings. Consumes the comments in the process.
178
+ */
179
+ get preCommentStrings() {
180
+ const strings = [];
181
+ for (const comment of this.preComments) {
182
+ strings.push(comment.read());
183
+ }
184
+ return strings;
185
+ }
186
+ /**
187
+ * Convenience getters to read all post comments as strings. Consumes the comments in the process.
188
+ */
189
+ get postCommentStrings() {
190
+ const strings = [];
191
+ for (const comment of this.postComments) {
192
+ strings.push(comment.read());
193
+ }
194
+ return strings;
195
+ }
196
+ /**
197
+ * Convenience getter to read a single pre comment as a string. Returns null if no comments are present. Consumes the comment in the process.
198
+ */
199
+ get singlePreCommentString() {
200
+ const preComments = this.preComments;
201
+ const first = preComments.next();
202
+ if (first.done) {
203
+ return null;
204
+ }
205
+ return first.value.read();
206
+ }
207
+ /**
208
+ * Convenience getter to read a single post comment as a string. Returns null if no comments are present. Consumes the comment in the process.
209
+ */
210
+ get singlePostCommentString() {
211
+ const postComments = this.postComments;
212
+ const first = postComments.next();
213
+ if (first.done) {
214
+ return null;
215
+ }
216
+ return first.value.read();
217
+ }
104
218
  /**
105
219
  * Gets the type name of this entity.
106
220
  *
@@ -146,7 +260,7 @@ export class JsonEntity {
146
260
  }
147
261
  }
148
262
  /**
149
- * Skips whitespace characters in the buffer.
263
+ * Skips whitespace characters (and comments when JSONC is enabled) in the buffer.
150
264
  */
151
265
  skipWhitespace() {
152
266
  while (isWhitespace(this.buffer.peek())) {
@@ -163,6 +277,8 @@ export class JsonEntity {
163
277
  if (this.consumed) {
164
278
  throw new Error('JSON entity has already been consumed.');
165
279
  }
280
+ for (const _ of this.preComments) {
281
+ }
166
282
  const read = this.parse();
167
283
  this.consumed = true;
168
284
  if (this.buffer.canCompact())
@@ -213,9 +329,6 @@ export class JsonEntity {
213
329
  * @throws Error if the entity has already been consumed
214
330
  */
215
331
  tryParse(cb) {
216
- if (this.consumed) {
217
- throw new Error('JSON entity has already been consumed.');
218
- }
219
332
  this.buffer.locked = true;
220
333
  return this.buffer.resetOnFail(() => {
221
334
  const res = cb(this);
@@ -228,6 +341,7 @@ export class JsonEntity {
228
341
  /**
229
342
  * Serializes a value into a JSON string using json-stream-lite.
230
343
  * See `jsonStreamStringify` for more details.
344
+ * @returns A generator yielding JSON string chunks
231
345
  */
232
346
  static stringify(value, replacer, indent = 0, options) {
233
347
  return jsonStreamStringify(value, replacer, indent, options);
@@ -235,10 +349,27 @@ export class JsonEntity {
235
349
  /**
236
350
  * Serializes a value into JSON as Uint8Array byte chunks using json-stream-lite.
237
351
  * See `jsonStreamStringifyBytes` for more details.
352
+ * @returns A generator yielding JSON byte chunks
238
353
  */
239
354
  static stringifyBytes(value, replacer, indent = 0, options) {
240
355
  return jsonStreamStringifyBytes(value, replacer, indent, options);
241
356
  }
357
+ /**
358
+ * Asynchronously serializes a value into a JSON string using json-stream-lite.
359
+ * See `jsonStreamStringifyAsync` for more details.
360
+ * @returns An async generator yielding JSON string chunks
361
+ * */
362
+ static stringifyAsync(value, replacer, indent = 0, options) {
363
+ return jsonStreamStringifyAsync(value, replacer, indent, options);
364
+ }
365
+ /**
366
+ * Asynchronously serializes a value into JSON as Uint8Array byte chunks using json-stream-lite.
367
+ * See `jsonStreamStringifyBytesAsync` for more details.
368
+ * @returns An async generator yielding JSON byte chunks
369
+ * */
370
+ static stringifyBytesAsync(value, replacer, indent = 0, options) {
371
+ return jsonStreamStringifyBytesAsync(value, replacer, indent, options);
372
+ }
242
373
  }
243
374
  /**
244
375
  * Represents a JSON string value.
@@ -246,6 +377,77 @@ export class JsonEntity {
246
377
  *
247
378
  * @typeParam T - The specific string type (defaults to string)
248
379
  */
380
+ /**
381
+ * Represents a JSONC comment (single-line or block).
382
+ * Extends JsonEntity so it can be yielded alongside other entities in JSONC containers.
383
+ */
384
+ /**
385
+ * Represents a JSONC comment (single-line or block).
386
+ * Parses lazily from the buffer — the comment text is only decoded when read().
387
+ */
388
+ export class JsonComment extends JsonEntity {
389
+ /** The comment style: 'line' for //, 'block' for /* * / */
390
+ style = 'line';
391
+ parse() {
392
+ this.skipWhitespace();
393
+ if (this.buffer.peek() === BYTE_MAP.colon) {
394
+ this.buffer.next(); // consume :
395
+ }
396
+ this.skipWhitespace();
397
+ if (this.buffer.peek() !== BYTE_MAP.slash) {
398
+ return '';
399
+ }
400
+ // Consume opening // or /*
401
+ this.buffer.next(); // consume /
402
+ const second = this.buffer.next();
403
+ const bytes = [];
404
+ if (second === BYTE_MAP.slash) {
405
+ this.style = 'line';
406
+ while (true) {
407
+ const byte = this.buffer.peek();
408
+ if (byte === null ||
409
+ byte === BYTE_MAP.lineFeed ||
410
+ byte === BYTE_MAP.carriageReturn) {
411
+ if (byte === BYTE_MAP.carriageReturn) {
412
+ this.buffer.next();
413
+ if (this.buffer.peek() === BYTE_MAP.lineFeed) {
414
+ this.buffer.next();
415
+ }
416
+ }
417
+ else if (byte === BYTE_MAP.lineFeed) {
418
+ this.buffer.next();
419
+ }
420
+ break;
421
+ }
422
+ bytes.push(this.buffer.next());
423
+ }
424
+ }
425
+ else {
426
+ // asterisk — block comment
427
+ this.style = 'block';
428
+ while (true) {
429
+ const byte = this.buffer.peek();
430
+ if (byte === null)
431
+ break;
432
+ if (byte === BYTE_MAP.asterisk &&
433
+ this.buffer.peek(1) === BYTE_MAP.slash) {
434
+ this.buffer.next(); // *
435
+ this.buffer.next(); // /
436
+ break;
437
+ }
438
+ bytes.push(this.buffer.next());
439
+ }
440
+ }
441
+ const commentString = bytesToString(new Uint8Array(bytes)).trim();
442
+ return commentString;
443
+ }
444
+ get preComments() {
445
+ return (function* () { })();
446
+ }
447
+ get postComments() {
448
+ return (function* () { })();
449
+ }
450
+ }
249
451
  export class JsonString extends JsonEntity {
250
452
  /**
251
453
  * Parses a JSON string from the buffer.
@@ -486,6 +688,7 @@ export class JsonNull extends JsonEntity {
486
688
  export class JsonValue extends JsonEntity {
487
689
  key;
488
690
  value;
691
+ hasReadValue = false;
489
692
  /**
490
693
  * Creates a new JsonValue entity.
491
694
  *
@@ -549,6 +752,7 @@ export class JsonValue extends JsonEntity {
549
752
  }
550
753
  this.value = super.read();
551
754
  this.consumed = false;
755
+ this.hasReadValue = true;
552
756
  return this.value;
553
757
  }
554
758
  /**
@@ -735,10 +939,9 @@ export class JsonArray extends JsonEntity {
735
939
  this.buffer.next(); // consume ,
736
940
  this.skipWhitespace();
737
941
  }
738
- const value = new JsonValue(this.buffer).read();
739
- yield value;
740
- if (!value.consumed)
741
- value.read();
942
+ const valueObject = new JsonValue(this.buffer);
943
+ yield valueObject;
944
+ valueObject.consume();
742
945
  this.skipWhitespace();
743
946
  }
744
947
  this.buffer.expect(BYTE_MAP.rightSquare);
@@ -790,7 +993,7 @@ export class JsonArray extends JsonEntity {
790
993
  parse() {
791
994
  const values = [];
792
995
  for (const value of this) {
793
- values.push(value.read());
996
+ values.push(value.readValue());
794
997
  }
795
998
  return values;
796
999
  }
@@ -840,7 +1043,7 @@ export class JsonKeyValueParser extends JsonEntity {
840
1043
  else if (this.container instanceof JsonArray) {
841
1044
  let index = 0;
842
1045
  for (const valueEntity of this.container) {
843
- const value = valueEntity;
1046
+ const value = valueEntity.read();
844
1047
  const finalKey = this.parentKey
845
1048
  ? `${this.parentKey}[${index}]`
846
1049
  : `[${index}]`;
@@ -1,9 +1,20 @@
1
+ /**
2
+ * Comment entry for JSONC stringification.
3
+ */
4
+ export type JsoncStringifyComment = string | {
5
+ text: string;
6
+ style?: 'line' | 'block';
7
+ };
1
8
  /**
2
9
  * Options for JSON streaming stringification.
3
10
  */
4
11
  export type JsonStreamStringifyOptions = {
5
12
  /** Maximum size of string chunks when yielding formatted strings */
6
13
  stringChunkSize?: number;
14
+ /** Enable JSONC output (trailing commas after last items) */
15
+ jsonc?: boolean;
16
+ /** Comments to emit, keyed by dot-notation path. Only emitted when indent > 0. */
17
+ comments?: Record<string, JsoncStringifyComment | JsoncStringifyComment[]>;
7
18
  };
8
19
  /**
9
20
  * Converts a JavaScript value to JSON format, yielding string chunks.
@@ -43,3 +54,5 @@ export declare function jsonStreamStringify(value: unknown, replacer?: any, inde
43
54
  * ```
44
55
  */
45
56
  export declare function jsonStreamStringifyBytes(value: unknown, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<Uint8Array>;
57
+ export declare function jsonStreamStringifyAsync(value: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<string>;
58
+ export declare function jsonStreamStringifyBytesAsync(value: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<Uint8Array>;
package/dist/stringify.js CHANGED
@@ -90,6 +90,25 @@ function hasCustomToStringFunction(value) {
90
90
  value.toString !== Object.prototype.toString &&
91
91
  value.toString !== Array.prototype.toString);
92
92
  }
93
+ /**
94
+ * Yields comment string(s) for a given path from the comments map.
95
+ */
96
+ function* emitComments(path, options, indentStr) {
97
+ if (!options?.comments || !options.comments[path])
98
+ return;
99
+ const entries = options.comments[path];
100
+ const list = Array.isArray(entries) ? entries : [entries];
101
+ for (const entry of list) {
102
+ const text = typeof entry === 'string' ? entry : entry.text;
103
+ const style = typeof entry === 'string' ? 'line' : (entry.style ?? 'line');
104
+ if (style === 'line') {
105
+ yield `${indentStr}// ${text}\n`;
106
+ }
107
+ else {
108
+ yield `${indentStr}/* ${text} */\n`;
109
+ }
110
+ }
111
+ }
93
112
  /**
94
113
  * Internal recursive function that stringifies a value with depth tracking.
95
114
  * Handles all JSON types including primitives, arrays, and objects.
@@ -98,10 +117,12 @@ function hasCustomToStringFunction(value) {
98
117
  * @param replacer - Optional replacer function for value transformation
99
118
  * @param indent - Number of spaces for indentation (0 for compact)
100
119
  * @param currentDepth - Current nesting depth for indentation
120
+ * @param start - Indicates if this is the start of the stringification
101
121
  * @param options - Stringification options
122
+ * @param currentPath - Current dot-notation path for comment matching
102
123
  * @yields String chunks representing the JSON output
103
124
  */
104
- function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth = 0, options) {
125
+ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth = 0, start = true, options, currentPath = '') {
105
126
  if (replacer) {
106
127
  value = replacer('', value);
107
128
  }
@@ -113,6 +134,10 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
113
134
  value = value.toString();
114
135
  }
115
136
  }
137
+ // If this is the first call and indenting, add initial indentation
138
+ if (start && indent > 0 && currentDepth > 0) {
139
+ yield ' '.repeat(indent * currentDepth);
140
+ }
116
141
  if (value === null) {
117
142
  yield 'null';
118
143
  }
@@ -126,22 +151,33 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
126
151
  yield* formatString(value, options?.stringChunkSize);
127
152
  }
128
153
  else if (Array.isArray(value)) {
129
- yield '[';
130
154
  const len = value.length;
131
155
  const valueIndent = indent * (currentDepth + 1);
156
+ const valueIndentStr = indent > 0 ? ' '.repeat(valueIndent) : '';
157
+ const isJsonc = options?.jsonc === true;
158
+ yield '[';
132
159
  for (let i = 0; i < len; i++) {
133
160
  const next = value[i];
161
+ const isLast = i === len - 1;
134
162
  if (i > 0) {
135
163
  yield ',';
136
164
  }
137
165
  if (indent > 0) {
138
- yield '\n' + ' '.repeat(valueIndent);
166
+ yield '\n';
167
+ const itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;
168
+ yield* emitComments(itemPath, options, valueIndentStr);
169
+ yield valueIndentStr;
139
170
  }
140
171
  if (shouldIgnore(next)) {
141
172
  yield 'null';
173
+ if (isLast && isJsonc)
174
+ yield ',';
142
175
  continue;
143
176
  }
144
- yield* jsonStreamStringifyWithDepth(next, replacer, indent > 0 ? indent : 0, currentDepth + 1, options);
177
+ const itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;
178
+ yield* jsonStreamStringifyWithDepth(next, replacer, indent > 0 ? indent : 0, currentDepth + 1, false, options, itemPath);
179
+ if (isLast && isJsonc)
180
+ yield ',';
145
181
  }
146
182
  if (indent > 0 && len > 0) {
147
183
  yield '\n' + ' '.repeat(indent * currentDepth);
@@ -149,11 +185,16 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
149
185
  yield ']';
150
186
  }
151
187
  else if (typeof value === 'object') {
152
- yield '{';
153
188
  const keys = Object.keys(value);
154
189
  const len = keys.length;
155
190
  const valueIndent = indent * (currentDepth + 1);
191
+ const valueIndentStr = indent > 0 ? ' '.repeat(valueIndent) : '';
192
+ const isJsonc = options?.jsonc === true;
156
193
  let count = 0;
194
+ // Count non-ignored keys for trailing comma logic
195
+ const validKeys = keys.filter((k) => !shouldIgnore(value[k]));
196
+ const totalValid = validKeys.length;
197
+ yield '{';
157
198
  for (let i = 0; i < len; i++) {
158
199
  const key = keys[i];
159
200
  const next = value[key];
@@ -163,13 +204,18 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
163
204
  if (count > 0) {
164
205
  yield ',';
165
206
  }
207
+ const memberPath = currentPath ? `${currentPath}.${key}` : key;
166
208
  if (indent > 0) {
167
- yield '\n' + ' '.repeat(valueIndent);
209
+ yield '\n';
210
+ yield* emitComments(memberPath, options, valueIndentStr);
211
+ yield valueIndentStr;
168
212
  }
169
213
  yield* formatString(key, options?.stringChunkSize);
170
214
  yield `:${indent > 0 ? ' ' : ''}`;
171
- yield* jsonStreamStringifyWithDepth(next, replacer, indent > 0 ? indent : 0, currentDepth + 1, options);
215
+ yield* jsonStreamStringifyWithDepth(next, replacer, indent > 0 ? indent : 0, currentDepth + 1, false, options, memberPath);
172
216
  count++;
217
+ if (count === totalValid && isJsonc)
218
+ yield ',';
173
219
  }
174
220
  if (indent > 0 && len > 0) {
175
221
  yield '\n' + ' '.repeat(indent * currentDepth);
@@ -196,7 +242,7 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
196
242
  * ```
197
243
  */
198
244
  export function jsonStreamStringify(value, replacer, indent = 0, options) {
199
- return jsonStreamStringifyWithDepth(value, replacer, indent, 0, options);
245
+ return jsonStreamStringifyWithDepth(value, replacer, indent, 0, true, options);
200
246
  }
201
247
  /**
202
248
  * Converts a JavaScript value to JSON format, yielding Uint8Array byte chunks.
@@ -222,3 +268,31 @@ export function* jsonStreamStringifyBytes(value, replacer, indent = 0, options)
222
268
  yield stringToBytes(chunk);
223
269
  }
224
270
  }
271
+ export async function* jsonStreamStringifyAsync(value, replacer, indent = 0, options) {
272
+ yield '[';
273
+ if (indent > 0)
274
+ yield '\n';
275
+ let isFirst = true;
276
+ for await (const item of value) {
277
+ const stringGenerator = jsonStreamStringifyWithDepth(item, replacer, indent, 1, true, options);
278
+ if (!isFirst) {
279
+ yield ',';
280
+ if (indent > 0)
281
+ yield '\n';
282
+ }
283
+ else {
284
+ isFirst = false;
285
+ }
286
+ for (const chunk of stringGenerator) {
287
+ yield chunk;
288
+ }
289
+ }
290
+ if (indent > 0)
291
+ yield '\n';
292
+ yield ']';
293
+ }
294
+ export async function* jsonStreamStringifyBytesAsync(value, replacer, indent = 0, options) {
295
+ for await (const chunk of jsonStreamStringifyAsync(value, replacer, indent, options)) {
296
+ yield stringToBytes(chunk);
297
+ }
298
+ }
package/dist/types.d.ts CHANGED
@@ -17,3 +17,12 @@ export type JsonPrimitive = string | number | boolean | null;
17
17
  * and the value is a JSON primitive.
18
18
  */
19
19
  export type JsonKeyValuePair = [string, JsonPrimitive];
20
+ /**
21
+ * Options for configuring JSON parsing behavior.
22
+ */
23
+ export type JsonParserOptions = {
24
+ /** Enable JSONC (JSON with Comments) parsing. Allows // and /* * / comments. */
25
+ jsonc?: boolean;
26
+ /** Enforce strict JSON parsing. When false, trailing commas are allowed. Default: true. */
27
+ strict?: boolean;
28
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-stream-lite",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
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",
@@ -46,7 +46,7 @@
46
46
  "author": "Jacob Shirley",
47
47
  "license": "MIT",
48
48
  "devDependencies": {
49
- "typescript": "^5.9.3",
49
+ "typescript": "^6.0.2",
50
50
  "vitest": "^4.0.14",
51
51
  "@vitest/browser": "^4.0.14",
52
52
  "@vitest/browser-playwright": "^4.0.14",