oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
71.82k stars 2.55k forks source link

Expose `URL` to bun.js #132

Closed Jarred-Sumner closed 2 years ago

Jarred-Sumner commented 2 years ago

Currently, bun.js doesn't expose URL and many libraries expect it to exist globally.

Awhile ago, I wrote a simple URL parser for bun loosely based on the WHATWG URL Standard (what browsers use)

https://github.com/Jarred-Sumner/bun/blob/74f4c8bcab092d97628e996dc89c81f76114ba37/src/url.zig#L204-L210

It is not 100% spec compliant. Specifically, it doesn't throw errors like new URL() does. It was designed for bun dev rather than for JavaScript. However, it probably is good enough for a first version.

I started to implement JavaScript bindings here: https://github.com/Jarred-Sumner/bun/blob/86a4ab704d026b984fba049c67b2e9594d0ddf65/src/javascript/jsc/webcore/url.zig#L44-L60

It would be great if a contributor could help finish it.

The easiest way to do this correctly would be to port WebKit's implementation of setters & getters. That file is here:

void URL::setPort(std::optional<uint16_t> port)
{
    if (!m_isValid)
        return;

    if (!port) {
        remove(m_hostEnd, m_portLength);
        return;
    }

    parse(makeString(
        StringView(m_string).left(m_hostEnd),
        ':',
        static_cast<unsigned>(*port),
        StringView(m_string).substring(pathStart())
    ));
}

To expose it to JavaScript, you'd add it to GlobalConstructors in here https://github.com/Jarred-Sumner/bun/blob/ce742f665aba7ae9cc5ea1838ea45b4342021a2e/src/javascript/jsc/javascript.zig#L88-L100

To write tests, you'd probably add a file like integration/bunjs-only-snippets/url.test.js and then run bun wiptest url.

It would be ideal to use some of the web platform tests for this, but running those isn't setup yet. For now, I suggest copy pasting some of the tests from here: https://github.com/web-platform-tests/wpt/blob/master/url, particularly https://github.com/web-platform-tests/wpt/blob/master/url/url-setters.any.js and then reading the json file from disk

I will probably do this in a week or two if a contributor doesn't jump in

Jarred-Sumner commented 2 years ago

Fixed in https://github.com/Jarred-Sumner/bun/commit/ed4f4ae4e29bc7a27d0eb7503401a8fbfb669470