Skip to content

Commit

Permalink
Implement URL.parse
Browse files Browse the repository at this point in the history
  • Loading branch information
jasnell committed Apr 4, 2024
1 parent 9b5650b commit 3aec968
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/workerd/api/tests/url-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9778,3 +9778,20 @@ export const urlPatternPortRegression = {
ok(!pattern.test(url));
}
};

export const urlParseStatic = {
test() {
const url = URL.parse('http://example.org');
strictEqual(url.protocol, 'http:');
strictEqual(url.host, 'example.org');

const url2 = URL.parse('foo', 'http://example.org');
strictEqual(url2.protocol, 'http:');
strictEqual(url2.host, 'example.org');
strictEqual(url2.pathname, '/foo');

// Unlike `new URL(...)` the `URL.parse(...)` function does not throw on invalid URLs
// (which is the key point)
strictEqual(URL.parse('not valid'), null);
}
};
4 changes: 2 additions & 2 deletions src/workerd/api/url-standard.c++
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
namespace workerd::api::url {

namespace {
jsg::Url parse(kj::StringPtr url, kj::Maybe<kj::StringPtr> maybeBase) {
jsg::Url parseImpl(kj::StringPtr url, kj::Maybe<kj::StringPtr> maybeBase) {
return JSG_REQUIRE_NONNULL(jsg::Url::tryParse(url, maybeBase), TypeError, "Invalid URL string.");
}
} // namespace
Expand All @@ -38,7 +38,7 @@ jsg::Ref<URL> URL::constructor(kj::String url, jsg::Optional<kj::String> base) {
base.map([](kj::String& base) { return base.asPtr(); }));
}

URL::URL(kj::StringPtr url, kj::Maybe<kj::StringPtr> base) : inner(parse(url, base)) {}
URL::URL(kj::StringPtr url, kj::Maybe<kj::StringPtr> base) : inner(parseImpl(url, base)) {}

URL::~URL() noexcept(false) {
KJ_IF_SOME(searchParams, maybeSearchParams) {
Expand Down
8 changes: 8 additions & 0 deletions src/workerd/api/url-standard.h
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,13 @@ class URL: public jsg::Object {

static jsg::Ref<URL> constructor(kj::String url, jsg::Optional<kj::String> base);

static kj::Maybe<jsg::Ref<URL>> parse(jsg::Lock& js, kj::String url, jsg::Optional<kj::String> base) {
// Method should not throw if the parse fails
return js.tryCatch([&]() -> kj::Maybe<jsg::Ref<URL>> {
return constructor(kj::mv(url), kj::mv(base));
}, [](auto) -> kj::Maybe<jsg::Ref<URL>> { return kj::none; });
}

kj::ArrayPtr<const char> getHref();
void setHref(kj::String value);

Expand Down Expand Up @@ -215,6 +222,7 @@ class URL: public jsg::Object {
JSG_METHOD_NAMED(toJSON, getHref);
JSG_METHOD_NAMED(toString, getHref);
JSG_STATIC_METHOD(canParse);
JSG_STATIC_METHOD(parse);

JSG_TS_OVERRIDE(URL {
constructor(url: string | URL, base?: string | URL);
Expand Down

0 comments on commit 3aec968

Please sign in to comment.