From ef62e5a59e67f07fa1f5c94790e1cb45df997797 Mon Sep 17 00:00:00 2001 From: Khafra Date: Wed, 22 Mar 2023 15:44:44 -0400 Subject: [PATCH] url: implement URL.canParse PR-URL: https://github.com/nodejs/node/pull/47179 Reviewed-By: Yagiz Nizipli Reviewed-By: Debadree Chatterjee --- benchmark/url/whatwgurl-canParse.js | 14 +++++++ doc/api/url.md | 21 ++++++++++ lib/internal/url.js | 17 ++++++++ src/node_url.cc | 26 ++++++++++++ test/fixtures/wpt/README.md | 2 +- .../wpt/url/url-statics-canparse.any.js | 42 +++++++++++++++++++ test/fixtures/wpt/versions.json | 2 +- 7 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 benchmark/url/whatwgurl-canParse.js create mode 100644 test/fixtures/wpt/url/url-statics-canparse.any.js diff --git a/benchmark/url/whatwgurl-canParse.js b/benchmark/url/whatwgurl-canParse.js new file mode 100644 index 00000000000000..65741d9884f106 --- /dev/null +++ b/benchmark/url/whatwgurl-canParse.js @@ -0,0 +1,14 @@ +'use strict'; +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + type: Object.keys(common.urls), + n: [25e6], +}); + +function main({ type, n }) { + bench.start(); + for (let i = 0; i < n; i += 1) + URL.canParse(common.urls[type]); + bench.end(n); +} diff --git a/doc/api/url.md b/doc/api/url.md index ab8b4154ff023e..de4a4cb85bce37 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -662,6 +662,27 @@ added: v16.7.0 Removes the stored {Blob} identified by the given ID. Attempting to revoke a ID that isn't registered will silently fail. +#### `URL.canParse(input[, base])` + + + +* `input` {string} The absolute or relative input URL to parse. If `input` + is relative, then `base` is required. If `input` is absolute, the `base` + is ignored. If `input` is not a string, it is [converted to a string][] first. +* `base` {string} The base URL to resolve against if the `input` is not + absolute. If `base` is not a string, it is [converted to a string][] first. +* Returns: {boolean} + +Checks if an `input` relative to the `base` can be parsed to a `URL`. + +```js +const isValid = URL.canParse('/foo', 'https://example.org/'); // true + +const isNotValid = URL.canParse('/foo'); // false +``` + ### Class: `URLSearchParams`