1
1
'use strict' ;
2
2
3
3
const stringify = require ( './stringify' ) ;
4
+ const { isCorrectBraces, validateInput} = require ( './validate-input' ) ;
4
5
5
6
/**
6
7
* Constants
7
8
*/
8
9
9
10
const {
10
11
MAX_LENGTH ,
12
+ MAX_SYMBOLS ,
11
13
CHAR_BACKSLASH , /* \ */
12
14
CHAR_BACKTICK , /* ` */
13
15
CHAR_COMMA , /* , */
@@ -34,6 +36,11 @@ const parse = (input, options = {}) => {
34
36
}
35
37
36
38
let opts = options || { } ;
39
+
40
+ validateInput ( input , {
41
+ maxSymbols : opts . maxSymbols || MAX_SYMBOLS ,
42
+ } ) ;
43
+
37
44
let max = typeof opts . maxLength === 'number' ? Math . min ( MAX_LENGTH , opts . maxLength ) : MAX_LENGTH ;
38
45
if ( input . length > max ) {
39
46
throw new SyntaxError ( `Input length (${ input . length } ), exceeds max characters (${ max } )` ) ;
@@ -304,30 +311,43 @@ const parse = (input, options = {}) => {
304
311
push ( { type : 'text' , value } ) ;
305
312
}
306
313
314
+ flattenBlocks ( stack )
315
+ markImbalancedBraces ( ast ) ;
316
+ push ( { type : 'eos' } ) ;
317
+
318
+ return ast ;
319
+ } ;
320
+
321
+ module . exports = parse ;
322
+
323
+ function markImbalancedBraces ( { nodes} ) {
307
324
// Mark imbalanced braces and brackets as invalid
325
+ for ( const node of nodes ) {
326
+ if ( ! node . nodes && ! node . invalid ) {
327
+ if ( node . type === 'open' ) node . isOpen = true ;
328
+ if ( node . type === 'close' ) node . isClose = true ;
329
+ if ( ! node . nodes ) node . type = 'text' ;
330
+
331
+ node . invalid = true ;
332
+ }
333
+
334
+ delete node . parent ;
335
+ delete node . prev ;
336
+ }
337
+ }
338
+
339
+ function flattenBlocks ( stack ) {
340
+ let block ;
308
341
do {
309
342
block = stack . pop ( ) ;
310
343
311
- if ( block . type !== 'root' ) {
312
- block . nodes . forEach ( node => {
313
- if ( ! node . nodes ) {
314
- if ( node . type === 'open' ) node . isOpen = true ;
315
- if ( node . type === 'close' ) node . isClose = true ;
316
- if ( ! node . nodes ) node . type = 'text' ;
317
- node . invalid = true ;
318
- }
319
- } ) ;
344
+ if ( block . type === 'root' )
345
+ continue ;
320
346
321
- // get the location of the block on parent.nodes (block's siblings)
322
- let parent = stack [ stack . length - 1 ] ;
323
- let index = parent . nodes . indexOf ( block ) ;
324
- // replace the (invalid) block with it's nodes
325
- parent . nodes . splice ( index , 1 , ...block . nodes ) ;
326
- }
347
+ // get the location of the block on parent.nodes (block's siblings)
348
+ let parent = stack . at ( - 1 ) ;
349
+ let index = parent . nodes . indexOf ( block ) ;
350
+ // replace the (invalid) block with its nodes
351
+ parent . nodes . splice ( index , 1 , ...block . nodes ) ;
327
352
} while ( stack . length > 0 ) ;
328
-
329
- push ( { type : 'eos' } ) ;
330
- return ast ;
331
- } ;
332
-
333
- module . exports = parse ;
353
+ }
0 commit comments