parse-chunked.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. const { isReadableStream } = require('./utils');
  2. const TextDecoder = require('./text-decoder');
  3. const STACK_OBJECT = 1;
  4. const STACK_ARRAY = 2;
  5. const decoder = new TextDecoder();
  6. function isObject(value) {
  7. return value !== null && typeof value === 'object';
  8. }
  9. function adjustPosition(error, parser) {
  10. if (error.name === 'SyntaxError' && parser.jsonParseOffset) {
  11. error.message = error.message.replace(/at position (\d+)/, (_, pos) =>
  12. 'at position ' + (Number(pos) + parser.jsonParseOffset)
  13. );
  14. }
  15. return error;
  16. }
  17. function append(array, elements) {
  18. // Note: Avoid to use array.push(...elements) since it may lead to
  19. // "RangeError: Maximum call stack size exceeded" for a long arrays
  20. const initialLength = array.length;
  21. array.length += elements.length;
  22. for (let i = 0; i < elements.length; i++) {
  23. array[initialLength + i] = elements[i];
  24. }
  25. }
  26. module.exports = function(chunkEmitter) {
  27. let parser = new ChunkParser();
  28. if (isObject(chunkEmitter) && isReadableStream(chunkEmitter)) {
  29. return new Promise((resolve, reject) => {
  30. chunkEmitter
  31. .on('data', chunk => {
  32. try {
  33. parser.push(chunk);
  34. } catch (e) {
  35. reject(adjustPosition(e, parser));
  36. parser = null;
  37. }
  38. })
  39. .on('error', (e) => {
  40. parser = null;
  41. reject(e);
  42. })
  43. .on('end', () => {
  44. try {
  45. resolve(parser.finish());
  46. } catch (e) {
  47. reject(adjustPosition(e, parser));
  48. } finally {
  49. parser = null;
  50. }
  51. });
  52. });
  53. }
  54. if (typeof chunkEmitter === 'function') {
  55. const iterator = chunkEmitter();
  56. if (isObject(iterator) && (Symbol.iterator in iterator || Symbol.asyncIterator in iterator)) {
  57. return new Promise(async (resolve, reject) => {
  58. try {
  59. for await (const chunk of iterator) {
  60. parser.push(chunk);
  61. }
  62. resolve(parser.finish());
  63. } catch (e) {
  64. reject(adjustPosition(e, parser));
  65. } finally {
  66. parser = null;
  67. }
  68. });
  69. }
  70. }
  71. throw new Error(
  72. 'Chunk emitter should be readable stream, generator, ' +
  73. 'async generator or function returning an iterable object'
  74. );
  75. };
  76. class ChunkParser {
  77. constructor() {
  78. this.value = undefined;
  79. this.valueStack = null;
  80. this.stack = new Array(100);
  81. this.lastFlushDepth = 0;
  82. this.flushDepth = 0;
  83. this.stateString = false;
  84. this.stateStringEscape = false;
  85. this.pendingByteSeq = null;
  86. this.pendingChunk = null;
  87. this.chunkOffset = 0;
  88. this.jsonParseOffset = 0;
  89. }
  90. parseAndAppend(fragment, wrap) {
  91. // Append new entries or elements
  92. if (this.stack[this.lastFlushDepth - 1] === STACK_OBJECT) {
  93. if (wrap) {
  94. this.jsonParseOffset--;
  95. fragment = '{' + fragment + '}';
  96. }
  97. Object.assign(this.valueStack.value, JSON.parse(fragment));
  98. } else {
  99. if (wrap) {
  100. this.jsonParseOffset--;
  101. fragment = '[' + fragment + ']';
  102. }
  103. append(this.valueStack.value, JSON.parse(fragment));
  104. }
  105. }
  106. prepareAddition(fragment) {
  107. const { value } = this.valueStack;
  108. const expectComma = Array.isArray(value)
  109. ? value.length !== 0
  110. : Object.keys(value).length !== 0;
  111. if (expectComma) {
  112. // Skip a comma at the beginning of fragment, otherwise it would
  113. // fail to parse
  114. if (fragment[0] === ',') {
  115. this.jsonParseOffset++;
  116. return fragment.slice(1);
  117. }
  118. // When value (an object or array) is not empty and a fragment
  119. // doesn't start with a comma, a single valid fragment starting
  120. // is a closing bracket. If it's not, a prefix is adding to fail
  121. // parsing. Otherwise, the sequence of chunks can be successfully
  122. // parsed, although it should not, e.g. ["[{}", "{}]"]
  123. if (fragment[0] !== '}' && fragment[0] !== ']') {
  124. this.jsonParseOffset -= 3;
  125. return '[[]' + fragment;
  126. }
  127. }
  128. return fragment;
  129. }
  130. flush(chunk, start, end) {
  131. let fragment = chunk.slice(start, end);
  132. // Save position correction an error in JSON.parse() if any
  133. this.jsonParseOffset = this.chunkOffset + start;
  134. // Prepend pending chunk if any
  135. if (this.pendingChunk !== null) {
  136. fragment = this.pendingChunk + fragment;
  137. this.jsonParseOffset -= this.pendingChunk.length;
  138. this.pendingChunk = null;
  139. }
  140. if (this.flushDepth === this.lastFlushDepth) {
  141. // Depth didn't changed, so it's a root value or entry/element set
  142. if (this.flushDepth > 0) {
  143. this.parseAndAppend(this.prepareAddition(fragment), true);
  144. } else {
  145. // That's an entire value on a top level
  146. this.value = JSON.parse(fragment);
  147. this.valueStack = {
  148. value: this.value,
  149. prev: null
  150. };
  151. }
  152. } else if (this.flushDepth > this.lastFlushDepth) {
  153. // Add missed closing brackets/parentheses
  154. for (let i = this.flushDepth - 1; i >= this.lastFlushDepth; i--) {
  155. fragment += this.stack[i] === STACK_OBJECT ? '}' : ']';
  156. }
  157. if (this.lastFlushDepth === 0) {
  158. // That's a root value
  159. this.value = JSON.parse(fragment);
  160. this.valueStack = {
  161. value: this.value,
  162. prev: null
  163. };
  164. } else {
  165. this.parseAndAppend(this.prepareAddition(fragment), true);
  166. }
  167. // Move down to the depths to the last object/array, which is current now
  168. for (let i = this.lastFlushDepth || 1; i < this.flushDepth; i++) {
  169. let value = this.valueStack.value;
  170. if (this.stack[i - 1] === STACK_OBJECT) {
  171. // find last entry
  172. let key;
  173. // eslint-disable-next-line curly
  174. for (key in value);
  175. value = value[key];
  176. } else {
  177. // last element
  178. value = value[value.length - 1];
  179. }
  180. this.valueStack = {
  181. value,
  182. prev: this.valueStack
  183. };
  184. }
  185. } else /* this.flushDepth < this.lastFlushDepth */ {
  186. fragment = this.prepareAddition(fragment);
  187. // Add missed opening brackets/parentheses
  188. for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) {
  189. this.jsonParseOffset--;
  190. fragment = (this.stack[i] === STACK_OBJECT ? '{' : '[') + fragment;
  191. }
  192. this.parseAndAppend(fragment, false);
  193. for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) {
  194. this.valueStack = this.valueStack.prev;
  195. }
  196. }
  197. this.lastFlushDepth = this.flushDepth;
  198. }
  199. push(chunk) {
  200. if (typeof chunk !== 'string') {
  201. // Suppose chunk is Buffer or Uint8Array
  202. // Prepend uncompleted byte sequence if any
  203. if (this.pendingByteSeq !== null) {
  204. const origRawChunk = chunk;
  205. chunk = new Uint8Array(this.pendingByteSeq.length + origRawChunk.length);
  206. chunk.set(this.pendingByteSeq);
  207. chunk.set(origRawChunk, this.pendingByteSeq.length);
  208. this.pendingByteSeq = null;
  209. }
  210. // In case Buffer/Uint8Array, an input is encoded in UTF8
  211. // Seek for parts of uncompleted UTF8 symbol on the ending
  212. // This makes sense only if we expect more chunks and last char is not multi-bytes
  213. if (chunk[chunk.length - 1] > 127) {
  214. for (let seqLength = 0; seqLength < chunk.length; seqLength++) {
  215. const byte = chunk[chunk.length - 1 - seqLength];
  216. // 10xxxxxx - 2nd, 3rd or 4th byte
  217. // 110xxxxx – first byte of 2-byte sequence
  218. // 1110xxxx - first byte of 3-byte sequence
  219. // 11110xxx - first byte of 4-byte sequence
  220. if (byte >> 6 === 3) {
  221. seqLength++;
  222. // If the sequence is really incomplete, then preserve it
  223. // for the future chunk and cut off it from the current chunk
  224. if ((seqLength !== 4 && byte >> 3 === 0b11110) ||
  225. (seqLength !== 3 && byte >> 4 === 0b1110) ||
  226. (seqLength !== 2 && byte >> 5 === 0b110)) {
  227. this.pendingByteSeq = chunk.slice(chunk.length - seqLength);
  228. chunk = chunk.slice(0, -seqLength);
  229. }
  230. break;
  231. }
  232. }
  233. }
  234. // Convert chunk to a string, since single decode per chunk
  235. // is much effective than decode multiple small substrings
  236. chunk = decoder.decode(chunk);
  237. }
  238. const chunkLength = chunk.length;
  239. let lastFlushPoint = 0;
  240. let flushPoint = 0;
  241. // Main scan loop
  242. scan: for (let i = 0; i < chunkLength; i++) {
  243. if (this.stateString) {
  244. for (; i < chunkLength; i++) {
  245. if (this.stateStringEscape) {
  246. this.stateStringEscape = false;
  247. } else {
  248. switch (chunk.charCodeAt(i)) {
  249. case 0x22: /* " */
  250. this.stateString = false;
  251. continue scan;
  252. case 0x5C: /* \ */
  253. this.stateStringEscape = true;
  254. }
  255. }
  256. }
  257. break;
  258. }
  259. switch (chunk.charCodeAt(i)) {
  260. case 0x22: /* " */
  261. this.stateString = true;
  262. this.stateStringEscape = false;
  263. break;
  264. case 0x2C: /* , */
  265. flushPoint = i;
  266. break;
  267. case 0x7B: /* { */
  268. // Open an object
  269. flushPoint = i + 1;
  270. this.stack[this.flushDepth++] = STACK_OBJECT;
  271. break;
  272. case 0x5B: /* [ */
  273. // Open an array
  274. flushPoint = i + 1;
  275. this.stack[this.flushDepth++] = STACK_ARRAY;
  276. break;
  277. case 0x5D: /* ] */
  278. case 0x7D: /* } */
  279. // Close an object or array
  280. flushPoint = i + 1;
  281. this.flushDepth--;
  282. if (this.flushDepth < this.lastFlushDepth) {
  283. this.flush(chunk, lastFlushPoint, flushPoint);
  284. lastFlushPoint = flushPoint;
  285. }
  286. break;
  287. case 0x09: /* \t */
  288. case 0x0A: /* \n */
  289. case 0x0D: /* \r */
  290. case 0x20: /* space */
  291. // Move points forward when they points on current position and it's a whitespace
  292. if (lastFlushPoint === i) {
  293. lastFlushPoint++;
  294. }
  295. if (flushPoint === i) {
  296. flushPoint++;
  297. }
  298. break;
  299. }
  300. }
  301. if (flushPoint > lastFlushPoint) {
  302. this.flush(chunk, lastFlushPoint, flushPoint);
  303. }
  304. // Produce pendingChunk if something left
  305. if (flushPoint < chunkLength) {
  306. if (this.pendingChunk !== null) {
  307. // When there is already a pending chunk then no flush happened,
  308. // appending entire chunk to pending one
  309. this.pendingChunk += chunk;
  310. } else {
  311. // Create a pending chunk, it will start with non-whitespace since
  312. // flushPoint was moved forward away from whitespaces on scan
  313. this.pendingChunk = chunk.slice(flushPoint, chunkLength);
  314. }
  315. }
  316. this.chunkOffset += chunkLength;
  317. }
  318. finish() {
  319. if (this.pendingChunk !== null) {
  320. this.flush('', 0, 0);
  321. this.pendingChunk = null;
  322. }
  323. return this.value;
  324. }
  325. };