diff --git a/lib/utils.js b/lib/utils.js index 4f0be041..a0434d58 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -100,13 +100,24 @@ exports.escapeXML = function (markup) { .replace(_MATCH_HTML, encode_char); }; -// If the Object prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property -// cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict -// mode, attempting that will be silently ignored. -// However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object. -Object.defineProperty(exports.escapeXML, 'toString', function () { +function escapeXMLToString() { return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr; -}); +} + +try { + if (typeof Object.defineProperty === 'function') { + // If the Function prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property + // cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict + // mode, attempting that will be silently ignored. + // However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object. + Object.defineProperty(exports.escapeXML, 'toString', { value: escapeXMLToString }); + } else { + // If Object.defineProperty() doesn't exist, attempt to shadow this property using the assignment operator. + exports.escapeXML.toString = escapeXMLToString; + } +} catch (err) { + console.warn('Unable to set escapeXML.toString (is the Function prototype frozen?)'); +} /** * Naive copy of properties from one object to another. diff --git a/package.json b/package.json index 047f6ee1..88b28a98 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,6 @@ "node": ">=0.10.0" }, "scripts": { - "test": "mocha" + "test": "mocha -u tdd" } } diff --git a/test/utils.js b/test/utils.js index 327e9171..0dd56561 100644 --- a/test/utils.js +++ b/test/utils.js @@ -83,8 +83,27 @@ suite('unit testing exported functions of module \'utils.js\'', function () { */ suite('unit testing function \'escapeXML\' of module \'utils.js\'', function () { test('it should be callable without parameters', function () { + const stringified = +`function (markup) { + return markup == undefined + ? '' + : String(markup) + .replace(_MATCH_HTML, encode_char); +}; +var _ENCODE_HTML_RULES = { + "&": "&" + , "<": "<" + , ">": ">" + , '"': """ + , "'": "'" + } + , _MATCH_HTML = /[&<>'"]/g; +function encode_char(c) { + return _ENCODE_HTML_RULES[c] || c; +}; +`; assert.doesNotThrow(() => { utils.escapeXML.toString(); }); - assert.ok(typeof(utils.escapeXML.toString())==='string'); + assert.ok(utils.escapeXML.toString()===stringified); }); });