sanitize extension ID in getExtensionIdForOpcode

This commit is contained in:
Christopher Willis-Ford 2020-06-15 17:41:35 -07:00
parent b67ba75d8b
commit 90b9da45f4
3 changed files with 10 additions and 2 deletions
docs
src/serialization
test/unit

View file

@ -310,6 +310,7 @@ class SomeBlocks {
return { return {
// Required: the machine-readable name of this extension. // Required: the machine-readable name of this extension.
// Will be used as the extension's namespace. // Will be used as the extension's namespace.
// Allowed characters are those matching the regular expression [\w-]: A-Z, a-z, 0-9, and hyphen ("-").
id: 'someBlocks', id: 'someBlocks',
// Core extensions only: override the default extension block colors. // Core extensions only: override the default extension block colors.

View file

@ -273,13 +273,17 @@ const compressInputTree = function (block, blocks) {
}; };
/** /**
* Get non-core extension ID for a given sb3 opcode. * Get sanitized non-core extension ID for a given sb3 opcode.
* Note that this should never return a URL. If in the future the SB3 loader supports loading extensions by URL, this
* ID should be used to (for example) look up the extension's full URL from a table in the SB3's JSON.
* @param {!string} opcode The opcode to examine for extension. * @param {!string} opcode The opcode to examine for extension.
* @return {?string} The extension ID, if it exists and is not a core extension. * @return {?string} The extension ID, if it exists and is not a core extension.
*/ */
const getExtensionIdForOpcode = function (opcode) { const getExtensionIdForOpcode = function (opcode) {
// Allowed ID characters are those matching the regular expression [\w-]: A-Z, a-z, 0-9, and hyphen ("-").
const index = opcode.indexOf('_'); const index = opcode.indexOf('_');
const prefix = opcode.substring(0, index); const forbiddenSymbols = /[^\w-]/g;
const prefix = opcode.substring(0, index).replace(forbiddenSymbols, '-');
if (CORE_EXTENSIONS.indexOf(prefix) === -1) { if (CORE_EXTENSIONS.indexOf(prefix) === -1) {
if (prefix !== '') return prefix; if (prefix !== '') return prefix;
} }

View file

@ -290,6 +290,9 @@ test('getExtensionIdForOpcode', t => {
// does not return anything for opcodes with no extension // does not return anything for opcodes with no extension
t.false(sb3.getExtensionIdForOpcode('hello')); t.false(sb3.getExtensionIdForOpcode('hello'));
// forbidden characters must be replaced with '-'
t.equal(sb3.getExtensionIdForOpcode('hi:there/happy_people'), 'hi-there-happy');
t.end(); t.end();
}); });