@@ -66,13 +66,47 @@ export class Marshaller implements IMarshaller {
6666 return ( ) => data ;
6767 }
6868
69+ /**
70+ * Quotes the given string if needed. It will escape the string if it already starts and/or ends with a clashing quote.
71+ * @param {string } content
72+ * @returns {string }
73+ */
74+ private quoteIfNecessary ( content : string ) : string {
75+ if ( ! ( typeof content === "string" ) ) return content ;
76+ const firstChar = content [ 0 ] ;
77+ const lastChar = content [ content . length - 1 ] ;
78+ let str = "`" ;
79+ const startsWithClashingQuote = firstChar === "`" ;
80+ const endsWithClashingQuote = lastChar === "`" ;
81+ const startOffset = startsWithClashingQuote ? 1 : 0 ;
82+ const endOffset = endsWithClashingQuote ? 1 : 0 ;
83+ if ( startsWithClashingQuote ) str += "\`" ;
84+ str += content . slice ( startOffset , content . length - endOffset ) ;
85+ if ( endsWithClashingQuote ) str += "\`" ;
86+ str += "`" ;
87+ return str ;
88+ }
89+
6990 /**
7091 * Marshals an object into a string.
7192 * @param {object } data
7293 * @returns {string }
7394 */
7495 private marshalObjectToString < T > ( data : { [ key : string ] : T } ) : string {
75- return JSON . stringify ( data ) ;
96+ let str = "{" ;
97+ const space = " " ;
98+ const keys = Object . keys ( data ) ;
99+ keys . forEach ( ( key , index ) => {
100+ str += `"${ key } ":${ space } ` ;
101+ const value = data [ key ] ;
102+ const isString = typeof this . marshal ( value ) === "string" ;
103+ const marshalled = this . marshalToString ( value ) ;
104+ str += isString ? this . quoteIfNecessary ( < string > marshalled ) : marshalled ;
105+ if ( index !== keys . length - 1 ) str += `,${ space } ` ;
106+ } ) ;
107+ str += "}" ;
108+ return str ;
109+ // return JSON.stringify(data);
76110 }
77111
78112 /**
@@ -531,6 +565,7 @@ export class Marshaller implements IMarshaller {
531565 let trimmed = primitive
532566 . replace ( / ( [ { , : } " \] ] ) ( [ \t \r \n ] * ) / g, ( _ , p1 ) => `${ p1 } ` )
533567 . replace ( / ( [ { , ] ) ( \w + ) ( : ) / g, ( _ , p1 , p2 , p3 ) => `${ p1 } "${ p2 } "${ p3 } ` )
568+ . replace ( / ` ( [ ^ ` ] * ) ` / g, ( _ , p1 ) => `"${ p1 } "` )
534569 . trim ( ) ;
535570 if ( trimmed . endsWith ( ";" ) ) trimmed = trimmed . slice ( 0 , trimmed . length - 1 ) ;
536571 return this . marshalStringToObject ( trimmed , ++ attempt ) ;
0 commit comments