Re: [whatwg/url] Add `URL.from(object)` constructor? (Issue #782)

I actually assume the *easiest* method would be to just build a URL string from the parts, then pass it to the URL constructor. That requires the least corner-casing or refactoring, as it would use the existing spec machinery exactly as-is. It's a little bit wasteful, but what matters is just the author-observable behavior; an impl could, if they wished, implement the parsing more directly so long as it matched behavior.

This wouldn't reduce the testing effort for the feature itself, but it would substantially reduce the *unrelated* testing effort caused by spec refactoring to accommodate this. In fact, it should reduce to zero.

Thinking like:

```webidl
dictionary URLFromInit {
  required USVString protocol;
  USVString hostname;
  USVString username;
  USVString password;
  USVString port;
  (USVString or sequence<USVString>) pathname;
  (USVString or URLSearchParams) search;
  USVString hash;
};

partial interface URL {
  static URL from(URLFromInit init);
};
```

Then the algo would be (stealing directly from the URL serializer algo):

1. Let |output| be a string consisting of |protocol| concatenated with "://".
2. If |username| or |password| are present:
    1. If |username| and |password| are not *both* present, then throw a SyntaxError.
    2. Append |username| to |output|.
    3. If |password| is not the empty string, append ":" to |output|, then append |password| to |output|.
    4. Append "@" to |output|.
3. If |hostname| is present:
    1. Append |hostname|, [=serialized=], to |output|.
    2. If |port| is present, append ":" followed by |port| to |output|.
4. If |hostname| is not present, |path| is present and is a sequence of length 2 or greater, and the first item in |path| is the empty string, append "/." to |output|.
5. If |path| is present:
    1. If |path| is a DOMString, set |path| to be a list containing |path|.
    2. For each |segment| of |path|, append "/" followed by |segment| to |output|.
6. If |search| is present:
    1. If |search| is a URLSearchParams, set |search| to the serialization of |search|.
    2. Append "?", followed by |search|, to |output|.
7. If |hash| is present, append "#" followed by |hash| to |output|.
8. [Run the "new URL(url, base)" algo steps and return the result].

Sprinkle some appropriate encode steps in this and you're golden. I skipped them for brevity and because figuring out precisely where and what kind of escaping is needed is more work than I want to do for a proposal.

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/url/issues/782#issuecomment-1698084058
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/url/issues/782/1698084058@github.com>

Received on Tuesday, 29 August 2023 20:29:54 UTC