@cobol-ts/cursor-loader-json 0.0.2 → 0.0.4

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kEAA+C"}
@@ -0,0 +1,63 @@
1
+ import { type Parser, type ParserPhysicalRecordContent, type ParserResult, type ProjectionRecordState, utf8RangeToString } from "@cobol-ts/cursor-loader-types";
2
+ export type JsonPrimitive = null | boolean | number | string;
3
+ export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
4
+ export interface JsonObject {
5
+ [name: string]: JsonValue;
6
+ }
7
+ export type JsonArray = JsonValue[];
8
+ export type JsonProjectionPath = readonly string[];
9
+ export type JsonRecordState = ProjectionRecordState;
10
+ export declare const createJsonRecordState: () => JsonRecordState;
11
+ export type JsonParser = Parser<JsonValue, undefined, undefined, JsonRecordState, JsonProjectionPath>;
12
+ /**
13
+ * JSONL parser.
14
+ *
15
+ * Each successfully parsed record is one JSON value:
16
+ *
17
+ * null
18
+ * boolean
19
+ * number
20
+ * string
21
+ * object
22
+ * array
23
+ *
24
+ * The parser has no configuration, prepared details or per-record state.
25
+ *
26
+ * JSON projection paths remain readonly string[] because JSON property
27
+ * traversal already uses that representation directly.
28
+ */
29
+ export declare const jsonParser: {
30
+ toDebugString: typeof utf8RangeToString;
31
+ parse: typeof parse;
32
+ compileProjectionPath: (_details: undefined, _context: import("@cobol-ts/cursor-loader-types").PhysicalRecordContext | undefined, path: readonly (string | number)[]) => readonly string[];
33
+ object(representation: JsonValue, _details: undefined, path: readonly string[]): JsonValue;
34
+ array(representation: JsonValue, _details: undefined, path: readonly string[]): import("@cobol-ts/arrays").ProjectedArraySource<JsonValue>;
35
+ integer(representation: unknown, _details: undefined, path: readonly string[], ...occurrenceIndices: number[]): number;
36
+ float(representation: unknown, _details: undefined, path: readonly string[], ...occurrenceIndices: number[]): number;
37
+ character(representation: unknown, _details: undefined, path: readonly string[], ...occurrenceIndices: number[]): string;
38
+ string(representation: unknown, _details: undefined, path: readonly string[], ...occurrenceIndices: number[]): string;
39
+ };
40
+ /**
41
+ * Parse one JSONL physical record.
42
+ *
43
+ * JSONL records are terminated by LF.
44
+ *
45
+ * CRLF works naturally because CR is JSON whitespace and remains immediately
46
+ * before the terminating LF.
47
+ *
48
+ * record.startByte is the inclusive logical byte offset of this record across
49
+ * record.buffers.
50
+ *
51
+ * record.lastValidByte is the exclusive logical end of source bytes currently
52
+ * available.
53
+ *
54
+ * If no LF is currently available, readMore() extends the same physical record
55
+ * and scanning continues from the current position.
56
+ *
57
+ * The final record may end at EOF without a terminating LF.
58
+ *
59
+ * Before returning, record.endByte is the exclusive physical end of the
60
+ * completed record.
61
+ */
62
+ declare function parse(record: ParserPhysicalRecordContent<unknown>, _details: undefined): Promise<ParserResult<JsonValue>>;
63
+ export {};
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.jsonParser = exports.createJsonRecordState = void 0;
4
+ const cursor_loader_types_1 = require("@cobol-ts/cursor-loader-types");
5
+ const json_projection_support_1 = require("./json.projection.support");
6
+ const LINE_FEED = 0x0a;
7
+ const createJsonRecordState = () => ({ projectionViews: new Map() });
8
+ exports.createJsonRecordState = createJsonRecordState;
9
+ /**
10
+ * JSONL parser.
11
+ *
12
+ * Each successfully parsed record is one JSON value:
13
+ *
14
+ * null
15
+ * boolean
16
+ * number
17
+ * string
18
+ * object
19
+ * array
20
+ *
21
+ * The parser has no configuration, prepared details or per-record state.
22
+ *
23
+ * JSON projection paths remain readonly string[] because JSON property
24
+ * traversal already uses that representation directly.
25
+ */
26
+ exports.jsonParser = {
27
+ ...json_projection_support_1.jsonProjectionSupport,
28
+ toDebugString: cursor_loader_types_1.utf8RangeToString,
29
+ parse
30
+ };
31
+ /**
32
+ * Parse one JSONL physical record.
33
+ *
34
+ * JSONL records are terminated by LF.
35
+ *
36
+ * CRLF works naturally because CR is JSON whitespace and remains immediately
37
+ * before the terminating LF.
38
+ *
39
+ * record.startByte is the inclusive logical byte offset of this record across
40
+ * record.buffers.
41
+ *
42
+ * record.lastValidByte is the exclusive logical end of source bytes currently
43
+ * available.
44
+ *
45
+ * If no LF is currently available, readMore() extends the same physical record
46
+ * and scanning continues from the current position.
47
+ *
48
+ * The final record may end at EOF without a terminating LF.
49
+ *
50
+ * Before returning, record.endByte is the exclusive physical end of the
51
+ * completed record.
52
+ */
53
+ async function parse(record, _details) {
54
+ let scanByte = record.startByte;
55
+ let bufferIndex = 0;
56
+ let bufferStart = 0;
57
+ /*
58
+ * Locate the buffer containing startByte.
59
+ */
60
+ while (bufferIndex < record.buffers.length
61
+ && scanByte >= bufferStart + record.buffers[bufferIndex].length) {
62
+ bufferStart += record.buffers[bufferIndex].length;
63
+ bufferIndex++;
64
+ }
65
+ while (true) {
66
+ /*
67
+ * Scan every currently available source byte.
68
+ *
69
+ * lastValidByte, rather than Uint8Array.length, is authoritative. The
70
+ * final pooled buffer may contain unused capacity.
71
+ */
72
+ while (scanByte < record.lastValidByte) {
73
+ const buffer = record.buffers[bufferIndex];
74
+ const bufferValidEnd = Math.min(buffer.length, record.lastValidByte - bufferStart);
75
+ while (scanByte < record.lastValidByte
76
+ && scanByte - bufferStart < bufferValidEnd) {
77
+ if (buffer[scanByte - bufferStart] === LINE_FEED) {
78
+ record.endByte = scanByte + 1;
79
+ return parseRecord(record);
80
+ }
81
+ scanByte++;
82
+ }
83
+ if (scanByte >= bufferStart + buffer.length) {
84
+ bufferStart += buffer.length;
85
+ bufferIndex++;
86
+ }
87
+ }
88
+ /*
89
+ * EOF terminates the final record even without a newline.
90
+ */
91
+ if (record.fileFinished) {
92
+ record.endByte = record.lastValidByte;
93
+ return parseRecord(record);
94
+ }
95
+ /*
96
+ * Local scan state survives readMore(), so parsing simply resumes from
97
+ * the current logical byte.
98
+ */
99
+ await record.readMore();
100
+ }
101
+ }
102
+ /**
103
+ * Decode and parse the completed JSONL record.
104
+ *
105
+ * JSON.parse() is the validation boundary. A successful parse necessarily
106
+ * produces a JsonValue.
107
+ */
108
+ function parseRecord(record) {
109
+ const text = (0, cursor_loader_types_1.utf8RangeToString)(record, record.startByte, record.endByte);
110
+ try {
111
+ return JSON.parse(text);
112
+ }
113
+ catch (error) {
114
+ const message = error instanceof Error
115
+ ? error.message
116
+ : String(error);
117
+ return {
118
+ errors: [
119
+ `${record.source}: record ${record.recordNumber}: `
120
+ + `JSON parse error ${message}\n${text}`
121
+ ]
122
+ };
123
+ }
124
+ }
125
+ //# sourceMappingURL=cursor.loader.json.parser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cursor.loader.json.parser.js","sourceRoot":"","sources":["../../src/cursor.loader.json.parser.ts"],"names":[],"mappings":";;;AAAA,uEAMuC;AAEvC,uEAAgE;AAGhE,MAAM,SAAS,GAAG,IAAI,CAAC;AAuBhB,MAAM,qBAAqB,GAAG,GAAmB,EAAE,CAAC,CAAC,EAAC,eAAe,EAAC,IAAI,GAAG,EAAE,EAAC,CAAC,CAAC;AAA5E,QAAA,qBAAqB,yBAAuD;AAWzF;;;;;;;;;;;;;;;;GAgBG;AACU,QAAA,UAAU,GAAG;IACtB,GAAG,+CAAqB;IACxB,aAAa,EAAE,uCAAiB;IAChC,KAAK;CACa,CAAC;AAGvB;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,KAAK,UAAU,KAAK,CAChB,MAA4C,EAC5C,QAAmB;IAEnB,IAAI,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC;IAChC,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,IAAI,WAAW,GAAG,CAAC,CAAC;IAEpB;;OAEG;IACH,OACI,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM;WAChC,QAAQ,IAAI,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,MAAM,EAC7D,CAAC;QACH,WAAW,IAAI,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC;QAClD,WAAW,EAAE,CAAC;IAClB,CAAC;IAED,OAAO,IAAI,EAAE,CAAC;QACV;;;;;WAKG;QACH,OAAO,QAAQ,GAAG,MAAM,CAAC,aAAa,EAAE,CAAC;YACrC,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;YAC3C,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAC3B,MAAM,CAAC,MAAM,EACb,MAAM,CAAC,aAAa,GAAG,WAAW,CACrC,CAAC;YAEF,OACI,QAAQ,GAAG,MAAM,CAAC,aAAa;mBAC5B,QAAQ,GAAG,WAAW,GAAG,cAAc,EACxC,CAAC;gBACH,IAAI,MAAM,CAAC,QAAQ,GAAG,WAAW,CAAC,KAAK,SAAS,EAAE,CAAC;oBAC/C,MAAM,CAAC,OAAO,GAAG,QAAQ,GAAG,CAAC,CAAC;oBAC9B,OAAO,WAAW,CAAC,MAAM,CAAC,CAAC;gBAC/B,CAAC;gBAED,QAAQ,EAAE,CAAC;YACf,CAAC;YAED,IAAI,QAAQ,IAAI,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;gBAC1C,WAAW,IAAI,MAAM,CAAC,MAAM,CAAC;gBAC7B,WAAW,EAAE,CAAC;YAClB,CAAC;QACL,CAAC;QAED;;WAEG;QACH,IAAI,MAAM,CAAC,YAAY,EAAE,CAAC;YACtB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAC,aAAa,CAAC;YACtC,OAAO,WAAW,CAAC,MAAM,CAAC,CAAC;QAC/B,CAAC;QAED;;;WAGG;QACH,MAAM,MAAM,CAAC,QAAQ,EAAE,CAAC;IAC5B,CAAC;AACL,CAAC;AAGD;;;;;GAKG;AACH,SAAS,WAAW,CAChB,MAA4C;IAE5C,MAAM,IAAI,GAAG,IAAA,uCAAiB,EAC1B,MAAM,EACN,MAAM,CAAC,SAAS,EAChB,MAAM,CAAC,OAAO,CACjB,CAAC;IAEF,IAAI,CAAC;QACD,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAc,CAAC;IACzC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,MAAM,OAAO,GACT,KAAK,YAAY,KAAK;YAClB,CAAC,CAAC,KAAK,CAAC,OAAO;YACf,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAExB,OAAO;YACH,MAAM,EAAE;gBACJ,GAAG,MAAM,CAAC,MAAM,YAAY,MAAM,CAAC,YAAY,IAAI;sBACjD,oBAAoB,OAAO,KAAK,IAAI,EAAE;aAC3C;SACJ,CAAC;IACN,CAAC;AACL,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,469 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const errors_1 = require("@cobol-ts/errors");
4
+ const cursor_record_1 = require("@cobol-ts/cursor-record");
5
+ const physical_record_1 = require("@cobol-ts/cursor-record/src/physical.record");
6
+ const cursor_loader_json_parser_1 = require("./cursor.loader.json.parser");
7
+ const encoder = new TextEncoder();
8
+ describe("jsonParser", () => {
9
+ test("renders physical JSON bytes as UTF-8 for diagnostics", () => {
10
+ const bytes = encode(`xx{"name":"£"}yy`);
11
+ const record = createRecord([bytes], true);
12
+ expect(cursor_loader_json_parser_1.jsonParser.toDebugString(record, 2, bytes.length - 2)).toBe(`{"name":"£"}`);
13
+ });
14
+ test("renders diagnostic UTF-8 spanning physical buffers", () => {
15
+ const content = encode(`{"name":"£"}`);
16
+ /*
17
+ * £ is UTF-8:
18
+ *
19
+ * c2 a3
20
+ *
21
+ * Split between those two bytes.
22
+ */
23
+ const split = content.indexOf(0xc2) + 1;
24
+ const record = createRecord([
25
+ content.slice(0, split),
26
+ content.slice(split)
27
+ ], true);
28
+ expect(cursor_loader_json_parser_1.jsonParser.toDebugString(record, 0, content.length)).toBe(`{"name":"£"}`);
29
+ });
30
+ test("parses a JSON object ending at EOF", async () => {
31
+ const record = createRecord([
32
+ encode(`{"id":"123","name":"Fred"}`)
33
+ ], true);
34
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
35
+ expect(result).toEqual({
36
+ id: "123",
37
+ name: "Fred"
38
+ });
39
+ expect(record.endByte).toBe(record.lastValidByte);
40
+ });
41
+ test("parses a JSON array", async () => {
42
+ const result = await parse(`[1,2,3]`);
43
+ expect(result).toEqual([
44
+ 1,
45
+ 2,
46
+ 3
47
+ ]);
48
+ });
49
+ test("parses a JSON string primitive", async () => {
50
+ const result = await parse(`"hello"`);
51
+ expect(result).toBe("hello");
52
+ });
53
+ test("parses a JSON number primitive", async () => {
54
+ const result = await parse(`42`);
55
+ expect(result).toBe(42);
56
+ });
57
+ test("parses a JSON boolean primitive", async () => {
58
+ const result = await parse(`true`);
59
+ expect(result).toBe(true);
60
+ });
61
+ test("parses JSON null", async () => {
62
+ const result = await parse(`null`);
63
+ expect(result).toBeNull();
64
+ });
65
+ test("ends a physical record immediately after LF", async () => {
66
+ const json = encode(`{"id":123}\n`);
67
+ const record = createRecord([json], false);
68
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
69
+ expect(result).toEqual({
70
+ id: 123
71
+ });
72
+ expect(record.endByte).toBe(json.length);
73
+ expect(record.fileFinished).toBe(false);
74
+ });
75
+ test("parses a CRLF terminated JSONL record", async () => {
76
+ const json = encode(`{"id":123}\r\n`);
77
+ const record = createRecord([json], false);
78
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
79
+ expect(result).toEqual({
80
+ id: 123
81
+ });
82
+ expect(record.endByte).toBe(json.length);
83
+ });
84
+ test("stops at LF when later records have already been read", async () => {
85
+ const first = `{"id":1}\n`;
86
+ const all = encode(first
87
+ + `{"id":2}\n`);
88
+ const record = createRecord([all], true);
89
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
90
+ expect(result).toEqual({
91
+ id: 1
92
+ });
93
+ expect(record.endByte).toBe(encode(first).length);
94
+ expect(record.lastValidByte).toBe(all.length);
95
+ expect(record.fileFinished).toBe(true);
96
+ });
97
+ test("parses an already-read carried record starting part way through a buffer", async () => {
98
+ const prefix = encode(`{"previous":1}\n`);
99
+ const json = encode(`{"id":123}`);
100
+ const buffer = new Uint8Array(prefix.length + json.length);
101
+ buffer.set(prefix, 0);
102
+ buffer.set(json, prefix.length);
103
+ let readMoreCalls = 0;
104
+ const record = createRecord([buffer], true, prefix.length, async () => {
105
+ readMoreCalls++;
106
+ });
107
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
108
+ expect(result).toEqual({
109
+ id: 123
110
+ });
111
+ expect(record.endByte).toBe(buffer.length);
112
+ expect(readMoreCalls).toBe(0);
113
+ });
114
+ test("parses a carried record and stops at its LF before later bytes", async () => {
115
+ const prefix = `{"previous":1}\n`;
116
+ const current = `{"id":123}\n`;
117
+ const later = `{"id":456}\n`;
118
+ const buffer = encode(prefix
119
+ + current
120
+ + later);
121
+ const startByte = encode(prefix).length;
122
+ const expectedEnd = startByte
123
+ + encode(current).length;
124
+ const record = createRecord([buffer], true, startByte);
125
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
126
+ expect(result).toEqual({
127
+ id: 123
128
+ });
129
+ expect(record.endByte).toBe(expectedEnd);
130
+ expect(record.lastValidByte).toBe(buffer.length);
131
+ });
132
+ test("calls readMore when all currently valid bytes have been scanned", async () => {
133
+ const first = encode(`{"id":`);
134
+ const second = encode(`123}\n`);
135
+ let readMoreCalls = 0;
136
+ const record = createRecord([first], false, 0, async (buffers, current) => {
137
+ readMoreCalls++;
138
+ buffers.push(second);
139
+ current.lastValidByte +=
140
+ second.length;
141
+ current.fileFinished =
142
+ true;
143
+ });
144
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
145
+ expect(result).toEqual({
146
+ id: 123
147
+ });
148
+ expect(readMoreCalls).toBe(1);
149
+ expect(record.endByte).toBe(first.length + second.length);
150
+ expect(record.lastValidByte).toBe(first.length + second.length);
151
+ expect(record.fileFinished).toBe(true);
152
+ });
153
+ test("continues through several readMore calls", async () => {
154
+ const first = encode(`{"id":"`);
155
+ const second = encode(`123`);
156
+ const third = encode(`"}\n`);
157
+ const remainingBuffers = [
158
+ second,
159
+ third
160
+ ];
161
+ let readMoreCalls = 0;
162
+ const record = createRecord([first], false, 0, async (buffers, current) => {
163
+ const buffer = remainingBuffers[readMoreCalls];
164
+ readMoreCalls++;
165
+ buffers.push(buffer);
166
+ current.lastValidByte +=
167
+ buffer.length;
168
+ if (readMoreCalls
169
+ === remainingBuffers.length) {
170
+ current.fileFinished =
171
+ true;
172
+ }
173
+ });
174
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
175
+ expect(result).toEqual({
176
+ id: "123"
177
+ });
178
+ expect(readMoreCalls).toBe(2);
179
+ expect(record.endByte).toBe(first.length
180
+ + second.length
181
+ + third.length);
182
+ });
183
+ test("parses a final record without LF", async () => {
184
+ const json = encode(`{"id":123}`);
185
+ const record = createRecord([json], true);
186
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
187
+ expect(result).toEqual({
188
+ id: 123
189
+ });
190
+ expect(record.endByte).toBe(json.length);
191
+ });
192
+ test("uses lastValidByte rather than physical buffer capacity", async () => {
193
+ const json = encode(`{"id":123}`);
194
+ const buffer = new Uint8Array(json.length + 20);
195
+ buffer.set(json, 0);
196
+ buffer.fill(0xff, json.length);
197
+ const record = createRecord([buffer], true, 0, undefined, json.length);
198
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
199
+ expect(result).toEqual({
200
+ id: 123
201
+ });
202
+ expect(record.endByte).toBe(json.length);
203
+ expect(record.lastValidByte).toBe(json.length);
204
+ });
205
+ test("does not call readMore when EOF is already known", async () => {
206
+ let readMoreCalls = 0;
207
+ const record = createRecord([
208
+ encode(`{"id":123}`)
209
+ ], true, 0, async () => {
210
+ readMoreCalls++;
211
+ });
212
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
213
+ expect(result).toEqual({
214
+ id: 123
215
+ });
216
+ expect(readMoreCalls).toBe(0);
217
+ });
218
+ test("does not modify startByte", async () => {
219
+ const prefix = encode("ignored");
220
+ const json = encode(`{"id":123}`);
221
+ const buffer = new Uint8Array(prefix.length + json.length);
222
+ buffer.set(prefix, 0);
223
+ buffer.set(json, prefix.length);
224
+ const record = createRecord([buffer], true, prefix.length);
225
+ await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
226
+ expect(record.startByte).toBe(prefix.length);
227
+ });
228
+ test("does not modify lastValidByte while parsing already available bytes", async () => {
229
+ const content = encode(`{"id":1}\n{"id":2}`);
230
+ const record = createRecord([content], true);
231
+ const originalLastValidByte = record.lastValidByte;
232
+ await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
233
+ expect(record.lastValidByte).toBe(originalLastValidByte);
234
+ });
235
+ test("does not modify fileFinished while parsing already available bytes", async () => {
236
+ const record = createRecord([
237
+ encode(`{"id":1}\n`)
238
+ ], false);
239
+ await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
240
+ expect(record.fileFinished).toBe(false);
241
+ });
242
+ test("parses JSON spanning several buffers", async () => {
243
+ const first = encode(`{"id":"123",`);
244
+ const second = encode(`"name":"`);
245
+ const third = encode(`Fred"}\n`);
246
+ const record = createRecord([
247
+ first,
248
+ second,
249
+ third
250
+ ], true);
251
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
252
+ expect(result).toEqual({
253
+ id: "123",
254
+ name: "Fred"
255
+ });
256
+ expect(record.endByte).toBe(first.length
257
+ + second.length
258
+ + third.length);
259
+ });
260
+ test("parses a multi-buffer record starting part way through the first buffer", async () => {
261
+ const first = encode(`xxx{"id":"123",`);
262
+ const second = encode(`"name":"Fred"`);
263
+ const third = encode(`}\nyyy`);
264
+ const startByte = 3;
265
+ const expectedEnd = startByte
266
+ + encode(`{"id":"123","name":"Fred"}\n`).length;
267
+ const record = createRecord([
268
+ first,
269
+ second,
270
+ third
271
+ ], true, startByte);
272
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
273
+ expect(result).toEqual({
274
+ id: "123",
275
+ name: "Fred"
276
+ });
277
+ expect(record.endByte).toBe(expectedEnd);
278
+ });
279
+ test("parses UTF-8 characters split across physical buffers", async () => {
280
+ const json = encode(`{"name":"£"}\n`);
281
+ /*
282
+ * £ is UTF-8:
283
+ *
284
+ * c2 a3
285
+ *
286
+ * Split between those two bytes.
287
+ */
288
+ const split = json.indexOf(0xc2) + 1;
289
+ const record = createRecord([
290
+ json.slice(0, split),
291
+ json.slice(split)
292
+ ], true);
293
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
294
+ expect(result).toEqual({
295
+ name: "£"
296
+ });
297
+ });
298
+ test("returns Errors for malformed JSON with physical provenance", async () => {
299
+ const record = createRecord([
300
+ encode(`{"id":`)
301
+ ], true, 0, undefined, undefined, "customers.jsonl", 17);
302
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
303
+ expect((0, errors_1.isErrors)(result)).toBe(true);
304
+ if (!(0, errors_1.isErrors)(result)) {
305
+ throw new Error("Expected JSON parse error");
306
+ }
307
+ expect(result.errors).toHaveLength(1);
308
+ expect(result.errors[0]).toContain("customers.jsonl: record 17: JSON parse error");
309
+ expect(result.errors[0]).toContain(`{"id":`);
310
+ });
311
+ test("accepts any valid JSON value without application schema validation", async () => {
312
+ const result = await parse(`{"somethingElse":123}`);
313
+ expect(result).toEqual({
314
+ somethingElse: 123
315
+ });
316
+ });
317
+ test("propagates readMore failures", async () => {
318
+ const expectedError = new Error("physical read failed");
319
+ const record = createRecord([
320
+ encode(`{"id":`)
321
+ ], false, 0, async () => {
322
+ throw expectedError;
323
+ });
324
+ await expect(cursor_loader_json_parser_1.jsonParser.parse(record, undefined)).rejects.toBe(expectedError);
325
+ });
326
+ test("handles EOF discovered by a zero-byte read", async () => {
327
+ const json = encode(`{"id":123}`);
328
+ let readMoreCalls = 0;
329
+ const record = createRecord([json], false, 0, async (buffers, current) => {
330
+ readMoreCalls++;
331
+ /*
332
+ * Match the physical readMore() contract: a zero-byte read
333
+ * still transfers the acquired physical buffer.
334
+ */
335
+ buffers.push(new Uint8Array(json.length));
336
+ /*
337
+ * Zero bytes were valid, so lastValidByte does not advance.
338
+ */
339
+ current.fileFinished =
340
+ true;
341
+ });
342
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
343
+ expect(result).toEqual({
344
+ id: 123
345
+ });
346
+ expect(readMoreCalls).toBe(1);
347
+ expect(record.lastValidByte).toBe(json.length);
348
+ expect(record.endByte).toBe(json.length);
349
+ });
350
+ test("parses several records from the final physical buffer", async () => {
351
+ const content = encoder.encode(`{"id":1}\n`
352
+ + `{"id":2}\n`
353
+ + `{"id":3}`);
354
+ const config = (0, physical_record_1.createDefaultPhysicalRecordConfig)({
355
+ source: "test",
356
+ file: {
357
+ name: "test"
358
+ },
359
+ /*
360
+ * Deliberately larger than the file content.
361
+ *
362
+ * The first physical read is therefore short, so readMore()
363
+ * establishes:
364
+ *
365
+ * fileFinished = true
366
+ * lastValidByte = content.length
367
+ *
368
+ * All three JSONL records are already present in the same
369
+ * final physical buffer.
370
+ */
371
+ bufferSize: content.length + 10,
372
+ fillFileBuffer: async (_file, buffer) => {
373
+ buffer.set(content);
374
+ return content.length;
375
+ },
376
+ createRecordState: () => undefined
377
+ });
378
+ const iterator = (0, cursor_record_1.createRecordCursor)(cursor_loader_json_parser_1.jsonParser, undefined, config);
379
+ const first = await iterator.next();
380
+ const second = await iterator.next();
381
+ const third = await iterator.next();
382
+ if (first.done
383
+ || second.done
384
+ || third.done) {
385
+ throw new Error("Expected three JSONL records");
386
+ }
387
+ expect(first.value.result).toEqual({
388
+ id: 1
389
+ });
390
+ expect(second.value.result).toEqual({
391
+ id: 2
392
+ });
393
+ expect(third.value.result).toEqual({
394
+ id: 3
395
+ });
396
+ /*
397
+ * The cursor carries exactly the same physical Uint8Array through all
398
+ * three logical records.
399
+ */
400
+ expect(first.value.physicalRecord.buffers[0]).toBe(second.value.physicalRecord.buffers[0]);
401
+ expect(second.value.physicalRecord.buffers[0]).toBe(third.value.physicalRecord.buffers[0]);
402
+ /*
403
+ * EOF was already known while parsing every record.
404
+ */
405
+ expect(first.value.physicalRecord.fileFinished).toBe(true);
406
+ expect(second.value.physicalRecord.fileFinished).toBe(true);
407
+ expect(third.value.physicalRecord.fileFinished).toBe(true);
408
+ /*
409
+ * The final unterminated JSON document ends exactly at the known EOF
410
+ * position.
411
+ */
412
+ expect(third.value.physicalRecord.endByte).toBe(third.value.physicalRecord.lastValidByte);
413
+ first.value.physicalRecord.close();
414
+ second.value.physicalRecord.close();
415
+ third.value.physicalRecord.close();
416
+ const finished = await iterator.next();
417
+ expect(finished.done).toBe(true);
418
+ });
419
+ });
420
+ async function parse(text) {
421
+ const record = createRecord([encode(text)], true);
422
+ const result = await cursor_loader_json_parser_1.jsonParser.parse(record, undefined);
423
+ if ((0, errors_1.isErrors)(result)) {
424
+ throw new Error(result.errors.join("; "));
425
+ }
426
+ return result;
427
+ }
428
+ function encode(value) {
429
+ return encoder.encode(value);
430
+ }
431
+ /**
432
+ * Construct the parser-visible physical-record contract.
433
+ *
434
+ * The mutable buffers array belongs to this test's fake physical reader.
435
+ *
436
+ * ParserPhysicalRecordContent exposes the physical lifecycle state as readonly.
437
+ * Tests which impersonate readMore() deliberately cast to any at the exact
438
+ * mutation point.
439
+ */
440
+ function createRecord(initialBuffers, fileFinished, startByte = 0, readMore = undefined, lastValidByte = undefined, source = "test-source", recordNumber = 1) {
441
+ const buffers = initialBuffers;
442
+ let record;
443
+ record = {
444
+ buffers,
445
+ recordState: undefined,
446
+ startByte,
447
+ endByte: startByte,
448
+ lastValidByte: lastValidByte
449
+ ?? totalLength(initialBuffers),
450
+ fileFinished,
451
+ source,
452
+ recordNumber,
453
+ readMore() {
454
+ if (readMore === undefined) {
455
+ throw new Error("Unexpected readMore()");
456
+ }
457
+ return readMore(buffers, record);
458
+ }
459
+ };
460
+ return record;
461
+ }
462
+ function totalLength(buffers) {
463
+ let length = 0;
464
+ for (const buffer of buffers) {
465
+ length += buffer.length;
466
+ }
467
+ return length;
468
+ }
469
+ //# sourceMappingURL=cursor.loader.json.parser.spec.js.map