parse-chunked.cjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. 'use strict';
  2. const utils = require('./utils.cjs');
  3. const NO_VALUE = Symbol('empty');
  4. const STACK_OBJECT = 1;
  5. const STACK_ARRAY = 2;
  6. const MODE_JSON = 0;
  7. const MODE_JSONL = 1;
  8. const MODE_JSONL_AUTO = 2;
  9. const decoder = new TextDecoder();
  10. function adjustPosition(error, jsonParseOffset) {
  11. if (error.name === 'SyntaxError' && jsonParseOffset) {
  12. error.message = error.message.replace(/at position (\d+)/, (_, pos) =>
  13. 'at position ' + (Number(pos) + jsonParseOffset)
  14. );
  15. }
  16. return error;
  17. }
  18. function append(array, elements) {
  19. // Note: Avoid using array.push(...elements) since it may lead to
  20. // "RangeError: Maximum call stack size exceeded" for long arrays
  21. const initialLength = array.length;
  22. array.length += elements.length;
  23. for (let i = 0; i < elements.length; i++) {
  24. array[initialLength + i] = elements[i];
  25. }
  26. }
  27. function resolveParseMode(mode) {
  28. switch (mode) {
  29. case 'json':
  30. return MODE_JSON;
  31. case 'jsonl':
  32. return MODE_JSONL;
  33. case 'auto':
  34. return MODE_JSONL_AUTO;
  35. default:
  36. throw new TypeError('Invalid options: `mode` should be "json", "jsonl", or "auto"');
  37. }
  38. }
  39. function parseChunkedOptions(value) {
  40. const options = typeof value === 'function'
  41. ? { reviver: value }
  42. : value || {};
  43. return {
  44. mode: resolveParseMode(options.mode ?? 'json'),
  45. reviver: options.reviver ?? null,
  46. onRootValue: options.onRootValue ?? null,
  47. onChunk: options.onChunk ?? null
  48. };
  49. }
  50. function applyReviver(value, reviver) {
  51. return walk({ '': value }, '', value);
  52. function walk(holder, key, value) {
  53. if (value && typeof value === 'object') {
  54. for (const childKey of Object.keys(value)) {
  55. const childValue = value[childKey];
  56. const newValue = walk(value, childKey, childValue);
  57. if (newValue === undefined) {
  58. delete value[childKey];
  59. } else if (newValue !== childValue) {
  60. value[childKey] = newValue;
  61. }
  62. }
  63. }
  64. return reviver.call(holder, key, value);
  65. }
  66. }
  67. async function parseChunked(chunkEmitter, optionsOrReviver) {
  68. const { mode, reviver, onRootValue, onChunk } = parseChunkedOptions(optionsOrReviver);
  69. const iterable = typeof chunkEmitter === 'function'
  70. ? chunkEmitter()
  71. : chunkEmitter;
  72. if (utils.isIterable(iterable)) {
  73. const parser = createChunkParser(mode, reviver, onRootValue, onChunk);
  74. try {
  75. for await (const chunk of iterable) {
  76. if (typeof chunk !== 'string' && !ArrayBuffer.isView(chunk)) {
  77. throw new TypeError('Invalid chunk: Expected string, TypedArray or Buffer');
  78. }
  79. parser.push(chunk);
  80. }
  81. return parser.finish();
  82. } catch (e) {
  83. throw adjustPosition(e, parser.jsonParseOffset);
  84. }
  85. }
  86. throw new TypeError(
  87. 'Invalid chunk emitter: Expected an Iterable, AsyncIterable, generator, ' +
  88. 'async generator, or a function returning an Iterable or AsyncIterable'
  89. );
  90. }
  91. function createChunkParser(parseMode, reviver, onRootValue, onChunk) {
  92. let rootValues = parseMode === MODE_JSONL ? [] : null;
  93. let rootValuesCount = 0;
  94. let currentRootValue = NO_VALUE;
  95. let currentRootValueCursor = null;
  96. let consumedChunkLength = 0;
  97. let parsedChunkLength = 0;
  98. let prevArray = null;
  99. let prevArraySlices = [];
  100. let stack = new Array(100);
  101. let lastFlushDepth = 0;
  102. let flushDepth = 0;
  103. let stateString = false;
  104. let stateStringEscape = false;
  105. let seenNonWhiteSpace = false;
  106. let allowNewRootValue = true;
  107. let pendingByteSeq = null;
  108. let pendingChunk = null;
  109. let jsonParseOffset = 0;
  110. const state = Object.freeze({
  111. get mode() {
  112. return parseMode === MODE_JSONL ? 'jsonl' : 'json';
  113. },
  114. get rootValuesCount() {
  115. return rootValuesCount;
  116. },
  117. get consumed() {
  118. return consumedChunkLength;
  119. },
  120. get parsed() {
  121. return parsedChunkLength;
  122. }
  123. });
  124. return {
  125. push,
  126. finish,
  127. state,
  128. get jsonParseOffset() {
  129. return jsonParseOffset;
  130. }
  131. };
  132. function startRootValue(fragment) {
  133. // Extra non-whitespace after complete root value should fail to parse
  134. if (!allowNewRootValue) {
  135. jsonParseOffset -= 2;
  136. JSON.parse('[]' + fragment);
  137. }
  138. // In "auto" mode, switch to JSONL when a second root value is starting after a newline
  139. if (currentRootValue !== NO_VALUE && parseMode === MODE_JSONL_AUTO) {
  140. parseMode = MODE_JSONL;
  141. rootValues = [currentRootValue];
  142. }
  143. // Block parsing of an additional root value until a newline is encountered
  144. allowNewRootValue = false;
  145. // Parse fragment as a new root value
  146. currentRootValue = JSON.parse(fragment);
  147. }
  148. function finishRootValue() {
  149. rootValuesCount++;
  150. if (typeof reviver === 'function') {
  151. currentRootValue = applyReviver(currentRootValue, reviver);
  152. }
  153. if (typeof onRootValue === 'function') {
  154. onRootValue(currentRootValue, state);
  155. } else if (parseMode === MODE_JSONL) {
  156. rootValues.push(currentRootValue);
  157. }
  158. }
  159. function mergeArraySlices() {
  160. if (prevArray === null) {
  161. return;
  162. }
  163. if (prevArraySlices.length !== 0) {
  164. const newArray = prevArraySlices.length === 1
  165. ? prevArray.concat(prevArraySlices[0])
  166. : prevArray.concat(...prevArraySlices);
  167. if (currentRootValueCursor.prev !== null) {
  168. currentRootValueCursor.prev.value[currentRootValueCursor.key] = newArray;
  169. } else {
  170. currentRootValue = newArray;
  171. }
  172. currentRootValueCursor.value = newArray;
  173. prevArraySlices = [];
  174. }
  175. prevArray = null;
  176. }
  177. function parseAndAppend(fragment, wrap) {
  178. // Append new entries or elements
  179. if (stack[lastFlushDepth - 1] === STACK_OBJECT) {
  180. if (wrap) {
  181. jsonParseOffset--;
  182. fragment = '{' + fragment + '}';
  183. }
  184. Object.assign(currentRootValueCursor.value, JSON.parse(fragment));
  185. } else {
  186. if (wrap) {
  187. jsonParseOffset--;
  188. fragment = '[' + fragment + ']';
  189. }
  190. if (prevArray === currentRootValueCursor.value) {
  191. prevArraySlices.push(JSON.parse(fragment));
  192. } else {
  193. append(currentRootValueCursor.value, JSON.parse(fragment));
  194. prevArray = currentRootValueCursor.value;
  195. }
  196. }
  197. }
  198. function prepareAddition(fragment) {
  199. const { value } = currentRootValueCursor;
  200. const expectComma = Array.isArray(value)
  201. ? value.length !== 0
  202. : Object.keys(value).length !== 0;
  203. if (expectComma) {
  204. // Skip a comma at the beginning of fragment, otherwise it would
  205. // fail to parse
  206. if (fragment[0] === ',') {
  207. jsonParseOffset++;
  208. return fragment.slice(1);
  209. }
  210. // When value (an object or array) is not empty and a fragment
  211. // doesn't start with a comma, a single valid fragment starting
  212. // is a closing bracket. If it's not, a prefix is adding to fail
  213. // parsing. Otherwise, the sequence of chunks can be successfully
  214. // parsed, although it should not, e.g. ["[{}", "{}]"]
  215. if (fragment[0] !== '}' && fragment[0] !== ']') {
  216. jsonParseOffset -= 3;
  217. return '[[]' + fragment;
  218. }
  219. }
  220. return fragment;
  221. }
  222. function flush(chunk, start, end) {
  223. let fragment = chunk.slice(start, end);
  224. // Save position correction for an error in JSON.parse() if any
  225. jsonParseOffset = consumedChunkLength + start;
  226. parsedChunkLength += end - start;
  227. // Prepend pending chunk if any
  228. if (pendingChunk !== null) {
  229. fragment = pendingChunk + fragment;
  230. jsonParseOffset -= pendingChunk.length;
  231. parsedChunkLength += pendingChunk.length;
  232. pendingChunk = null;
  233. }
  234. if (flushDepth === lastFlushDepth) {
  235. // Depth didn't change, so it's a continuation of the current value or entire value if it's a root one
  236. if (lastFlushDepth === 0) {
  237. startRootValue(fragment);
  238. } else {
  239. parseAndAppend(prepareAddition(fragment), true);
  240. }
  241. } else if (flushDepth > lastFlushDepth) {
  242. // Add missed closing brackets/parentheses
  243. for (let i = flushDepth - 1; i >= lastFlushDepth; i--) {
  244. fragment += stack[i] === STACK_OBJECT ? '}' : ']';
  245. }
  246. if (lastFlushDepth === 0) {
  247. startRootValue(fragment);
  248. currentRootValueCursor = {
  249. value: currentRootValue,
  250. key: null,
  251. prev: null
  252. };
  253. } else {
  254. parseAndAppend(prepareAddition(fragment), true);
  255. mergeArraySlices();
  256. }
  257. // Move down to the depths to the last object/array, which is current now
  258. for (let i = lastFlushDepth || 1; i < flushDepth; i++) {
  259. let { value } = currentRootValueCursor;
  260. let key = null;
  261. if (stack[i - 1] === STACK_OBJECT) {
  262. // Find last entry
  263. // eslint-disable-next-line curly
  264. for (key in value);
  265. value = value[key];
  266. } else {
  267. // Last element
  268. key = value.length - 1;
  269. value = value[key];
  270. }
  271. currentRootValueCursor = {
  272. value,
  273. key,
  274. prev: currentRootValueCursor
  275. };
  276. }
  277. } else /* flushDepth < lastFlushDepth */ {
  278. fragment = prepareAddition(fragment);
  279. // Add missed opening brackets/parentheses
  280. for (let i = lastFlushDepth - 1; i >= flushDepth; i--) {
  281. jsonParseOffset--;
  282. fragment = (stack[i] === STACK_OBJECT ? '{' : '[') + fragment;
  283. }
  284. parseAndAppend(fragment, false);
  285. mergeArraySlices();
  286. for (let i = lastFlushDepth - 1; i >= flushDepth; i--) {
  287. currentRootValueCursor = currentRootValueCursor.prev;
  288. }
  289. }
  290. if (flushDepth === 0) {
  291. finishRootValue();
  292. }
  293. lastFlushDepth = flushDepth;
  294. seenNonWhiteSpace = false;
  295. }
  296. function ensureChunkString(chunk) {
  297. if (typeof chunk !== 'string') {
  298. // Suppose chunk is Buffer or Uint8Array
  299. // Prepend uncompleted byte sequence if any
  300. if (pendingByteSeq !== null) {
  301. const origRawChunk = chunk;
  302. chunk = new Uint8Array(pendingByteSeq.length + origRawChunk.length);
  303. chunk.set(pendingByteSeq);
  304. chunk.set(origRawChunk, pendingByteSeq.length);
  305. pendingByteSeq = null;
  306. }
  307. // In case Buffer/Uint8Array, an input is encoded in UTF8
  308. // Seek for parts of uncompleted UTF8 symbol on the ending
  309. // This makes sense only if we expect more chunks and last char is not multi-bytes
  310. if (chunk[chunk.length - 1] > 127) {
  311. for (let seqLength = 0; seqLength < chunk.length; seqLength++) {
  312. const byte = chunk[chunk.length - 1 - seqLength];
  313. // 10xxxxxx - 2nd, 3rd or 4th byte
  314. // 110xxxxx – first byte of 2-byte sequence
  315. // 1110xxxx - first byte of 3-byte sequence
  316. // 11110xxx - first byte of 4-byte sequence
  317. if (byte >> 6 === 3) {
  318. seqLength++;
  319. // If the sequence is really incomplete, then preserve it
  320. // for the future chunk and cut off it from the current chunk
  321. if ((seqLength !== 4 && byte >> 3 === 0b11110) ||
  322. (seqLength !== 3 && byte >> 4 === 0b1110) ||
  323. (seqLength !== 2 && byte >> 5 === 0b110)) {
  324. pendingByteSeq = chunk.slice(chunk.length - seqLength); // use slice to avoid tying chunk
  325. chunk = chunk.subarray(0, -seqLength); // use subarray to avoid buffer copy
  326. }
  327. break;
  328. }
  329. }
  330. }
  331. // Convert chunk to a string, since single decode per chunk
  332. // is much effective than decode multiple small substrings
  333. chunk = decoder.decode(chunk);
  334. }
  335. return chunk;
  336. }
  337. function push(chunk) {
  338. chunk = ensureChunkString(chunk);
  339. const chunkLength = chunk.length;
  340. const prevParsedChunkLength = parsedChunkLength;
  341. let lastFlushPoint = 0;
  342. let flushPoint = 0;
  343. // Main scan loop
  344. scan: for (let i = 0; i < chunkLength; i++) {
  345. if (stateString) {
  346. for (; i < chunkLength; i++) {
  347. if (stateStringEscape) {
  348. stateStringEscape = false;
  349. } else {
  350. switch (chunk.charCodeAt(i)) {
  351. case 0x22: /* " */
  352. stateString = false;
  353. continue scan;
  354. case 0x5C: /* \ */
  355. stateStringEscape = true;
  356. }
  357. }
  358. }
  359. break;
  360. }
  361. switch (chunk.charCodeAt(i)) {
  362. case 0x22: /* " */
  363. stateString = true;
  364. stateStringEscape = false;
  365. seenNonWhiteSpace = true;
  366. break;
  367. case 0x2C: /* , */
  368. flushPoint = i;
  369. break;
  370. case 0x7B: /* { */
  371. // Open an object
  372. flushPoint = i + 1;
  373. stack[flushDepth++] = STACK_OBJECT;
  374. seenNonWhiteSpace = true;
  375. break;
  376. case 0x5B: /* [ */
  377. // Open an array
  378. flushPoint = i + 1;
  379. stack[flushDepth++] = STACK_ARRAY;
  380. seenNonWhiteSpace = true;
  381. break;
  382. case 0x5D: /* ] */
  383. case 0x7D: /* } */
  384. // Close an object or array
  385. flushPoint = i + 1;
  386. if (flushDepth === 0) {
  387. // Unmatched closing bracket/brace at top level, should fail to parse
  388. break scan;
  389. }
  390. flushDepth--;
  391. // Flush on depth decrease related to last flush, otherwise wait for more chunks to flush together
  392. if (flushDepth < lastFlushDepth) {
  393. flush(chunk, lastFlushPoint, flushPoint);
  394. lastFlushPoint = flushPoint;
  395. }
  396. break;
  397. case 0x09: /* \t */
  398. case 0x0A: /* \n */
  399. case 0x0D: /* \r */
  400. case 0x20: /* space */
  401. if (flushDepth === 0) {
  402. if (seenNonWhiteSpace) {
  403. flushPoint = i;
  404. flush(chunk, lastFlushPoint, flushPoint);
  405. lastFlushPoint = flushPoint;
  406. }
  407. if (parseMode !== MODE_JSON &&
  408. allowNewRootValue === false &&
  409. (chunk.charCodeAt(i) === 0x0A || chunk.charCodeAt(i) === 0x0D)
  410. ) {
  411. allowNewRootValue = true;
  412. }
  413. if (flushPoint === i) {
  414. parsedChunkLength++;
  415. }
  416. }
  417. // Move points forward when they point to current position and it's a whitespace
  418. if (lastFlushPoint === i) {
  419. lastFlushPoint++;
  420. }
  421. if (flushPoint === i) {
  422. flushPoint++;
  423. }
  424. break;
  425. default:
  426. seenNonWhiteSpace = true;
  427. }
  428. }
  429. if (flushPoint > lastFlushPoint) {
  430. flush(chunk, lastFlushPoint, flushPoint);
  431. }
  432. // Produce pendingChunk if something left
  433. if (flushPoint < chunkLength) {
  434. if (pendingChunk !== null) {
  435. // When there is already a pending chunk then no flush happened,
  436. // appending entire chunk to pending one
  437. pendingChunk += chunk;
  438. } else {
  439. // Create a pending chunk, it will start with non-whitespace since
  440. // flushPoint was moved forward away from whitespaces on scan
  441. pendingChunk = chunk.slice(flushPoint, chunkLength);
  442. }
  443. }
  444. consumedChunkLength += chunkLength;
  445. if (typeof onChunk === 'function') {
  446. onChunk(parsedChunkLength - prevParsedChunkLength, chunk, pendingChunk, state);
  447. }
  448. }
  449. function finish() {
  450. if (pendingChunk !== null || (currentRootValue === NO_VALUE && parseMode !== MODE_JSONL)) {
  451. // Force the `flushDepth < lastFlushDepth` branch in flush() to prepend missed
  452. // opening brackets/parentheses and produce a natural JSON.parse() EOF error
  453. flushDepth = 0;
  454. flush('', 0, 0);
  455. }
  456. if (typeof onChunk === 'function') {
  457. parsedChunkLength = consumedChunkLength;
  458. onChunk(0, null, null, state);
  459. }
  460. if (typeof onRootValue === 'function') {
  461. return rootValuesCount;
  462. }
  463. return rootValues !== null ? rootValues : currentRootValue;
  464. }
  465. }
  466. exports.parseChunked = parseChunked;