yahoo / serialize-javascript

Serialize JavaScript to a superset of JSON that includes regular expressions and functions.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Split responsibilities

c089 opened this issue · comments

commented

Just a quick thought I had when I read the changelog for 1.3.0: To me it seems to have two responsibilities and as such violate the SRP:

  1. prevent security issues by espacing unsafe characters
  2. serialize data that is not compatible with JSON

Instead of having a isJSON flag that controls wether one of those functionalities should be ignored, there could be two functions:

const escapeUnsafe = (o) => ...
const serializeNonJSON = (o) => 

And a function that has the current behaviour could simply be composed of those functions:

const serializeJavascript = compose(escapeUnsafe, serializeNonJSON);

(For performance reasons a different implementation may be necessary in JS of course)

I agree that the option is not the best API, but it's a tradeoff for speed. And the string has to be escaped before the functions and regexp are added back into it after passing though JSON.stringify(). The order is:

  1. JSON.stringify() with replacer that inserts did placeholder strings for regexps and functions.
  2. Escape string to prevent XSS in <script> context
  3. Serialize regexps and functions and insert them where their placeholders are.

Since the escaping happens in the middle, the functions don't compose very cleanly.

commented

👍 Makes sense, was just curious to discuss my understanding of the design :)