nodejs/node · #67807
url: add experimental URLPatternList
benchmark/url/urlpatternlist-exec.jsadded48 + / 0 −
@@ -0,0 +1,48 @@+'use strict';+const common = require('../common.js');+const { URLPattern, URLPatternList } = require('url');+const assert = require('assert');++const bench = common.createBenchmark(main, {+ routes: [10, 100, 1000],+ input: ['first', 'last', 'none'],+ method: ['URLPatternList', 'URLPattern'],+ n: [1e4],+}, {+ flags: ['--disable-warning=ExperimentalWarning'],+});++function main({ routes, input, method, n }) {+ const patterns = [];+ for (let i = 0; i < routes; i++) {+ patterns.push(new URLPattern({ pathname: `/api/resource${i}/:id` }));+ }+ const url = {+ first: 'https://example.com/api/resource0/42',+ last: `https://example.com/api/resource${routes - 1}/42`,+ none: 'https://example.com/api/missing/42',+ }[input];++ let exec;+ if (method === 'URLPatternList') {+ const list = new URLPatternList(patterns);+ exec = (url) => list.exec(url);+ } else {+ // The loop that URLPatternList#exec() is specified as.+ exec = (url) => {+ for (const pattern of patterns) {+ const result = pattern.exec(url);+ if (result !== null) return result;+ }+ return null;+ };+ }++ let result;+ bench.start();+ for (let i = 0; i < n; i++) {+ result = exec(url);+ }+ bench.end(n);+ assert.strictEqual(result === null, input === 'none');+}doc/api/url.md175 + / 0 −
@@ -755,6 +755,8 @@ console.log(myPattern.test('https://nodejs.org/docs/latest/api/dns.html')); // Prints: true ``` +To find which of several patterns matches a URL, see [`URLPatternList`][].+ #### `new URLPattern()` Instantiate a new empty `URLPattern` object.@@ -846,6 +848,175 @@ console.log(myPattern.test('https://nodejs.org/docs/latest/api/dns.html')); // Prints: true ``` +### Class: `URLPatternList`++<!-- YAML+added: REPLACEME+-->++> Stability: 1.0 - Early development++A `URLPatternList` matches a URL against an ordered list of {URLPattern}+objects and reports the first pattern that matches. `URLPatternList` is+not a standard API, and it is not yet clear whether it will become one.+It implements the interface proposed in [whatwg/urlpattern#166][].++The result is the same as calling [`urlPattern.exec()`][] on each pattern in+list order and keeping the first result that is not `null`. A `URLPatternList`+processes the input once per call instead of once per pattern, and uses an+index of the patterns' pathnames to skip patterns that cannot match.++```mjs+import { URLPattern, URLPatternList } from 'node:url';++const patterns = [+ new URLPattern('https://example.com/'),+ new URLPattern('https://example.com/about'),+ new URLPattern('https://example.com/blog/:slug'),+];+const list = new URLPatternList(patterns);++const result = list.exec('https://example.com/blog/hello');+console.log(patterns.indexOf(result.pattern));+// Prints: 2+console.log(result.pathname.groups.slug);+// Prints: hello++console.log(list.test('https://example.com/contact'));+// Prints: false+```++```cjs+const { URLPattern, URLPatternList } = require('node:url');++const patterns = [+ new URLPattern('https://example.com/'),+ new URLPattern('https://example.com/about'),+ new URLPattern('https://example.com/blog/:slug'),+];+const list = new URLPatternList(patterns);++const result = list.exec('https://example.com/blog/hello');+console.log(patterns.indexOf(result.pattern));+// Prints: 2+console.log(result.pathname.groups.slug);+// Prints: hello++console.log(list.test('https://example.com/contact'));+// Prints: false+```++To attach data such as a route handler to each pattern, keep it in a {Map}+keyed by the `URLPattern` and look it up with `result.pattern`.++#### `new URLPatternList(patterns)`++* `patterns` {Iterable} The {URLPattern} objects to match against, in the order+ in which they are matched.++Creates a `URLPatternList` from the values of `patterns`, in iteration order.+Later changes to `patterns` do not affect the list.++The values must be `URLPattern` objects. Pattern strings, `URLPatternInit`+objects, and options such as `ignoreCase` are not accepted; pass them to the+{URLPattern} constructor instead. Each pattern keeps its own options, so a list+can mix case-sensitive and case-insensitive patterns.++A `TypeError` is thrown if `patterns` is not iterable, if one of its values is+not a `URLPattern`, if it contains the same `URLPattern` object more than once,+or if it is empty.++#### `urlPatternList.exec([input[, baseURL]])`++* `input` {string|Object} A URL string, or an object with the URL components+ to match, as accepted by [`urlPattern.exec()`][]. **Default:** `{}`.+* `baseURL` {string} A base URL string used to resolve `input` when it is a+ relative URL string.+* Returns: {Object|null}++Matches `input` against the patterns in list order. Returns `null` if no pattern+matches, which includes the case where `input` or `baseURL` is not a valid URL.+Otherwise, returns the result of [`urlPattern.exec()`][] for the first pattern+that matches, with an additional `pattern` property set to that `URLPattern`.++A `TypeError` is thrown if `baseURL` is passed and `input` is not a string.++The first pattern that matches wins, even if a later pattern is more specific:++```mjs+import { URLPattern, URLPatternList } from 'node:url';++const me = new URLPattern({ pathname: '/users/me' });+const user = new URLPattern({ pathname: '/users/:id' });++console.log(new URLPatternList([user, me]).exec({ pathname: '/users/me' })+ .pattern === user);+// Prints: true+console.log(new URLPatternList([me, user]).exec({ pathname: '/users/me' })+ .pattern === me);+// Prints: true+```++```cjs+const { URLPattern, URLPatternList } = require('node:url');++const me = new URLPattern({ pathname: '/users/me' });+const user = new URLPattern({ pathname: '/users/:id' });++console.log(new URLPatternList([user, me]).exec({ pathname: '/users/me' })+ .pattern === user);+// Prints: true+console.log(new URLPatternList([me, user]).exec({ pathname: '/users/me' })+ .pattern === me);+// Prints: true+```++#### `urlPatternList.test([input[, baseURL]])`++* `input` {string|Object} A URL string, or an object with the URL components+ to match, as accepted by [`urlPattern.test()`][]. **Default:** `{}`.+* `baseURL` {string} A base URL string used to resolve `input` when it is a+ relative URL string.+* Returns: {boolean}++Returns `true` if any pattern in the list matches `input`, and `false`+otherwise, which includes the case where `input` or `baseURL` is not a valid+URL.++A `TypeError` is thrown if `baseURL` is passed and `input` is not a string.++```mjs+import { URLPattern, URLPatternList } from 'node:url';++const list = new URLPatternList([+ new URLPattern({ pathname: '/about' }),+ new URLPattern({ pathname: '/blog/:slug' }),+]);++console.log(list.test('https://example.com/blog/hello'));+// Prints: true+console.log(list.test('/about', 'https://example.com'));+// Prints: true+console.log(list.test({ pathname: '/contact' }));+// Prints: false+```++```cjs+const { URLPattern, URLPatternList } = require('node:url');++const list = new URLPatternList([+ new URLPattern({ pathname: '/about' }),+ new URLPattern({ pathname: '/blog/:slug' }),+]);++console.log(list.test('https://example.com/blog/hello'));+// Prints: true+console.log(list.test('/about', 'https://example.com'));+// Prints: true+console.log(list.test({ pathname: '/contact' }));+// Prints: false+```+ ### Class: `URLSearchParams` <!-- YAML@@ -2103,6 +2274,7 @@ console.log(myURL.origin); [`Error`]: errors.md#class-error [`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify [`TypeError`]: errors.md#class-typeerror+[`URLPatternList`]: #class-urlpatternlist [`URLSearchParams`]: #class-urlsearchparams [`array.toString()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString [`http.request()`]: http.md#httprequestoptions-callback@@ -2118,6 +2290,8 @@ console.log(myURL.origin); [`url.search`]: #urlsearch [`url.toJSON()`]: #urltojson [`url.toString()`]: #urltostring+[`urlPattern.exec()`]: #urlpatternexecinput-baseurl+[`urlPattern.test()`]: #urlpatterntestinput-baseurl [`urlSearchParams.entries()`]: #urlsearchparamsentries [`urlSearchParamsSymbol.iterator()`]: #urlsearchparamssymboliterator [converted to a string]: https://tc39.es/ecma262/#sec-tostring@@ -2126,3 +2300,4 @@ console.log(myURL.origin); [legacy `urlObject`]: #legacy-urlobject [percent-encoded]: #percent-encoding-in-urls [stable sorting algorithm]: https://en.wikipedia.org/wiki/Sorting_algorithm#Stability+[whatwg/urlpattern#166]: https://github.com/whatwg/urlpattern/pull/166doc/type-map.json2 + / 0 −
@@ -146,6 +146,8 @@ "TransformStreamDefaultController": "webstreams.html#class-transformstreamdefaultcontroller", "TurboShakeParams": "webcrypto.html#class-turboshakeparams", "URL": "url.html#the-whatwg-url-api",+ "URLPattern": "url.html#class-urlpattern",+ "URLPatternList": "url.html#class-urlpatternlist", "URLSearchParams": "url.html#class-urlsearchparams", "Verify": "crypto.html#class-verify", "VirtualFileSystem": "vfs.html#class-virtualfilesystem",lib/url.js2 + / 1 −
@@ -35,7 +35,7 @@ const { decodeURIComponent, } = primordials; -const { URLPattern } = internalBinding('url_pattern');+const { URLPattern, URLPatternList } = internalBinding('url_pattern'); const { toASCII } = internalBinding('encoding_binding'); const { encodeStr, hexTable } = require('internal/querystring'); const querystring = require('querystring');@@ -1033,6 +1033,7 @@ module.exports = { // WHATWG API URL, URLPattern,+ URLPatternList, URLSearchParams, domainToASCII, domainToUnicode,src/env.h7 + / 0 −
@@ -1120,6 +1120,12 @@ class Environment final : public MemoryRetainer { return current_value; } + inline bool EmitURLPatternListWarning() {+ bool current_value = emit_url_pattern_list_warning_;+ emit_url_pattern_list_warning_ = false;+ return current_value;+ }+ // cb will be called as cb(env) on the next event loop iteration. // Unlike the JS setImmediate() function, nested SetImmediate() calls will // be run without returning control to the event loop, similar to nextTick().@@ -1353,6 +1359,7 @@ class Environment final : public MemoryRetainer { bool trace_sync_io_ = false; bool emit_env_nonstring_warning_ = true; bool emit_err_name_warning_ = true;+ bool emit_url_pattern_list_warning_ = true; bool source_maps_enabled_ = false; size_t async_callback_scope_depth_ = 0;src/env_properties.h2 + / 0 −
@@ -470,8 +470,10 @@ V(tlsa_record_template, v8::DictionaryTemplate) \ V(tty_constructor_template, v8::FunctionTemplate) \ V(txt_record_template, v8::DictionaryTemplate) \+ V(urlpattern_constructor_template, v8::FunctionTemplate) \ V(urlpatterncomponentresult_template, v8::DictionaryTemplate) \ V(urlpatterninit_template, v8::DictionaryTemplate) \+ V(urlpatternlistresult_template, v8::DictionaryTemplate) \ V(urlpatternresult_template, v8::DictionaryTemplate) \ V(write_wrap_template, v8::FunctionTemplate) \ V(worker_cpu_profile_taker_template, v8::ObjectTemplate) \src/node_url_pattern.cc460 + / 24 −
@@ -5,9 +5,14 @@ #include "node.h" #include "node_errors.h" #include "node_mem-inl.h"+#include "node_process.h" #include "path.h" #include "util-inl.h" +#include <iterator>+#include <span>+#include <unordered_set>+ namespace node { using node::url_pattern::URLPatternRegexProvider; @@ -56,9 +61,12 @@ using v8::Array; using v8::Context; using v8::DictionaryTemplate; using v8::DontDelete;+using v8::DontEnum;+using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Global;+using v8::HandleScope; using v8::Isolate; using v8::Local; using v8::LocalVector;@@ -71,6 +79,7 @@ using v8::ReadOnly; using v8::RegExp; using v8::Signature; using v8::String;+using v8::Symbol; using v8::Value; std::optional<URLPatternRegexProvider::regex_type>@@ -447,23 +456,48 @@ MaybeLocal<Object> URLPattern::URLPatternComponentResult::ToJSObject( MaybeLocal<Value> URLPattern::URLPatternResult::ToJSValue( Environment* env, const ada::url_pattern_result& result) {+ return ToJSValue(env, result, Local<Object>());+}++MaybeLocal<Value> URLPattern::URLPatternResult::ToJSValue(+ Environment* env,+ const ada::url_pattern_result& result,+ Local<Object> pattern) { auto isolate = env->isolate(); - auto tmpl = env->urlpatternresult_template();- if (tmpl.IsEmpty()) {- static constexpr std::string_view namesVec[] = {- "hash",- "hostname",- "inputs",- "password",- "pathname",- "port",- "protocol",- "search",- "username",- };- tmpl = DictionaryTemplate::New(isolate, namesVec);- env->set_urlpatternresult_template(tmpl);+ // Per WebIDL, the members of a dictionary are ordered lexicographically,+ // after the members of the dictionary it inherits from. The `pattern` member+ // of a URLPatternListResult therefore comes after the URLPatternResult ones.+ static constexpr std::string_view namesVec[] = {+ "hash",+ "hostname",+ "inputs",+ "password",+ "pathname",+ "port",+ "protocol",+ "search",+ "username",+ "pattern",+ };+ constexpr size_t kResultMemberCount = std::size(namesVec) - 1;++ Local<DictionaryTemplate> tmpl;+ if (pattern.IsEmpty()) {+ tmpl = env->urlpatternresult_template();+ if (tmpl.IsEmpty()) {+ tmpl = DictionaryTemplate::New(+ isolate,+ std::span<const std::string_view>(namesVec).first(+ kResultMemberCount));+ env->set_urlpatternresult_template(tmpl);+ }+ } else {+ tmpl = env->urlpatternlistresult_template();+ if (tmpl.IsEmpty()) {+ tmpl = DictionaryTemplate::New(isolate, namesVec);+ env->set_urlpatternlistresult_template(tmpl);+ } } size_t index = 0;@@ -489,8 +523,13 @@ MaybeLocal<Value> URLPattern::URLPatternResult::ToJSValue( URLPatternComponentResult::ToJSObject(env, result.port), URLPatternComponentResult::ToJSObject(env, result.protocol), URLPatternComponentResult::ToJSObject(env, result.search),- URLPatternComponentResult::ToJSObject(env, result.username)};- return NewDictionaryInstanceNullProto(env->context(), tmpl, vals);+ URLPatternComponentResult::ToJSObject(env, result.username),+ pattern};+ std::span<MaybeLocal<Value>> values(vals);+ return NewDictionaryInstanceNullProto(+ env->context(),+ tmpl,+ pattern.IsEmpty() ? values.first(kResultMemberCount) : values); } std::optional<ada::url_pattern_options>@@ -662,6 +701,363 @@ void URLPattern::HasRegexpGroups(const FunctionCallbackInfo<Value>& info) { info.GetReturnValue().Set(url_pattern->HasRegExpGroups()); } +namespace {+// Processes `input` and `base_url` as the URLPattern "match" algorithm does+// before it runs the component regular expressions, mirroring+// ada::url_pattern::match(). Returns errors::type_error where "match" throws,+// and std::nullopt where it returns null.+// https://urlpattern.spec.whatwg.org/#url-pattern-match+ada::result<std::optional<URLPatternList::Components>> ProcessMatchInput(+ const ada::url_pattern_input& input, const std::string_view* base_url) {+ URLPatternList::Components components;++ if (const auto* init = std::get_if<ada::url_pattern_init>(&input)) {+ if (base_url != nullptr) {+ return tl::unexpected(ada::errors::type_error);+ }+ auto processed =+ ada::url_pattern_init::process(*init,+ ada::url_pattern_init::process_type::url,+ "",+ "",+ "",+ "",+ "",+ "",+ "",+ "");+ if (!processed) {+ return std::nullopt;+ }+ components.protocol = std::move(processed->protocol).value_or("");+ components.username = std::move(processed->username).value_or("");+ components.password = std::move(processed->password).value_or("");+ components.hostname = std::move(processed->hostname).value_or("");+ components.port = std::move(processed->port).value_or("");+ components.pathname = std::move(processed->pathname).value_or("");+ components.search = std::move(processed->search).value_or("");+ if (components.search.starts_with('?')) {+ components.search.erase(0, 1);+ }+ components.hash = std::move(processed->hash).value_or("");+ return components;+ }++ std::optional<ada::url_aggregator> base;+ if (base_url != nullptr) {+ auto parsed_base = ada::parse<ada::url_aggregator>(*base_url, nullptr);+ if (!parsed_base) {+ return std::nullopt;+ }+ base = std::move(*parsed_base);+ }+ auto url = ada::parse<ada::url_aggregator>(std::get<std::string_view>(input),+ base ? &*base : nullptr);+ if (!url) {+ return std::nullopt;+ }++ std::string_view protocol = url->get_protocol();+ protocol.remove_suffix(1); // The trailing ':'.+ components.protocol = protocol;+ components.username = url->get_username();+ components.password = url->get_password();+ components.hostname = url->get_hostname();+ components.port = url->get_port();+ components.pathname = url->get_pathname();+ if (url->has_search()) {+ std::string_view search = url->get_search();+ if (search.starts_with('?')) search.remove_prefix(1);+ components.search = search;+ }+ if (url->has_hash()) {+ std::string_view hash = url->get_hash();+ if (hash.starts_with('#')) hash.remove_prefix(1);+ components.hash = hash;+ }+ return components;+}++// Converts `value` to a WebIDL sequence<URLPattern>. Per WebIDL, any iterable+// is read through its iterator, including arrays, and the conversion stops at+// the first value that is not a URLPattern. Returns false if a JavaScript+// exception is pending.+// https://webidl.spec.whatwg.org/#js-sequence+bool ToURLPatternSequence(Environment* env,+ Local<Value> value,+ std::vector<BaseObjectPtr<URLPattern>>* patterns) {+ static constexpr std::string_view kNotIterable =+ "The \"patterns\" argument must be an iterable of URLPattern objects";+ Isolate* isolate = env->isolate();+ Local<Context> context = env->context();++ if (!value->IsObject()) {+ THROW_ERR_INVALID_ARG_TYPE(env, kNotIterable);+ return false;+ }+ Local<Object> iterable = value.As<Object>();+ Local<Value> method;+ if (!iterable->Get(context, Symbol::GetIterator(isolate)).ToLocal(&method)) {+ return false;+ }+ if (!method->IsFunction()) {+ THROW_ERR_INVALID_ARG_TYPE(env, kNotIterable);+ return false;+ }+ Local<Value> iterator;+ if (!method.As<Function>()+ ->Call(context, iterable, 0, nullptr)+ .ToLocal(&iterator)) {+ return false;+ }+ if (!iterator->IsObject()) {+ THROW_ERR_INVALID_ARG_TYPE(env, kNotIterable);+ return false;+ }+ Local<Value> next;+ if (!iterator.As<Object>()->Get(context, env->next_string()).ToLocal(&next)) {+ return false;+ }+ if (!next->IsFunction()) {+ THROW_ERR_INVALID_ARG_TYPE(env, kNotIterable);+ return false;+ }++ while (true) {+ HandleScope handle_scope(isolate);+ Local<Value> result;+ if (!next.As<Function>()+ ->Call(context, iterator, 0, nullptr)+ .ToLocal(&result)) {+ return false;+ }+ if (!result->IsObject()) {+ THROW_ERR_INVALID_ARG_TYPE(env, kNotIterable);+ return false;+ }+ Local<Value> done;+ if (!result.As<Object>()->Get(context, env->done_string()).ToLocal(&done)) {+ return false;+ }+ if (done->BooleanValue(isolate)) {+ return true;+ }+ Local<Value> item;+ if (!result.As<Object>()+ ->Get(context, env->value_string())+ .ToLocal(&item)) {+ return false;+ }+ if (!URLPattern::HasInstance(env, item)) {+ THROW_ERR_INVALID_ARG_TYPE(+ env,+ "The \"patterns[%d]\" argument must be an instance of URLPattern",+ patterns->size());+ return false;+ }+ patterns->emplace_back(BaseObject::Unwrap<URLPattern>(item));+ }+}+} // namespace++URLPatternList::URLPatternList(+ Environment* env,+ Local<Object> object,+ std::vector<BaseObjectPtr<URLPattern>>&& patterns)+ : BaseObject(env, object), patterns_(std::move(patterns)) {+ MakeWeak();+ BuildPathnameIndex();+}++void URLPatternList::BuildPathnameIndex() {+ // ada::url_pattern_list compiles every pathname as the pathname of a URL+ // with a special scheme, with one ignore_case flag for the whole index. A+ // pattern is only indexed if its own pathname component was compiled that+ // way, so that the index and the pattern agree on which pathnames match.+ std::optional<bool> ignore_case;+ std::vector<std::string_view> pathnames;+ for (size_t i = 0; i < patterns_.size(); i++) {+ auto& pattern = patterns_[i]->url_pattern_;+ bool indexable =+ ada::url_pattern_helpers::protocol_component_matches_special_scheme(+ pattern.protocol_component);+ if (indexable) {+ if (!ignore_case.has_value()) ignore_case = pattern.ignore_case();+ indexable = pattern.ignore_case() == *ignore_case;+ }+ if (indexable) {+ indexed_patterns_.push_back(i);+ pathnames.push_back(pattern.get_pathname());+ } else {+ unindexed_patterns_.push_back(i);+ }+ }+ if (pathnames.empty()) {+ return;+ }++ ada::url_pattern_options options{.ignore_case = *ignore_case};+ auto index = ada::parse_url_pattern_list<URLPatternRegexProvider>(+ pathnames, nullptr, &options);+ if (!index) {+ // Without an index, FindMatch() tests every pattern in list order.+ indexed_patterns_.clear();+ unindexed_patterns_.clear();+ return;+ }+ pathname_index_.emplace(std::move(*index));+}++bool URLPatternList::Matches(size_t index, const Components& components) const {+ return patterns_[index]->url_pattern_.test_components(components.protocol,+ components.username,+ components.password,+ components.hostname,+ components.port,+ components.pathname,+ components.search,+ components.hash);+}++std::optional<size_t> URLPatternList::FindMatch(const Components& components,+ bool any_match) const {+ size_t end = patterns_.size();+ std::optional<size_t> match;+ if (pathname_index_.has_value()) {+ auto result = pathname_index_->match(components.pathname);+ if (!result.has_match()) {+ for (size_t index : unindexed_patterns_) {+ if (Matches(index, components)) return index;+ }+ return std::nullopt;+ }+ // The index reports the most specific matching pathname rather than the+ // first one in list order, and the rest of that pattern may not match.+ // When it does match, only the patterns before it can match first.+ size_t candidate =+ indexed_patterns_[static_cast<size_t>(result.route_index)];+ if (Matches(candidate, components)) {+ if (any_match) return candidate;+ match = candidate;+ end = candidate;+ }+ }+ for (size_t index = 0; index < end; index++) {+ if (Matches(index, components)) return index;+ }+ return match;+}++void URLPatternList::MemoryInfo(MemoryTracker* tracker) const {+ tracker->TrackField("patterns", patterns_);+ tracker->TrackField("indexed_patterns", indexed_patterns_);+ tracker->TrackField("unindexed_patterns", unindexed_patterns_);+}++void URLPatternList::New(const FunctionCallbackInfo<Value>& args) {+ Environment* env = Environment::GetCurrent(args);+ if (!args.IsConstructCall()) {+ THROW_ERR_CONSTRUCT_CALL_REQUIRED(env);+ return;+ }+ if (env->EmitURLPatternListWarning() &&+ ProcessEmitWarningGeneric(env,+ "URLPatternList is an experimental feature and "+ "might change at any time",+ "ExperimentalWarning")+ .IsNothing()) {+ return;+ }+ if (args.Length() < 1) {+ THROW_ERR_MISSING_ARGS(env, "The \"patterns\" argument must be specified");+ return;+ }++ std::vector<BaseObjectPtr<URLPattern>> patterns;+ if (!ToURLPatternSequence(env, args[0], &patterns)) {+ return;+ }++ std::unordered_set<URLPattern*> seen;+ seen.reserve(patterns.size());+ for (const auto& pattern : patterns) {+ if (!seen.insert(pattern.get()).second) {+ THROW_ERR_INVALID_ARG_VALUE(env,+ "The \"patterns\" argument must not contain "+ "the same URLPattern more than once");+ return;+ }+ }+ if (patterns.empty()) {+ THROW_ERR_INVALID_ARG_VALUE(env,+ "The \"patterns\" argument must not be empty");+ return;+ }++ new URLPatternList(env, args.This(), std::move(patterns));+}++void URLPatternList::Exec(const FunctionCallbackInfo<Value>& args) {+ URLPatternList* list;+ ASSIGN_OR_RETURN_UNWRAP(&list, args.This());+ Environment* env = Environment::GetCurrent(args);++ URLPatternMatchArgs match_args;+ if (!ParseURLPatternMatchArgs(env, args, &match_args)) return;+ std::optional<std::string_view> base_url = match_args.base_url_view();+ const std::string_view* base_url_ptr = base_url ? &*base_url : nullptr;++ auto components = ProcessMatchInput(match_args.input, base_url_ptr);+ if (!components) {+ THROW_ERR_OPERATION_FAILED(env, "Failed to exec URLPatternList");+ return;+ }+ std::optional<size_t> index;+ if (components->has_value()) {+ index = list->FindMatch(**components, false);+ }+ if (!index.has_value()) {+ args.GetReturnValue().SetNull();+ return;+ }++ URLPattern* pattern = list->patterns_[*index].get();+ auto result = pattern->url_pattern_.exec(match_args.input, base_url_ptr);+ if (!result) {+ THROW_ERR_OPERATION_FAILED(env, "Failed to exec URLPatternList");+ return;+ }+ if (!result->has_value()) {+ args.GetReturnValue().SetNull();+ return;+ }+ Local<Value> js_result;+ if (URLPattern::URLPatternResult::ToJSValue(+ env, result->value(), pattern->object())+ .ToLocal(&js_result)) {+ args.GetReturnValue().Set(js_result);+ }+}++void URLPatternList::Test(const FunctionCallbackInfo<Value>& args) {+ URLPatternList* list;+ ASSIGN_OR_RETURN_UNWRAP(&list, args.This());+ Environment* env = Environment::GetCurrent(args);++ URLPatternMatchArgs match_args;+ if (!ParseURLPatternMatchArgs(env, args, &match_args)) return;+ std::optional<std::string_view> base_url = match_args.base_url_view();++ auto components =+ ProcessMatchInput(match_args.input, base_url ? &*base_url : nullptr);+ if (!components) {+ THROW_ERR_OPERATION_FAILED(env, "Failed to test URLPatternList");+ return;+ }+ args.GetReturnValue().Set(components->has_value() &&+ list->FindMatch(**components, true).has_value());+}+ static void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(URLPattern::New); #define URL_PATTERN_COMPONENT_GETTERS(uppercase_name, _) \@@ -671,16 +1067,20 @@ static void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(URLPattern::HasRegexpGroups); registry->Register(URLPattern::Exec); registry->Register(URLPattern::Test);+ registry->Register(URLPatternList::New);+ registry->Register(URLPatternList::Exec);+ registry->Register(URLPatternList::Test); } -static void Initialize(Local<Object> target,- Local<Value> unused,- Local<Context> context,- void* priv) {- Environment* env = Environment::GetCurrent(context);+Local<FunctionTemplate> URLPattern::GetConstructorTemplate(Environment* env) {+ Local<FunctionTemplate> ctor_tmpl = env->urlpattern_constructor_template();+ if (!ctor_tmpl.IsEmpty()) {+ return ctor_tmpl;+ }+ Isolate* isolate = env->isolate(); auto attributes = static_cast<PropertyAttribute>(ReadOnly | DontDelete);- auto ctor_tmpl = NewFunctionTemplate(isolate, URLPattern::New);+ ctor_tmpl = NewFunctionTemplate(isolate, URLPattern::New); auto instance_template = ctor_tmpl->InstanceTemplate(); auto prototype_template = ctor_tmpl->PrototypeTemplate(); Local<String> url_pattern_string =@@ -718,7 +1118,43 @@ static void Initialize(Local<Object> target, SetProtoMethodNoSideEffect(isolate, ctor_tmpl, "exec", URLPattern::Exec); SetProtoMethodNoSideEffect(isolate, ctor_tmpl, "test", URLPattern::Test);- SetConstructorFunction(context, target, "URLPattern", ctor_tmpl);+ env->set_urlpattern_constructor_template(ctor_tmpl);+ return ctor_tmpl;+}++bool URLPattern::HasInstance(Environment* env, Local<Value> value) {+ return GetConstructorTemplate(env)->HasInstance(value);+}++static void Initialize(Local<Object> target,+ Local<Value> unused,+ Local<Context> context,+ void* priv) {+ Environment* env = Environment::GetCurrent(context);+ Isolate* isolate = env->isolate();++ // The template is shared by every context of the isolate and may already be+ // instantiated, so its class name is set once in GetConstructorTemplate().+ SetConstructorFunction(context,+ target,+ "URLPattern",+ URLPattern::GetConstructorTemplate(env),+ SetConstructorFunctionFlag::NONE);++ auto list_tmpl = NewFunctionTemplate(isolate, URLPatternList::New);+ // The `patterns` argument is required.+ list_tmpl->SetLength(1);+ list_tmpl->InstanceTemplate()->SetInternalFieldCount(+ URLPatternList::kInternalFieldCount);+ Local<String> url_pattern_list_string =+ FIXED_ONE_BYTE_STRING(isolate, "URLPatternList");+ list_tmpl->PrototypeTemplate()->Set(+ Symbol::GetToStringTag(isolate),+ url_pattern_list_string,+ static_cast<PropertyAttribute>(ReadOnly | DontEnum));+ SetProtoMethodNoSideEffect(isolate, list_tmpl, "test", URLPatternList::Test);+ SetProtoMethodNoSideEffect(isolate, list_tmpl, "exec", URLPatternList::Exec);+ SetConstructorFunction(context, target, url_pattern_list_string, list_tmpl); } } // namespace node::url_patternsrc/node_url_pattern.h66 + / 0 −
@@ -10,7 +10,9 @@ #include <v8.h> #include <optional>+#include <string> #include <string_view>+#include <vector> namespace node::url_pattern { @@ -48,6 +50,10 @@ class URLPattern : public BaseObject { static void New(const v8::FunctionCallbackInfo<v8::Value>& args); + static v8::Local<v8::FunctionTemplate> GetConstructorTemplate(+ Environment* env);+ static bool HasInstance(Environment* env, v8::Local<v8::Value> value);+ // V8 APIs // - Functions static void Exec(const v8::FunctionCallbackInfo<v8::Value>& info);@@ -82,6 +88,12 @@ class URLPattern : public BaseObject { public: static v8::MaybeLocal<v8::Value> ToJSValue( Environment* env, const ada::url_pattern_result& result);+ // Returns a URLPatternListResult: a URLPatternResult whose `pattern`+ // member is the URLPattern that produced `result`.+ static v8::MaybeLocal<v8::Value> ToJSValue(+ Environment* env,+ const ada::url_pattern_result& result,+ v8::Local<v8::Object> pattern); }; class URLPatternComponentResult {@@ -91,6 +103,8 @@ class URLPattern : public BaseObject { }; private:+ friend class URLPatternList;+ ada::url_pattern<URLPatternRegexProvider> url_pattern_; // Getter methods #define URL_PATTERN_COMPONENT_GETTERS(name, _) v8::MaybeLocal<v8::Value> name();@@ -112,6 +126,58 @@ class URLPattern : public BaseObject { #undef URL_PATTERN_CACHED_VALUES }; +// url.URLPatternList, which is specified in+// https://github.com/whatwg/urlpattern/pull/166. The list matches an input+// against its patterns in list order and reports the first one that matches.+class URLPatternList : public BaseObject {+ public:+ URLPatternList(Environment* env,+ v8::Local<v8::Object> object,+ std::vector<BaseObjectPtr<URLPattern>>&& patterns);++ static void New(const v8::FunctionCallbackInfo<v8::Value>& args);+ static void Exec(const v8::FunctionCallbackInfo<v8::Value>& args);+ static void Test(const v8::FunctionCallbackInfo<v8::Value>& args);++ void MemoryInfo(MemoryTracker* tracker) const override;+ SET_MEMORY_INFO_NAME(URLPatternList)+ SET_SELF_SIZE(URLPatternList)++ // The URL components that a URLPattern matches against. They are computed+ // once per test() or exec() call, as the URLPattern "match" algorithm+ // computes them before running the component regular expressions.+ struct Components {+ std::string protocol;+ std::string username;+ std::string password;+ std::string hostname;+ std::string port;+ std::string pathname;+ std::string search;+ std::string hash;+ };++ private:+ void BuildPathnameIndex();+ bool Matches(size_t index, const Components& components) const;+ // Returns the index of the first pattern that matches `components`, in list+ // order. When `any_match` is true, it may return any matching pattern.+ std::optional<size_t> FindMatch(const Components& components,+ bool any_match) const;++ std::vector<BaseObjectPtr<URLPattern>> patterns_;+ // ada::url_pattern_list is a compiled index of pathname patterns that+ // reports the most specific matching pathname, not the first pattern that+ // matches the whole URL. It is used to skip patterns that cannot match:+ // when no indexed pathname matches, no indexed pattern matches either.+ std::optional<ada::url_pattern_list<URLPatternRegexProvider>> pathname_index_;+ // Maps a route index of `pathname_index_` to a position in `patterns_`.+ std::vector<size_t> indexed_patterns_;+ // Positions in `patterns_` of the patterns that `pathname_index_` does not+ // cover. They are tested whether or not an indexed pathname matches.+ std::vector<size_t> unindexed_patterns_;+};+ } // namespace node::url_pattern #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALStest/parallel/test-urlpatternlist-experimental-warning.jsadded35 + / 0 −
@@ -0,0 +1,35 @@+'use strict';++// URLPatternList emits an ExperimentalWarning once, when it is first+// constructed. Loading node:url, reading the export, importing the ESM+// facade, which reads every export, or calling the constructor without `new`+// does not emit it.++const common = require('../common');+const assert = require('assert');++let constructed = false;+process.on('warning', common.mustCall((warning) => {+ assert.strictEqual(constructed, true);+ assert.strictEqual(warning.name, 'ExperimentalWarning');+ assert.strictEqual(+ warning.message,+ 'URLPatternList is an experimental feature and might change at any time');+}));++const { URLPattern, URLPatternList } = require('url');++import('node:url').then(common.mustCall((namespace) => {+ assert.strictEqual(namespace.URLPatternList, URLPatternList);+ assert.throws(() => URLPatternList([new URLPattern()]), {+ code: 'ERR_CONSTRUCT_CALL_REQUIRED',+ });+ setImmediate(common.mustCall(() => {+ constructed = true;+ assert.throws(() => new URLPatternList([]), {+ code: 'ERR_INVALID_ARG_VALUE',+ });+ new URLPatternList([new URLPattern()]);+ new URLPatternList([new URLPattern()]);+ }));+}));test/parallel/test-urlpatternlist-worker.jsadded34 + / 0 −
@@ -0,0 +1,34 @@+// Flags: --disable-warning=ExperimentalWarning+'use strict';++// URLPattern and URLPatternList work in a worker, which has its own isolate+// and its own copy of the URLPattern constructor template.++const common = require('../common');+const assert = require('assert');+const { URLPattern, URLPatternList } = require('url');+const { Worker } = require('worker_threads');++const list = new URLPatternList([new URLPattern({ pathname: '/main' })]);+assert.strictEqual(list.test({ pathname: '/main' }), true);++const worker = new Worker(`+ const assert = require('assert');+ const { parentPort } = require('worker_threads');+ const { URLPattern, URLPatternList } = require('url');++ const users = new URLPattern({ pathname: '/users/:id' });+ const list = new URLPatternList([users]);+ const result = list.exec('https://example.com/users/42');+ assert.strictEqual(result.pattern, users);+ assert.throws(() => new URLPatternList([{ __proto__: URLPattern.prototype }]),+ { code: 'ERR_INVALID_ARG_TYPE' });+ parentPort.postMessage(result.pathname.groups.id);+`, { eval: true, execArgv: ['--disable-warning=ExperimentalWarning'] });++worker.on('message', common.mustCall((id) => {+ assert.strictEqual(id, '42');+}));+worker.on('exit', common.mustCall((code) => {+ assert.strictEqual(code, 0);+}));test/parallel/test-urlpatternlist-wpt.jsadded89 + / 0 −
@@ -0,0 +1,89 @@+// Flags: --disable-warning=ExperimentalWarning+'use strict';++// URLPatternList is specified in terms of URLPattern: exec() returns the+// URLPattern#exec() result of the first pattern in the list that matches, and+// test() returns whether any pattern matches. This test checks that against+// every case of the URLPattern web-platform-tests.++require('../common');+const assert = require('assert');+const fixtures = require('../common/fixtures');+const fs = require('fs');+const { URLPattern, URLPatternList } = require('url');++const entries = JSON.parse(fs.readFileSync(+ fixtures.path('wpt', 'urlpattern', 'resources', 'urlpatterntestdata.json'),+ 'utf8'));++function normalize(result) {+ if (result === null) return null;+ const normalized = {};+ for (const key of Object.keys(result)) {+ const value = result[key];+ if (key === 'pattern' || key === 'inputs') {+ normalized[key] = value;+ } else {+ normalized[key] = { input: value.input, groups: { ...value.groups } };+ }+ }+ return normalized;+}++function patternExec(pattern, inputs) {+ const result = pattern.exec(...inputs);+ return result === null ? null : normalize({ ...result, pattern });+}++const patterns = [];+const cases = [];+for (const entry of entries) {+ if (entry.expected_obj === 'error') continue;+ const pattern = new URLPattern(...entry.pattern);+ patterns.push(pattern);+ if (entry.inputs !== undefined) {+ cases.push({ pattern, inputs: entry.inputs,+ constructorArgs: entry.pattern,+ throws: entry.expected_match === 'error' });+ }+}+assert.ok(cases.length > 250);++// A list of one pattern behaves like the pattern.+for (const { pattern, inputs, constructorArgs, throws } of cases) {+ const list = new URLPatternList([pattern]);+ if (throws) {+ assert.throws(() => pattern.exec(...inputs), TypeError);+ assert.throws(() => list.exec(...inputs), TypeError);+ assert.throws(() => list.test(...inputs), TypeError);+ continue;+ }+ const message =+ `new URLPattern(...${JSON.stringify(constructorArgs)}) ` ++ `with ${JSON.stringify(inputs)}`;+ assert.deepStrictEqual(normalize(list.exec(...inputs)),+ patternExec(pattern, inputs), message);+ assert.strictEqual(list.test(...inputs), pattern.test(...inputs), message);+}++// A list of every pattern finds the first one, in list order, that matches.+// The patterns have special and non-special schemes, and some of them ignore+// case, so the list mixes patterns that its pathname index covers and+// patterns that it does not.+for (const list of [patterns, patterns.toReversed()]) {+ const patternList = new URLPatternList(list);+ for (const { inputs, throws } of cases) {+ if (throws) {+ assert.throws(() => patternList.exec(...inputs), TypeError);+ assert.throws(() => patternList.test(...inputs), TypeError);+ continue;+ }+ const first = list.find((pattern) => pattern.test(...inputs));+ const message = JSON.stringify(inputs);+ assert.deepStrictEqual(normalize(patternList.exec(...inputs)),+ first ? patternExec(first, inputs) : null,+ message);+ assert.strictEqual(patternList.test(...inputs), first !== undefined,+ message);+ }+}test/parallel/test-urlpatternlist.jsadded664 + / 0 −
@@ -0,0 +1,664 @@+// Flags: --expose-gc+'use strict';++const common = require('../common');+const assert = require('assert');+const url = require('url');+const util = require('util');+const { URLPattern, URLPatternList } = url;++common.expectWarning(+ 'ExperimentalWarning',+ 'URLPatternList is an experimental feature and might change at any time',+);++// Copies a URLPatternResult or URLPatternListResult into plain objects so that+// results from different calls can be compared with assert.deepStrictEqual().+function normalize(result) {+ if (result === null) return null;+ const normalized = {};+ for (const key of Object.keys(result)) {+ const value = result[key];+ if (key === 'pattern' || key === 'inputs') {+ normalized[key] = value;+ } else {+ normalized[key] = { input: value.input, groups: { ...value.groups } };+ }+ }+ return normalized;+}++// The result that URLPatternList#exec() must return when `pattern` is the+// first pattern of the list that matches `inputs`.+function expectedResult(pattern, ...inputs) {+ const result = pattern.exec(...inputs);+ assert.notStrictEqual(result, null);+ return normalize({ ...result, pattern });+}++// Exports and interface shape.+{+ assert.strictEqual(typeof URLPatternList, 'function');+ assert.strictEqual(URLPatternList.name, 'URLPatternList');+ assert.strictEqual(URLPatternList.length, 1);+ assert.ok(Object.keys(url).includes('URLPatternList'));+ assert.strictEqual(util.URLPatternList, undefined);+ assert.strictEqual(globalThis.URLPatternList, undefined);++ assert.strictEqual(Object.getPrototypeOf(URLPatternList.prototype),+ Object.prototype);+ assert.deepStrictEqual(+ Object.getOwnPropertyDescriptor(URLPatternList.prototype, Symbol.toStringTag),+ {+ configurable: true,+ enumerable: false,+ value: 'URLPatternList',+ writable: false,+ });+ for (const name of ['test', 'exec']) {+ const descriptor =+ Object.getOwnPropertyDescriptor(URLPatternList.prototype, name);+ assert.strictEqual(typeof descriptor.value, 'function');+ assert.strictEqual(descriptor.value.name, name);+ // Both arguments are optional.+ assert.strictEqual(descriptor.value.length, 0);+ assert.strictEqual(descriptor.enumerable, true);+ assert.strictEqual(descriptor.writable, true);+ assert.strictEqual(descriptor.configurable, true);+ }++ assert.throws(() => URLPatternList([new URLPattern()]), {+ code: 'ERR_CONSTRUCT_CALL_REQUIRED',+ name: 'TypeError',+ });++ const list = new URLPatternList([new URLPattern()]);+ assert.ok(list instanceof URLPatternList);+ assert.strictEqual(Object.prototype.toString.call(list),+ '[object URLPatternList]');+ assert.deepStrictEqual(Object.keys(list), []);++ import('node:url').then(common.mustCall((namespace) => {+ assert.strictEqual(namespace.URLPatternList, URLPatternList);+ assert.strictEqual(namespace.default.URLPatternList, URLPatternList);+ }));+}++// The constructor accepts any iterable of URLPattern objects.+{+ const a = new URLPattern({ pathname: '/a' });+ const b = new URLPattern({ pathname: '/b' });+ const lists = [+ new URLPatternList([a, b]),+ new URLPatternList(new Set([a, b])),+ new URLPatternList(new Map([[a, 1], [b, 2]]).keys()),+ new URLPatternList((function*() { yield a; yield b; })()),+ new URLPatternList({ *[Symbol.iterator]() { yield a; yield b; } }),+ ];+ for (const list of lists) {+ assert.strictEqual(list.exec({ pathname: '/a' }).pattern, a);+ assert.strictEqual(list.exec({ pathname: '/b' }).pattern, b);+ assert.strictEqual(list.exec({ pathname: '/c' }), null);+ assert.strictEqual(list.test({ pathname: '/a' }), true);+ assert.strictEqual(list.test({ pathname: '/c' }), false);+ }++ // Arrays are converted with their iterator, like any other iterable.+ const array = [a];+ array[Symbol.iterator] = function*() { yield b; };+ const list = new URLPatternList(array);+ assert.strictEqual(list.test({ pathname: '/a' }), false);+ assert.strictEqual(list.exec({ pathname: '/b' }).pattern, b);+}++// The list is a snapshot of the iterable.+{+ const a = new URLPattern({ pathname: '/a' });+ const b = new URLPattern({ pathname: '/b' });+ const patterns = [a];+ const list = new URLPatternList(patterns);+ patterns[0] = b;+ patterns.push(b);+ assert.strictEqual(list.exec({ pathname: '/a' }).pattern, a);+ assert.strictEqual(list.test({ pathname: '/b' }), false);+}++// Extra constructor arguments, such as URLPattern options, are ignored.+{+ const list = new URLPatternList([new URLPattern({ pathname: '/a' })],+ { ignoreCase: true });+ assert.strictEqual(list.test({ pathname: '/a' }), true);+ assert.strictEqual(list.test({ pathname: '/A' }), false);+}++// Distinct URLPattern objects with the same pattern are not duplicates.+{+ const first = new URLPattern({ pathname: '/same' });+ const second = new URLPattern({ pathname: '/same' });+ const list = new URLPatternList([first, second]);+ assert.strictEqual(list.exec({ pathname: '/same' }).pattern, first);+}++// Constructor argument validation.+{+ const pattern = new URLPattern({ pathname: '/a' });++ assert.throws(() => new URLPatternList(), {+ code: 'ERR_MISSING_ARGS',+ name: 'TypeError',+ message: 'The "patterns" argument must be specified',+ });++ for (const value of [undefined, null, 1, true, 'https://example.com/*',+ Symbol('patterns'), {}, { [Symbol.iterator]: 1 },+ { [Symbol.iterator]() { return 1; } },+ { [Symbol.iterator]() { return {}; } },+ { [Symbol.iterator]() { return { next() { return 1; } }; } },+ new URLPattern()]) {+ assert.throws(() => new URLPatternList(value), {+ code: 'ERR_INVALID_ARG_TYPE',+ name: 'TypeError',+ message: 'The "patterns" argument must be an iterable of URLPattern ' ++ 'objects',+ });+ }++ // Values must be URLPattern objects: strings, URLPatternInit dictionaries+ // and objects that only look like a URLPattern are rejected.+ for (const value of ['/a', 'https://example.com/*', { pathname: '/a' },+ undefined, null, 1, URLPattern,+ { __proto__: URLPattern.prototype },+ new Proxy(pattern, {}),+ new URL('https://example.com/')]) {+ assert.throws(() => new URLPatternList([value]), {+ code: 'ERR_INVALID_ARG_TYPE',+ name: 'TypeError',+ message: 'The "patterns[0]" argument must be an instance of URLPattern',+ });+ assert.throws(() => new URLPatternList([pattern, value]), {+ code: 'ERR_INVALID_ARG_TYPE',+ name: 'TypeError',+ message: 'The "patterns[1]" argument must be an instance of URLPattern',+ });+ }++ // Conversion stops at the first value that is not a URLPattern.+ let yielded = 0;+ function* generate() {+ yielded++;+ yield pattern;+ yielded++;+ yield '/b';+ yielded++;+ yield new URLPattern({ pathname: '/c' });+ }+ assert.throws(() => new URLPatternList(generate()), {+ code: 'ERR_INVALID_ARG_TYPE',+ message: 'The "patterns[1]" argument must be an instance of URLPattern',+ });+ assert.strictEqual(yielded, 2);++ // The whole iterable is converted before duplicates are looked for.+ assert.throws(() => new URLPatternList([pattern, pattern, '/b']), {+ code: 'ERR_INVALID_ARG_TYPE',+ message: 'The "patterns[2]" argument must be an instance of URLPattern',+ });++ // Errors thrown while iterating are propagated.+ const error = new Error('boom');+ assert.throws(() => new URLPatternList({+ get [Symbol.iterator]() { throw error; },+ }), error);+ assert.throws(() => new URLPatternList({+ [Symbol.iterator]() { throw error; },+ }), error);+ assert.throws(() => new URLPatternList({+ [Symbol.iterator]() { return { next() { throw error; } }; },+ }), error);+ assert.throws(() => new URLPatternList({+ [Symbol.iterator]() {+ return { next() { return { done: false, get value() { throw error; } }; } };+ },+ }), error);++ // The same URLPattern object may only appear once.+ const other = new URLPattern({ pathname: '/b' });+ for (const value of [[pattern, pattern], [pattern, other, pattern],+ (function*() { yield other; yield other; })()]) {+ assert.throws(() => new URLPatternList(value), {+ code: 'ERR_INVALID_ARG_VALUE',+ name: 'TypeError',+ message: 'The "patterns" argument must not contain the same ' ++ 'URLPattern more than once',+ });+ }++ // The list may not be empty.+ for (const value of [[], new Set(), (function*() {})()]) {+ assert.throws(() => new URLPatternList(value), {+ code: 'ERR_INVALID_ARG_VALUE',+ name: 'TypeError',+ message: 'The "patterns" argument must not be empty',+ });+ }+}++// The example from https://github.com/whatwg/urlpattern/pull/166.+{+ const patterns = [+ new URLPattern('https://example.com/'),+ new URLPattern('https://example.com/about'),+ new URLPattern('https://example.com/blog/:slug'),+ new URLPattern('https://example.com/blog/:slug/comments'),+ ];+ const list = new URLPatternList(patterns);++ let result = list.exec('https://example.com/about');+ assert.strictEqual(patterns.indexOf(result.pattern), 1);++ result = list.exec('https://example.com/blog/abc');+ assert.strictEqual(patterns.indexOf(result.pattern), 2);+ assert.deepStrictEqual({ ...result.pathname.groups }, { slug: 'abc' });++ assert.strictEqual(list.test('https://example.com/imprint'), false);+ assert.strictEqual(list.test('https://example.com/about'), true);+ assert.strictEqual(list.test('https://example.com/blog/abc/comments'), true);+ assert.strictEqual(list.exec('https://example.com/imprint'), null);+}++// The first pattern that matches in list order wins, not the most specific.+{+ const me = new URLPattern({ pathname: '/users/me' });+ const id = new URLPattern({ pathname: '/users/:id' });+ const wildcard = new URLPattern({ pathname: '/users/*' });+ const input = 'https://example.com/users/me';++ assert.strictEqual(new URLPatternList([id, me]).exec(input).pattern, id);+ assert.strictEqual(new URLPatternList([me, id]).exec(input).pattern, me);+ assert.strictEqual(+ new URLPatternList([wildcard, id, me]).exec(input).pattern, wildcard);+ assert.strictEqual(+ new URLPatternList([me, wildcard, id]).exec(input).pattern, me);++ const list = new URLPatternList([me, id, wildcard]);+ assert.strictEqual(list.exec('https://example.com/users/42').pattern, id);+ assert.strictEqual(list.exec('https://example.com/users/42/posts').pattern,+ wildcard);+ assert.strictEqual(list.exec('https://example.com/users'), null);+}++// Every component takes part in matching, not only the pathname.+{+ const otherHost = new URLPattern({+ hostname: 'other.example',+ pathname: '/users/me',+ });+ const id = new URLPattern({ pathname: '/users/:id' });+ const secure = new URLPattern({ protocol: 'https', pathname: '/*' });+ const search = new URLPattern({ pathname: '/users/me', search: 'tab=:tab' });++ // `otherHost` has the most specific pathname, but a different hostname.+ let list = new URLPatternList([otherHost, id]);+ assert.strictEqual(list.exec('https://example.com/users/me').pattern, id);+ assert.strictEqual(list.exec('https://other.example/users/me').pattern,+ otherHost);++ list = new URLPatternList([id, otherHost]);+ assert.strictEqual(list.exec('https://other.example/users/me').pattern, id);++ list = new URLPatternList([secure, search, id]);+ assert.strictEqual(list.exec('https://example.com/users/me?tab=a').pattern,+ secure);+ assert.strictEqual(list.exec('http://example.com/users/me?tab=a').pattern,+ search);+ assert.strictEqual(list.exec('http://example.com/users/me?tab=a')+ .search.groups.tab, 'a');+ assert.strictEqual(list.exec('http://example.com/users/me').pattern, id);+ assert.strictEqual(list.test('http://example.com/posts'), false);+}++// exec() returns the URLPattern#exec() result of the pattern that matched,+// with a `pattern` member after the URLPatternResult members.+{+ const about = new URLPattern({ pathname: '/about' });+ const blog = new URLPattern({+ protocol: 'https',+ hostname: ':sub.example.com',+ pathname: '/blog/:slug',+ search: 'x=*',+ hash: ':hash',+ });+ const list = new URLPatternList([about, blog]);+ const input = 'https://www.example.com/blog/hello?x=1#top';++ const result = list.exec(input);+ assert.strictEqual(Object.getPrototypeOf(result), null);+ assert.deepStrictEqual(Object.keys(result), [+ 'hash',+ 'hostname',+ 'inputs',+ 'password',+ 'pathname',+ 'port',+ 'protocol',+ 'search',+ 'username',+ 'pattern',+ ]);+ assert.strictEqual(result.pattern, blog);+ assert.deepStrictEqual(result.inputs, [input]);+ assert.deepStrictEqual(normalize(result), expectedResult(blog, input));+ assert.strictEqual(result.hostname.groups.sub, 'www');+ assert.strictEqual(result.pathname.groups.slug, 'hello');+ assert.strictEqual(result.search.input, 'x=1');+ assert.strictEqual(result.hash.groups.hash, 'top');++ // Each call returns a new result object.+ assert.notStrictEqual(list.exec(input), result);++ const initResult = list.exec({ pathname: '/about' });+ assert.deepStrictEqual(initResult.inputs, [{ pathname: '/about' }]);+ assert.deepStrictEqual(normalize(initResult),+ expectedResult(about, { pathname: '/about' }));+}++// Inputs: URL strings, base URLs and URLPatternInit dictionaries.+{+ const about = new URLPattern({ pathname: '/about' });+ const blog = new URLPattern({ hostname: 'example.com', pathname: '/blog/*' });+ const list = new URLPatternList([about, blog]);++ assert.strictEqual(list.exec('/about', 'https://example.com').pattern, about);+ assert.deepStrictEqual(list.exec('/about', 'https://example.com').inputs,+ ['/about', 'https://example.com']);+ assert.strictEqual(list.exec('../blog/x', 'https://example.com/a/b').pattern,+ blog);+ assert.strictEqual(list.test('/blog/x', 'https://example.org'), false);+ assert.strictEqual(list.exec({ hostname: 'example.com', pathname: '/blog/x' })+ .pattern, blog);+ assert.strictEqual(list.exec({+ pathname: '/blog/x',+ baseURL: 'https://example.com/',+ }).pattern, blog);++ // Inputs that are not valid URLs match nothing.+ for (const args of [['not a url'], ['/about'], ['/about', 'not a url'],+ ['https://example.com:99999/about'],+ ['/about', null]]) {+ assert.strictEqual(list.test(...args), false);+ assert.strictEqual(list.exec(...args), null);+ assert.strictEqual(about.exec(...args), null);+ }+ // A URLPatternInit that cannot be processed as a URL matches nothing.+ const invalidInit = { hostname: 'exa mple.com', pathname: '/about' };+ assert.strictEqual(about.exec(invalidInit), null);+ assert.strictEqual(list.test(invalidInit), false);+ assert.strictEqual(list.exec(invalidInit), null);++ // A base URL is only allowed with a string input.+ for (const input of [{ pathname: '/about' }, {}, undefined, null]) {+ assert.throws(() => list.test(input, 'https://example.com'), {+ code: 'ERR_OPERATION_FAILED',+ name: 'TypeError',+ });+ assert.throws(() => list.exec(input, 'https://example.com'), {+ code: 'ERR_OPERATION_FAILED',+ name: 'TypeError',+ });+ }+ // An undefined base URL is the same as no base URL.+ assert.strictEqual(list.exec({ pathname: '/about' }, undefined).pattern,+ about);++ // Arguments are type checked like URLPattern#exec() and URLPattern#test().+ for (const args of [[1], [true], [Symbol('input')], ['/about', 1],+ ['/about', {}]]) {+ assert.throws(() => list.test(...args), {+ code: 'ERR_INVALID_ARG_TYPE',+ name: 'TypeError',+ });+ assert.throws(() => list.exec(...args), {+ code: 'ERR_INVALID_ARG_TYPE',+ name: 'TypeError',+ });+ }++ // Errors thrown while reading a URLPatternInit are propagated.+ const error = new Error('boom');+ const throwingInit = { get pathname() { throw error; } };+ assert.throws(() => list.test(throwingInit), error);+ assert.throws(() => list.exec(throwingInit), error);+}++// The input defaults to an empty URLPatternInit.+{+ const wildcard = new URLPattern();+ const about = new URLPattern({ pathname: '/about' });++ let list = new URLPatternList([about]);+ for (const input of [undefined, null, {}]) {+ assert.strictEqual(list.test(input), false);+ assert.strictEqual(list.exec(input), null);+ }+ assert.strictEqual(list.test(), false);+ assert.strictEqual(list.exec(), null);++ list = new URLPatternList([about, wildcard]);+ assert.strictEqual(list.test(), true);+ const result = list.exec();+ assert.strictEqual(result.pattern, wildcard);+ assert.deepStrictEqual(result.inputs, [{}]);+ assert.strictEqual(list.exec(null).pattern, wildcard);+}++// Patterns keep their own ignoreCase option, and lists may mix them.+{+ const sensitive = new URLPattern({ pathname: '/Docs/:page' });+ const insensitive = new URLPattern({ pathname: '/API/*' },+ { ignoreCase: true });++ for (const list of [new URLPatternList([sensitive, insensitive]),+ new URLPatternList([insensitive, sensitive])]) {+ assert.strictEqual(list.exec({ pathname: '/Docs/Intro' }).pattern,+ sensitive);+ assert.strictEqual(list.exec({ pathname: '/Docs/Intro' })+ .pathname.groups.page, 'Intro');+ assert.strictEqual(list.test({ pathname: '/docs/intro' }), false);+ assert.strictEqual(list.exec({ pathname: '/api/v1' }).pattern, insensitive);+ assert.strictEqual(list.exec({ pathname: '/Api/V1' }).pattern, insensitive);+ assert.strictEqual(list.exec('https://example.com/aPi/x/y').pathname.input,+ '/aPi/x/y');+ }++ const users = new URLPattern({ pathname: '/Users/:id' }, { ignoreCase: true });+ const list = new URLPatternList([users]);+ assert.strictEqual(list.exec({ pathname: '/users/AbC' }).pathname.groups.id,+ 'AbC');+}++// Patterns of URLs with non-special schemes, whose pathname has no segments.+{+ const data = new URLPattern({ protocol: 'data', pathname: 'text/plain,*' });+ const custom = new URLPattern({ protocol: 'custom', pathname: ':path' });+ const any = new URLPattern({ pathname: '/*' });+ const list = new URLPatternList([any, data, custom]);++ assert.strictEqual(list.exec('data:text/plain,hello').pattern, data);+ assert.strictEqual(list.exec('data:text/plain,hello').pathname.groups[0],+ 'hello');+ // For a non-special scheme, a named group can match across '/'.+ const result = list.exec('custom:a/b/c');+ assert.strictEqual(result.pattern, custom);+ assert.strictEqual(result.pathname.groups.path, 'a/b/c');+ assert.strictEqual(list.exec('https://example.com/x').pattern, any);+ assert.strictEqual(list.exec('custom:/a/b').pattern, any);+ assert.strictEqual(list.test('data:text/html,x'), false);++ assert.strictEqual(+ new URLPatternList([custom, any]).exec('custom:/a/b').pattern, custom);+}++// Patterns with regular expression groups and modifiers.+{+ const numeric = new URLPattern({ pathname: '/posts/(\\d+)' });+ const named = new URLPattern({ pathname: '/posts/:slug([a-z]+)' });+ const optional = new URLPattern({ pathname: '/archive/:year?' });+ const repeated = new URLPattern({ pathname: '/files/:path+' });+ const list = new URLPatternList([numeric, named, optional, repeated]);++ assert.strictEqual(list.exec({ pathname: '/posts/42' }).pattern, numeric);+ assert.strictEqual(list.exec({ pathname: '/posts/42' }).pathname.groups[0],+ '42');+ assert.strictEqual(list.exec({ pathname: '/posts/hello' }).pattern, named);+ assert.strictEqual(list.exec({ pathname: '/posts/hello' })+ .pathname.groups.slug, 'hello');+ assert.strictEqual(list.exec({ pathname: '/posts/Hello' }), null);+ assert.strictEqual(list.exec({ pathname: '/archive' }).pattern, optional);+ assert.strictEqual(list.exec({ pathname: '/archive' }).pathname.groups.year,+ undefined);+ assert.strictEqual(list.exec({ pathname: '/archive/2024' })+ .pathname.groups.year, '2024');+ assert.strictEqual(list.exec({ pathname: '/files/a/b/c' })+ .pathname.groups.path, 'a/b/c');+ assert.strictEqual(list.test({ pathname: '/files' }), false);++ for (const pathname of ['/posts/42', '/archive', '/files/a/b']) {+ const result = list.exec({ pathname });+ assert.deepStrictEqual(normalize(result),+ expectedResult(result.pattern, { pathname }));+ }+}++// Non-ASCII and percent-encoded input.+{+ const cafe = new URLPattern({ pathname: '/café/:item' });+ const wiki = new URLPattern({ pathname: '/wiki/:title' });+ const idn = new URLPattern({ hostname: 'münchen.example', pathname: '/*' });+ const emoji = new URLPattern({ pathname: '/*', hash: '🎉' });+ const list = new URLPatternList([cafe, wiki, idn, emoji]);++ let result = list.exec('https://example.com/café/latte');+ assert.strictEqual(result.pattern, cafe);+ assert.strictEqual(result.pathname.input, '/caf%C3%A9/latte');+ assert.strictEqual(result.pathname.groups.item, 'latte');+ assert.strictEqual(list.exec('https://example.com/caf%C3%A9/latte').pattern,+ cafe);++ result = list.exec('https://example.com/wiki/東京');+ assert.strictEqual(result.pattern, wiki);+ assert.strictEqual(result.pathname.groups.title, '%E6%9D%B1%E4%BA%AC');++ result = list.exec('https://münchen.example/stadt');+ assert.strictEqual(result.pattern, idn);+ assert.strictEqual(result.hostname.input, 'xn--mnchen-3ya.example');+ assert.strictEqual(list.exec('https://xn--mnchen-3ya.example/').pattern, idn);++ assert.strictEqual(list.exec('https://example.com/party#🎉').pattern, emoji);+ assert.strictEqual(list.test('https://example.com/party#🎈'), false);++ // Lone surrogates are replaced like they are by URLPattern#exec().+ const surrogate = 'https://example.com/wiki/\ud800';+ assert.deepStrictEqual(normalize(list.exec(surrogate)),+ expectedResult(wiki, surrogate));+}++// Inputs and lists beyond the sizes that the pathname index handles directly.+{+ const routes = [];+ for (let i = 0; i < 500; i++) {+ routes.push(new URLPattern({ pathname: `/items/${i}/:action` }));+ }+ const fallback = new URLPattern({ pathname: '/items/*' });+ routes.push(fallback);+ const list = new URLPatternList(routes);++ for (const i of [0, 1, 250, 499]) {+ const result = list.exec(`https://example.com/items/${i}/edit`);+ assert.strictEqual(result.pattern, routes[i]);+ assert.strictEqual(result.pathname.groups.action, 'edit');+ }+ assert.strictEqual(list.exec('https://example.com/items/500/edit').pattern,+ fallback);+ assert.strictEqual(list.exec('https://example.com/other'), null);++ const deep = `/items/${'a/'.repeat(40)}end`;+ assert.strictEqual(list.exec({ pathname: deep }).pattern, fallback);+ const long = `/items/${'x'.repeat(5000)}`;+ assert.strictEqual(list.exec({ pathname: long }).pattern, fallback);+ assert.strictEqual(list.exec({ pathname: long }).pathname.groups[0],+ 'x'.repeat(5000));+}++// Matches the URLPattern#exec() loop that the specification describes, for+// lists generated from a small vocabulary of pathname segments.+{+ const segments = ['users', 'me', 'Me', ':id', '*', '(\\d+)', ':opt?',+ 'files', ':rest+', '42'];+ const inputs = ['/', '/users', '/users/me', '/users/Me', '/users/42',+ '/users/42/files', '/files/a/b', '/me/42', '/42/42/42',+ '/users/me/files/x'];+ let seed = 1;+ function random(n) {+ seed = (seed * 1103515245 + 12345) % 2147483648;+ return seed % n;+ }++ for (let iteration = 0; iteration < 50; iteration++) {+ const patterns = [];+ const count = 1 + random(12);+ for (let i = 0; i < count; i++) {+ const length = random(4);+ let pathname = '';+ for (let j = 0; j < length; j++) {+ pathname += `/${segments[random(segments.length)]}`;+ }+ let pattern;+ try {+ pattern = new URLPattern({ pathname: pathname || '/' },+ { ignoreCase: random(4) === 0 });+ } catch {+ continue;+ }+ patterns.push(pattern);+ }+ if (patterns.length === 0) continue;++ const list = new URLPatternList(patterns);+ for (const pathname of inputs) {+ const input = `https://example.com${pathname}`;+ const first = patterns.find((pattern) => pattern.test(input));+ assert.strictEqual(list.test(input), first !== undefined);+ assert.deepStrictEqual(normalize(list.exec(input)),+ first ? expectedResult(first, input) : null);+ }+ }+}++// Methods check their receiver.+{+ const { test, exec } = URLPatternList.prototype;+ const receivers = [undefined, null, 1, 'list', {}, new URLPattern(),+ { __proto__: URLPatternList.prototype }];+ for (const receiver of receivers) {+ assert.throws(() => test.call(receiver), {+ name: 'TypeError',+ message: 'Illegal invocation',+ });+ assert.throws(() => exec.call(receiver), {+ name: 'TypeError',+ message: 'Illegal invocation',+ });+ }+}++// The list keeps its patterns alive.+{+ let list = new URLPatternList([new URLPattern({ pathname: '/kept/:id' })]);+ globalThis.gc();+ const result = list.exec({ pathname: '/kept/1' });+ assert.ok(result.pattern instanceof URLPattern);+ assert.strictEqual(result.pattern.pathname, '/kept/:id');+ assert.strictEqual(result.pathname.groups.id, '1');+ list = null;+ globalThis.gc();+}tools/nix/sharedLibDeps.nix11 + / 1 −
@@ -10,7 +10,6 @@ }: { inherit (pkgs)- ada brotli gtest libuv@@ -23,6 +22,17 @@ zlib zstd ;+ # Vendored deps/ada is 4.1.1, which provides ada::url_pattern_list.+ # TODO: remove this override once the pin we use includes ada 4.1.1.+ ada = pkgs.ada.overrideAttrs (_old: {+ version = "4.1.1";+ src = pkgs.fetchFromGitHub {+ owner = "ada-url";+ repo = "ada";+ tag = "v4.1.1";+ hash = "sha256-Rwn8bKG6PEVUMCj0Oz6/BGFRH25IoyGf1iMWvGXm4r4=";+ };+ }); abseil = pkgs.abseil-cpp; cares = pkgs.c-ares; hdr-histogram = pkgs.hdrhistogram_c;typings/internalBinding/url_pattern.d.ts8 + / 0 −
@@ -15,6 +15,14 @@ export class URLPattern { test(input: string | Record<string, string>, baseURL?: string): boolean; } +export class URLPatternList {+ constructor(patterns: Iterable<URLPattern>);++ exec(input?: string | Record<string, string> | null, baseURL?: string | null): null | Record<string, unknown>;+ test(input?: string | Record<string, string> | null, baseURL?: string | null): boolean;+}+ export interface URLPatternBinding { URLPattern: URLPattern;+ URLPatternList: URLPatternList; }