feat(tests): Use a proper quote function

We need to generate string literals.  Best to use a quote function
instead of concatenating on quote marks withou escaping.  Copy a
well-tested one from Code City.
This commit is contained in:
Christopher Allen
2022-06-07 16:09:36 +01:00
parent b021e0da2f
commit c55b30d3bb

47
tests/bootstrap.js vendored
View File

@@ -125,11 +125,11 @@
' window.BlocklyMsg = window.Blockly.Msg;\n' +
' delete window.Blockly;\n' +
'</script>\n');
const requires = options.requires.map(r => '\'' + r + '\'').join();
const allRequires = options.requires.map(quote).join();
document.write(
'<script>\n' +
' window.BlocklyLoader = new Promise((resolve, reject) => {\n' +
' goog.bootstrap([' + requires + '], resolve);\n' +
' goog.bootstrap([' + allRequires + '], resolve);\n' +
' }).then(() => {\n' +
' // Copy Messages from temp Blockly.Msg object to the real one:\n' +
' Object.assign(goog.module.get(\'Blockly\').Msg,\n' +
@@ -147,4 +147,47 @@
'<script src="' + options.root + scripts[i] + '"></script>');
}
}
return; // All done. Only helper functions after this point.
/**
* Convert a string into a string literal. Strictly speaking we
* only need to escape backslash, \r, \n, \u2028 (line separator),
* \u2029 (paragraph separator) and whichever quote character we're
* using, but for simplicity we escape all the control characters.
*
* Based on https://github.com/google/CodeCity/blob/master/server/code.js
*
* @param {string} str The string to convert.
* @return {string} The value s as a eval-able string literal.
*/
function quote(str) {
/* eslint-disable no-control-regex, no-multi-spaces */
/** Regexp for characters to be escaped in a single-quoted string. */
const singleRE = /[\x00-\x1f\\\u2028\u2029']/g;
/** Map of control character replacements. */
const replacements = {
'\x00': '\\0', '\x01': '\\x01', '\x02': '\\x02', '\x03': '\\x03',
'\x04': '\\x04', '\x05': '\\x05', '\x06': '\\x06', '\x07': '\\x07',
'\x08': '\\b', '\x09': '\\t', '\x0a': '\\n', '\x0b': '\\v',
'\x0c': '\\f', '\x0d': '\\r', '\x0e': '\\x0e', '\x0f': '\\x0f',
'"': '\\"', "'": "\\'", '\\': '\\\\',
'\u2028': '\\u2028', '\u2029': '\\u2029',
};
/* eslint-enable no-control-regex, no-multi-spaces */
/**
* Replacer function.
* @param {string} c Single UTF-16 code unit ("character") string to
* be replaced.
* @return {string} Multi-character string containing escaped
* representation of c.
*/
function replace(c) {
return replacements[c];
}
return "'" + str.replace(singleRE, replace) + "'";
}
})();