Skip to content

Commit

Permalink
module: improve error message for invalid data URL
Browse files Browse the repository at this point in the history
Fixes: #37647

PR-URL: #37701
Reviewed-By: Derek Lewis <DerekNonGeneric@inf.is>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
  • Loading branch information
aduh95 authored and targos committed May 1, 2021
1 parent df54edc commit 079671d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
11 changes: 11 additions & 0 deletions lib/internal/modules/esm/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ require('internal/modules/cjs/loader');
const {
FunctionPrototypeBind,
ObjectSetPrototypeOf,
RegExpPrototypeExec,
SafeWeakMap,
StringPrototypeStartsWith,
} = primordials;

const {
ERR_INVALID_ARG_VALUE,
ERR_INVALID_MODULE_SPECIFIER,
ERR_INVALID_RETURN_PROPERTY,
ERR_INVALID_RETURN_PROPERTY_VALUE,
ERR_INVALID_RETURN_VALUE,
Expand Down Expand Up @@ -107,6 +109,15 @@ class Loader {
}

const { format } = getFormatResponse;
if (format === null) {
const dataUrl = RegExpPrototypeExec(
/^data:([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
url,
);
throw new ERR_INVALID_MODULE_SPECIFIER(
url,
dataUrl ? `has an unsupported MIME type "${dataUrl[1]}"` : '');
}
if (typeof format !== 'string') {
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
'string', 'loader getFormat', 'format', format);
Expand Down
2 changes: 1 addition & 1 deletion test/es-module/test-esm-data-urls.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ function createBase64URL(mime, body) {
await import(plainESMURL);
common.mustNotCall()();
} catch (e) {
assert.strictEqual(e.code, 'ERR_INVALID_RETURN_PROPERTY_VALUE');
assert.strictEqual(e.code, 'ERR_INVALID_MODULE_SPECIFIER');
}
}
})().then(common.mustCall());
24 changes: 24 additions & 0 deletions test/es-module/test-esm-invalid-data-urls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';
const common = require('../common');
const assert = require('assert');

(async () => {
await assert.rejects(import('data:text/plain,export default0'), {
code: 'ERR_INVALID_MODULE_SPECIFIER',
message:
'Invalid module "data:text/plain,export default0" has an unsupported ' +
'MIME type "text/plain"',
});
await assert.rejects(import('data:text/plain;base64,'), {
code: 'ERR_INVALID_MODULE_SPECIFIER',
message:
'Invalid module "data:text/plain;base64," has an unsupported ' +
'MIME type "text/plain"',
});
await assert.rejects(import('data:application/json,[]'), {
code: 'ERR_INVALID_MODULE_SPECIFIER',
message:
'Invalid module "data:application/json,[]" has an unsupported ' +
'MIME type "application/json"',
});
})().then(common.mustCall());

0 comments on commit 079671d

Please sign in to comment.