@@ -489,11 +489,31 @@ function boundedWorksheet(
489489 */
490490function engineStyles ( xml : string ) {
491491 const name = ( local : string ) => `<((?:[\\w.-]+:)?)${ local } \\b` ;
492- const block = ( local : string ) =>
493- new RegExp ( `${ name ( local ) } [^>]*>[\\s\\S]*?</\\1${ local } \\s*>` , "g" ) ;
492+ const blocks = new Map < string , { start : number ; end : number } > ( ) ;
493+ const parser = xmlParser ( ) ;
494+ let depth = 0 ;
495+ parser . on ( "opentag" , ( tag ) => {
496+ if ( ++ depth > 64 ) throw new Error ( "This workbook contains excessive XML nesting." ) ;
497+ if ( depth !== 2 || ! [ "numFmts" , "cellStyleXfs" , "cellXfs" ] . includes ( tag . local ) ) return ;
498+ if ( blocks . has ( tag . local ) )
499+ throw new Error ( "This workbook contains duplicate stylesheet blocks." ) ;
500+ blocks . set ( tag . local , {
501+ start : xml . lastIndexOf ( "<" , parser . position - 1 ) ,
502+ end : parser . position ,
503+ } ) ;
504+ } ) ;
505+ parser . on ( "closetag" , ( tag ) => {
506+ if ( depth === 2 ) {
507+ const block = blocks . get ( tag . local ) ;
508+ if ( block ) block . end = parser . position ;
509+ }
510+ depth -- ;
511+ } ) ;
512+ parser . write ( xml ) . close ( ) ;
494513 const id = / ( n u m F m t I d \s * = \s * ) ( [ " ' ] ) ( \d + ) \2/ g;
495514 const moved = new Map < string , number > ( ) ;
496- const formats = xml . match ( block ( "numFmts" ) ) ?. [ 0 ] ?? "" ;
515+ const formatBlock = blocks . get ( "numFmts" ) ;
516+ const formats = formatBlock ? xml . slice ( formatBlock . start , formatBlock . end ) : "" ;
497517 const used = new Set ( [ ...formats . matchAll ( id ) ] . map ( ( match ) => Number ( match [ 3 ] ) ) ) ;
498518 let next = 164 ;
499519 const renumber = ( part : string , assign : boolean ) =>
@@ -506,10 +526,19 @@ function engineStyles(xml: string) {
506526 const to = moved . get ( value ) ;
507527 return to === undefined ? attribute : `${ key } ${ quote } ${ to } ${ quote } ` ;
508528 } ) ;
509- return xml
510- . replace ( block ( "numFmts" ) , ( part ) => renumber ( part , true ) )
511- . replace ( block ( "cellStyleXfs" ) , ( part ) => renumber ( part , false ) )
512- . replace ( block ( "cellXfs" ) , ( part ) => renumber ( part , false ) )
529+ const numberedFormats = renumber ( formats , true ) ;
530+ const parts : string [ ] = [ ] ;
531+ let offset = 0 ;
532+ for ( const [ local , block ] of blocks ) {
533+ parts . push (
534+ xml . slice ( offset , block . start ) ,
535+ local === "numFmts" ? numberedFormats : renumber ( xml . slice ( block . start , block . end ) , false ) ,
536+ ) ;
537+ offset = block . end ;
538+ }
539+ parts . push ( xml . slice ( offset ) ) ;
540+ return parts
541+ . join ( "" )
513542 . replace (
514543 new RegExp (
515544 `${ name ( "u" ) } \\s+val\\s*=\\s*(["'])(?:single|double|singleAccounting|doubleAccounting)\\2\\s*/>` ,
0 commit comments