@@ -24,6 +24,7 @@ export const FUNCTION_BLOCK_DISPLAY_CODE_KEY = '_runtimeDisplayCode'
2424const logger = createLogger ( 'VariableResolver' )
2525
2626type ShellQuoteContext = 'single' | 'double' | null
27+ type CodeStringQuoteContext = ShellQuoteContext | 'template'
2728
2829export class VariableResolver {
2930 private resolvers : Resolver [ ]
@@ -351,14 +352,29 @@ export class VariableResolver {
351352 value : unknown
352353 ) : string {
353354 if ( language === 'python' ) {
354- return `globals()[${ JSON . stringify ( varName ) } ]`
355+ const expression = `globals()[${ JSON . stringify ( varName ) } ]`
356+ const quoteContext = this . getCodeStringQuoteContext ( template , matchIndex )
357+ if ( quoteContext === 'single' || quoteContext === 'double' ) {
358+ const quote = quoteContext === 'single' ? "'" : '"'
359+ return `${ quote } + json.dumps(${ expression } ) + ${ quote } `
360+ }
361+ return expression
355362 }
356363
357364 if ( language === 'shell' ) {
358365 return this . formatShellContextVariableReference ( varName , template , matchIndex , value )
359366 }
360367
361- return `globalThis[${ JSON . stringify ( varName ) } ]`
368+ const expression = `globalThis[${ JSON . stringify ( varName ) } ]`
369+ const quoteContext = this . getCodeStringQuoteContext ( template , matchIndex )
370+ if ( quoteContext === 'template' ) {
371+ return `\${JSON.stringify(${ expression } )}`
372+ }
373+ if ( quoteContext === 'single' || quoteContext === 'double' ) {
374+ const quote = quoteContext === 'single' ? "'" : '"'
375+ return `${ quote } + JSON.stringify(${ expression } ) + ${ quote } `
376+ }
377+ return expression
362378 }
363379
364380 private formatDisplayValueForCodeContext (
@@ -397,6 +413,27 @@ export class VariableResolver {
397413 return JSON . stringify ( value )
398414 }
399415
416+ private getCodeStringQuoteContext ( template : string , index : number ) : CodeStringQuoteContext {
417+ let quoteContext : CodeStringQuoteContext = null
418+
419+ for ( let i = 0 ; i < index ; i ++ ) {
420+ const char = template [ i ]
421+ if ( quoteContext !== null && char === '\\' ) {
422+ i ++
423+ continue
424+ }
425+ if ( char === "'" && quoteContext !== 'double' && quoteContext !== 'template' ) {
426+ quoteContext = quoteContext === 'single' ? null : 'single'
427+ } else if ( char === '"' && quoteContext !== 'single' && quoteContext !== 'template' ) {
428+ quoteContext = quoteContext === 'double' ? null : 'double'
429+ } else if ( char === '`' && quoteContext !== 'single' && quoteContext !== 'double' ) {
430+ quoteContext = quoteContext === 'template' ? null : 'template'
431+ }
432+ }
433+
434+ return quoteContext
435+ }
436+
400437 private formatShellContextVariableReference (
401438 varName : string ,
402439 template : string ,
0 commit comments