Add XHR response modifier

- Add ResponseModifier class which is responsible for handling the
  modification of the responses intercepted by XHRProxy. The
  modifications occur by processing requests via several individual
  response modifiers sequentially, which are applied if the URL matches
  a RegEx condition and, if applicable, passes a condition based on the
  features enabled by the user.

- A sample response modifier called "demo" is included, to show how a
  simple modifier would work.

- Add mainWorldOptionsWatcher with 2 components: a server and a client,
  so main world scripts (clients) can retrieve the extension options via
  their corresponding content scripts (the servers) using an
  OptionsWatcher class instantiated by the server. This is used by the
  ResponseModifier class since it's injected into the main world because
  it's the only way to intercept requests.

Bug: twpowertools:153
Change-Id: I8a9767e1eadd60d3a0f1054669e1e1f5e7a49fbb
diff --git a/src/xhrInterceptor/utils.js b/src/xhrInterceptor/utils.js
index 909549b..849c543 100644
--- a/src/xhrInterceptor/utils.js
+++ b/src/xhrInterceptor/utils.js
@@ -1,4 +1,4 @@
-import {correctArrayKeys} from '../common/protojs';
+import {correctArrayKeys, inverseCorrectArrayKeys} from '../common/protojs';
 
 import xhrInterceptors from './interceptors.json5';
 
@@ -52,7 +52,7 @@
     let rawResponse = dec.decode(byteArray);
     response = JSON.parse(rawResponse);
   } else if (xhr.responseType === 'text' || xhr.responseType === '') {
-    response = JSON.parse(xhr.responseText);
+    response = JSON.parse(xhr.response);
   } else if (xhr.responseType === 'json') {
     response = xhr.response;
   } else {
@@ -66,6 +66,29 @@
   return response;
 }
 
+export function convertJSONToResponse(xhr, json) {
+  if (xhr.$isArrayProto) json = inverseCorrectArrayKeys(json);
+
+  switch (xhr.responseType) {
+    case 'json':
+      return json;
+
+    case 'text':
+    case '':
+      return JSON.stringify(json);
+
+    case 'arraybuffer':
+      const encoder = new TextEncoder();
+      return encoder.encode(JSON.stringify(json)).buffer;
+
+    default:
+      console.error(
+          'Unexpected responseType ' + xhr.responseType + '. Request url: ',
+          xhr.$TWPTRequestURL || xhr.responseURL);
+      return undefined;
+  }
+}
+
 export function triggerEvent(eventName, body, id) {
   var evt = new CustomEvent('TWPT_' + eventName, {
     detail: {