@@ -380,29 +380,44 @@ function printer(
380380 refs : Refs ,
381381 hasCalledToJSON ?: boolean ,
382382) : string {
383+ let result : string
384+
383385 const plugin = findPlugin ( config . plugins , val )
384386 if ( plugin !== null ) {
385- return printPlugin ( plugin , val , config , indentation , depth , refs )
387+ result = printPlugin ( plugin , val , config , indentation , depth , refs )
388+ }
389+ else {
390+ const basicResult = printBasicValue (
391+ val ,
392+ config . printFunctionName ,
393+ config . escapeRegex ,
394+ config . escapeString ,
395+ )
396+ if ( basicResult !== null ) {
397+ result = basicResult
398+ }
399+ else {
400+ result = printComplexValue (
401+ val ,
402+ config ,
403+ indentation ,
404+ depth ,
405+ refs ,
406+ hasCalledToJSON ,
407+ )
408+ }
386409 }
387410
388- const basicResult = printBasicValue (
389- val ,
390- config . printFunctionName ,
391- config . escapeRegex ,
392- config . escapeString ,
393- )
394- if ( basicResult !== null ) {
395- return basicResult
411+ // Check string length budget:
412+ // accumulate output length and if exceeded,
413+ // force no further recursion by patching maxDepth.
414+ // Inspired by Node's util.inspect bail out approach.
415+ config . outputLength += result . length
416+ if ( config . outputLength > config . maxOutputLength ) {
417+ config . maxDepth = 0
396418 }
397419
398- return printComplexValue (
399- val ,
400- config ,
401- indentation ,
402- depth ,
403- refs ,
404- hasCalledToJSON ,
405- )
420+ return result
406421}
407422
408423const DEFAULT_THEME : Theme = {
@@ -425,6 +440,9 @@ export const DEFAULT_OPTIONS: Options = {
425440 highlight : false ,
426441 indent : 2 ,
427442 maxDepth : Number . POSITIVE_INFINITY ,
443+ // Practical default hard-limit to avoid too long string being generated
444+ // (Node's limit is buffer.constants.MAX_STRING_LENGTH ~ 512MB)
445+ maxOutputLength : 1_000_000 ,
428446 maxWidth : Number . POSITIVE_INFINITY ,
429447 min : false ,
430448 plugins : [ ] ,
@@ -509,6 +527,8 @@ function getConfig(options?: OptionsReceived): Config {
509527 printShadowRoot : options ?. printShadowRoot ?? true ,
510528 spacingInner : options ?. min ? ' ' : '\n' ,
511529 spacingOuter : options ?. min ? '' : '\n' ,
530+ maxOutputLength : options ?. maxOutputLength ?? DEFAULT_OPTIONS . maxOutputLength ,
531+ outputLength : 0 ,
512532 }
513533}
514534
0 commit comments