-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatter.js
More file actions
264 lines (210 loc) · 5.72 KB
/
Copy pathformatter.js
File metadata and controls
264 lines (210 loc) · 5.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
function countLines(text, endIndex) {
let lines = 1;
for (let index = 0; index < endIndex; index += 1) {
if (text[index] === "\n") {
lines += 1;
}
}
return lines;
}
function scanCompositeValue(text, startIndex) {
const stack = [text[startIndex]];
let inString = false;
let escaping = false;
for (let index = startIndex + 1; index < text.length; index += 1) {
const character = text[index];
if (inString) {
if (escaping) {
escaping = false;
continue;
}
if (character === "\\") {
escaping = true;
continue;
}
if (character === '"') {
inString = false;
}
continue;
}
if (character === '"') {
inString = true;
continue;
}
if (character === "{" || character === "[") {
stack.push(character);
continue;
}
if (character === "}") {
if (stack[stack.length - 1] !== "{") {
throw new SyntaxError("Unexpected closing brace.");
}
stack.pop();
}
if (character === "]") {
if (stack[stack.length - 1] !== "[") {
throw new SyntaxError("Unexpected closing bracket.");
}
stack.pop();
}
if (stack.length === 0) {
return index + 1;
}
}
throw new SyntaxError(
"Reached the end of the input before the JSON value closed.",
);
}
function scanSimpleValue(text, startIndex) {
let index = startIndex;
while (index < text.length && !/\s/.test(text[index])) {
index += 1;
}
return index;
}
function extractJsonValue(text, startIndex) {
const opener = text[startIndex];
if (opener === "{" || opener === "[") {
return scanCompositeValue(text, startIndex);
}
if (opener === '"' || opener === "-" || /[0-9tfn]/.test(opener)) {
return scanSimpleValue(text, startIndex);
}
throw new SyntaxError(`Unexpected token ${opener}.`);
}
function parseSequence(text) {
const records = [];
let index = 0;
while (index < text.length) {
while (index < text.length && /\s/.test(text[index])) {
index += 1;
}
if (index >= text.length) {
break;
}
const valueStart = index;
const valueEnd = extractJsonValue(text, valueStart);
const snippet = text.slice(valueStart, valueEnd);
try {
records.push(JSON.parse(snippet));
} catch (error) {
throw {
line: countLines(text, valueStart),
message:
error instanceof Error
? error.message
: "Failed to parse JSON value.",
};
}
index = valueEnd;
}
return records;
}
export function sortKeysDeep(value) {
if (Array.isArray(value)) {
return value.map(sortKeysDeep);
}
if (value && typeof value === "object") {
return Object.keys(value)
.sort((left, right) => left.localeCompare(right))
.reduce((result, key) => {
result[key] = sortKeysDeep(value[key]);
return result;
}, {});
}
return value;
}
export function parseJsonlInput(sourceText) {
const normalized = sourceText.replace(/\r\n?/g, "\n");
const trimmed = normalized.trim();
if (!trimmed) {
return [];
}
try {
const parsed = JSON.parse(trimmed);
return Array.isArray(parsed) ? parsed : [parsed];
} catch {
try {
return parseSequence(normalized);
} catch (error) {
const issue = error && typeof error === "object" ? error : {};
throw {
line: typeof issue.line === "number" ? issue.line : 1,
message:
typeof issue.message === "string"
? issue.message
: "Unable to parse the JSONL input.",
};
}
}
}
function buildPrettyRecordBlocks(records, indent) {
const renderedRecords = records.map((record) =>
JSON.stringify(record, null, indent),
);
const blocks = [];
let currentRow = 0;
const output = renderedRecords
.map((recordText, index) => {
const lineCount = recordText.split("\n").length;
blocks.push({ startRow: currentRow, endRow: currentRow + lineCount - 1 });
currentRow += lineCount;
return recordText;
})
.join("\n");
return { output, blocks };
}
function buildCompactRecordBlocks(records) {
const renderedRecords = records.map((record) => JSON.stringify(record));
const blocks = renderedRecords.map((_, index) => ({
startRow: index,
endRow: index,
}));
return {
output: renderedRecords.join("\n"),
blocks,
};
}
function buildArrayRecordBlocks(records, indent) {
if (records.length === 0) {
return { output: "[]", blocks: [] };
}
const indentUnit = typeof indent === "number" ? " ".repeat(indent) : indent;
const lines = ["["];
const blocks = [];
let currentRow = 1;
records.forEach((record, index) => {
const recordLines = JSON.stringify(record, null, indent)
.split("\n")
.map((line) => `${indentUnit}${line}`);
if (index < records.length - 1) {
recordLines[recordLines.length - 1] =
`${recordLines[recordLines.length - 1]},`;
}
lines.push(...recordLines);
blocks.push({
startRow: currentRow,
endRow: currentRow + recordLines.length - 1,
});
currentRow += recordLines.length;
});
lines.push("]");
return {
output: lines.join("\n"),
blocks,
};
}
export function formatRecordsWithBlocks(records, options) {
const { indent, layout, sortKeys } = options;
const preparedRecords = sortKeys ? records.map(sortKeysDeep) : records;
if (layout === "json-array") {
return buildArrayRecordBlocks(preparedRecords, indent);
}
if (layout === "compact-jsonl") {
return buildCompactRecordBlocks(preparedRecords);
}
return buildPrettyRecordBlocks(preparedRecords, indent);
}
export function formatRecords(records, options) {
return formatRecordsWithBlocks(records, options).output;
}